-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.js
359 lines (307 loc) · 11.8 KB
/
game.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
const kIngameTimeFactor = 1100;
const kMotivationPerHour = 16;
const kMoneyPerHour = 4;
let priceOfNewCoworker = 35;
const nextPriceOfNewCoworker = () => Math.round(priceOfNewCoworker * 1.4);
function randomElementIn(collection) {
const index = Math.floor(Math.random() * collection.length);
return collection[index];
}
function millisecondsFromHours(hours) {
return hours * 60 * 60 * 1000;
}
class Place {
constructor(place_name, place_description, capacity) {
this.name = place_name;
this.description = place_description;
this.capacity = capacity;
}
}
const kPlaces = [
new Place(`Bar "La Licorne"`, 'Un endroit convivial mais bruyant.', 4),
new Place("Dans un local prêté par un ami", 'Un endroit pratique mais un peu austère.', 8),
new Place("À la CCI", 'Un endroit qui permet de se concentrer et aussi de se détendre.', 16),
new Place("La Capsule II", 'Les meilleures conditions, à la fois pour travailler et pour prendre une pause', 32),
];
const kCoworkerNames = [
['Alexandra Lareine', 'F'],
['Alexis Bouchouille', 'M'],
['Anthony Loyer', 'M'],
['Benjamin Dantesque', 'M'],
['Chloé Basque', 'F'],
['Christine Séjoune', 'F'],
['David Tchernia', 'M'],
['Elise Brulot', 'F'],
['Emilie Dezurich', 'F'],
['Gaël Leprince', 'M'],
['Guillaume Meunarde', 'M'],
['Julien Bruxelles', 'F'],
['Manon Facheuse', 'F'],
['Margouche Claudel', 'F'],
['Nicolas Gilette', 'M'],
['Nolwenn Tripp', 'F'],
['Paul Cluzet', 'M'],
['Philippe Brenardreau', 'M'],
['Pierre-Arnaud Brioche', 'M'],
['Pierre-Francois Berurier', 'M'],
['Pierre-Louis Labenne', 'M'],
['Pierre', 'M'],
['Sandra Maison', 'F'],
];
const kJobs = [
['Influenceur', 'Influenceuse'],
['Developpeur', 'Developpeuse'],
['Web designer', 'Web designer'],
['Architecte', 'Architecte'],
['Graphiste', 'Graphiste'],
['Illustrateur', 'Illustratrice'],
['Dessinateur', 'Dessinatrice'],
['Animateur', 'Animatrice'],
['Facilitateur', 'Facilitatrice'],
['Congierge', 'Congierge'],
['Commercial', 'Commerciale'],
['Vidéaste', 'Vidéaste'],
['Agent immobilier', 'Agent immobilier'],
['Formateur', 'Formatrice'],
['Journaliste', 'Journaliste'],
['Écrivain', 'Écrivain'],
['Négociateur', 'Négociatrice'],
['Agriculteur', 'Agricultrice'],
['Conseiller', 'Conseillère'],
['Éleveur', 'Éleveuse'],
['Éducateur', 'Éducatrice'],
];
const kJobAdjectives = [
['', ''],
["mais n'assume pas", "mais n'assume pas"],
['en developpement durable', 'en developpement durable'],
['pour mal entendants', 'pour mal entendants'],
['pour personnes âgées', 'pour personnes âgées'],
['pour animaux', 'pour animaux'],
['paysagiste', 'paysagiste'],
['des stars', 'des stars'],
['en reconversion', 'en reconversion'],
['en agencement', 'en agencement'],
['sur internet', 'sur internet'],
['en éducation', 'en éducation'],
['en conseil', 'en conseil'],
['autodidacte', 'autodidacte'],
['debutant', 'debutante'],
['confirmé', 'confirmée'],
['retraité', 'retraitée'],
['excentrique', 'excentrique'],
['farfelu', 'farfelue'],
['consultant', 'consultante'],
['à mi-temps', 'à mi-temps'],
['des temps modernes', 'des temps modernes'],
["mais rêve secrètement d'être aventurier", "mais rêve secrètement d'être aventurière"],
];
class Coworker {
constructor() {
const nameAndSex = randomElementIn(kCoworkerNames);
const sex = nameAndSex[1];
const jobTitle = randomElementIn(kJobs)[sex == 'M' ? 0 : 1];
const jobAdjective = randomElementIn(kJobAdjectives)[sex == 'M' ? 0 : 1];
this.name = nameAndSex[0];
this.job = `${jobTitle} ${jobAdjective}`;
this.motivation = 100;
this.isWorking = true;
}
motivationAsEmoji() {
const faces = ['😁', '😄', '😃', '😀', '🙂', '😕', '😟', '😰', '🥵', '☠️'].reverse();
const faceIndex = Math.round((faces.length - 1) * this.motivation / 100);
return faces[faceIndex];
}
motivationAsColor() {
if (this.motivation > 66) return '#00e100'
else if (this.motivation > 33) return '#d7cb14';
else return 'red';
}
motivationAsBattery(coworker_index) {
const bar_color = this.motivationAsColor();
return `
<div id="coworkerMotivation${coworker_index}" style="display: inline-block; position: relative; top: 4px; height: 16px; width: 50px; border: 2px solid white; border-radius: 4px; margin-right:10px;">
<div id="motivationBar${coworker_index}" style="background-color: ${bar_color}; border-radius: 2px; height: 105%; width:105%"></div>
<div style="position:absolute; top:-5px; bottom:0px; left:0px; right:0px; text-align: center;" id="lightning${coworker_index}">⚡️</div>
<div style="position:absolute; border: 2px solid white; border-radius: 2px; left:50px; top:2px; width:3px; height:8px;"></div>
</div>
`;
}
}
class Dom {
constructor() {
this.place = document.getElementById('place');
this.capacity = document.getElementById('capacity');
this.coworkers = [
document.getElementById('coworker0'),
];
this.money = document.getElementById('money');
}
}
class Game {
constructor() {
this.coworkers = [new Coworker()];
this.money = 0;
this.level = 0;
this.dom = new Dom();
this.clockMs = 0;
this.lastUpdate = performance.now();
this.refreshHtml();
}
refreshHtml() {
// Place
const place = kPlaces[this.level];
this.dom.place.innerHTML = `${place.name}. ${place.description}.`;
this.dom.capacity.innerHTML = `${this.coworkers.length}/${place.capacity}`;
// Coworkers
for (let i = 0; i < place.capacity; ++i) {
if (i < this.coworkers.length) {
const coworker = this.coworkers[i];
const buttonText = coworker.isWorking ? 'Faire une pause 🎯' : '💪 Énergisation !';
this.dom.coworkers[i].innerHTML = `
<span class="emoji" id="coworkerEmoji${i}">${coworker.motivationAsEmoji()}</span>
${coworker.motivationAsBattery(i)}
<b>${coworker.name}</b>, ${coworker.job}.
<input type="button" id="toggleCoworker${i}" value="${buttonText}" onClick="onCoworkerClicked(${i})" />`;
}
}
}
addCoworkerCliked() {
if (this.money < priceOfNewCoworker) {
okDialog("Pas assez d'argent", '', "Dommage...");
return;
}
const place = kPlaces[this.level];
if (place.capacity <= this.coworkers.length) {
okDialog("Plus de place!", "Déménagez pour augmenter la capacité");
return;
}
okCancelDialog('Ajouter un coworker', `Dépenser ${priceOfNewCoworker}€ pour obtenir un nouveau coworker?`, () => {
this.money -= priceOfNewCoworker;
priceOfNewCoworker = nextPriceOfNewCoworker();
game.renderNewCoworkerPrice();
this.coworkers.push(new Coworker());
{
const coworkers_node = document.getElementById('coworkers');
const new_coworker_node = document.createElement('p');
new_coworker_node.classList.add("person");
new_coworker_node.setAttribute("id", "coworker0");
coworkers_node.appendChild(new_coworker_node);
this.dom.coworkers.push(new_coworker_node);
// Move add_coworker node to the end of the node
const add_coworker_button = document.getElementById('add_coworker');
coworkers_node.appendChild(add_coworker_button);
const place = kPlaces[this.level];
if (place.capacity <= this.coworkers.length) {
add_coworker_button.style.display = 'none';
}
}
this.refreshHtml();
});
}
renderNewCoworkerPrice() {
document.getElementById('add_coworker').setAttribute('value', `Ajouter un coworker (${priceOfNewCoworker}€)`);
}
update(now) {
const deltaMs = now - this.lastUpdate;
const ingameDeltaMs = deltaMs * kIngameTimeFactor;
this.clockMs += ingameDeltaMs;
// Update work motivation
{
this.coworkers.forEach((worker, worker_index) => {
const is_burntout = (worker.motivation == 0);
const factor = worker.isWorking ? -1 : 3;
worker.motivation = Math.max(0, worker.motivation + factor * ingameDeltaMs * (kMotivationPerHour / (3600000)));
if (worker.motivation == 0 && !is_burntout) {
this.logEvent(`${worker.name} est en surmenage...`);
} else if (worker.motivation >= 100) {
worker.motivation = 100;
if (!worker.isWorking) {
onCoworkerClicked(worker_index); // force switch working state and update buttons and log event
}
}
});
}
// Update money won.
{
const nb_active_workers = this.coworkers.reduce((count, worker) => count + (worker.isWorking && worker.motivation > 0 ? 1 : 0), 0);
this.money += nb_active_workers * ingameDeltaMs * (kMoneyPerHour / (3600000));
}
this.lastUpdate = now;
}
render() {
{
const place = kPlaces[this.level];
const chargeSpan = document.getElementById('capacity');
chargeSpan.innerHTML = `${this.coworkers.length}/${place.capacity}`;
}
this.dom.money.innerText = Math.floor(this.money) + "€";
{
this.coworkers.forEach((coworker, i) => {
const motivationBar = document.getElementById(`motivationBar${i}`);
motivationBar.style.width = `${coworker.motivation}%`;
motivationBar.style.backgroundColor = `${coworker.motivationAsColor()}`;
const emojiSpan = document.getElementById(`coworkerEmoji${i}`);
emojiSpan.innerText = coworker.motivationAsEmoji();
const lightning = document.getElementById(`lightning${i}`);
lightning.style.display = coworker.isWorking ? 'none' : 'block';
});
}
}
logEvent(text) {
console.log(text);
}
}
var game = {};
function onCoworkerClicked(index) {
const coworker = game.coworkers[index];
game.logEvent(`${coworker.name} se ${coworker.isWorking ? 'repose' : 'remet au travail'}`);
coworker.isWorking = !coworker.isWorking;
const buttonId = `toggleCoworker${index}`;
const button = document.getElementById(buttonId);
button.setAttribute('value', coworker.isWorking ? 'Faire une pause 🎯' : '💪 Énergisation !');
button.disabled = !coworker.isWorking;
}
function onLoad() {
game = new Game();
window.game = game;
window.onCoworkerClicked = onCoworkerClicked;
{
const button = document.getElementById('add_coworker');
button.addEventListener('click', () => game.addCoworkerCliked());
game.renderNewCoworkerPrice();
}
function loop(now) {
// use the optimum way to do a game loop. See Also: https://developer.mozilla.org/en-US/docs/Games/Anatomy
window.requestAnimationFrame(loop);
game.update(now);
game.render();
}
game.render();
loop(performance.now());
}
function okDialog(title, message = '', ok_label = 'OK') {
document.querySelector('#ok_dialog form #title').textContent = title;
document.querySelector('#ok_dialog form #message').textContent = message;
document.querySelector('#ok_dialog form #ok_button').value = ok_label;
document.getElementById('ok_dialog').showModal();
}
function okCancelDialog(title, message = '', on_ok_clicked, ok_label = 'OK', cancel_label = 'Annuler') {
const ok_button = document.querySelector('#ok_cancel_dialog form #ok_button');
const cancel_button = document.querySelector('#ok_cancel_dialog form #cancel_button');
const onClose = () => {
ok_button.removeEventListener('click', onOkClicked);
};
const onOkClicked = () => {
if (on_ok_clicked && typeof (on_ok_clicked) == "function") on_ok_clicked();
onClose();
};
document.querySelector('#ok_cancel_dialog form #title').textContent = title;
document.querySelector('#ok_cancel_dialog form #message').textContent = message;
ok_button.value = ok_label;
ok_button.addEventListener('click', onOkClicked);
cancel_button.value = cancel_label;
cancel_button.addEventListener('click', onClose);
document.getElementById('ok_cancel_dialog').showModal();
}
window.addEventListener('load', onLoad);