-
Notifications
You must be signed in to change notification settings - Fork 1
/
writting-simulator.html
596 lines (549 loc) · 22.7 KB
/
writting-simulator.html
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<!DOCTYPE HTML>
<html lang="es">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8">
<title>Writting simulator</title>
<style>
div,
p,
button {
font-size: 25px;
text-align: center;
}
.clickable {
cursor: pointer;
}
body {
background-color: #bbbbbb;
color: #000000;
}
table{
border-collapse: collapse;
margin-left: auto;
margin-right: auto;
}
td {
border-top: 1px solid black;
width: 60%;
text-align: left;
}
tr {
vertical-align: top;
}
</style>
</head>
<body>
<div id="menu_div">
<div><span id="play_button_span" class="clickable"></span>
</div>
<div id="language_div">
<label id="language_label" for="language"></label>
<select id="language">
<option selected value="english">English</option>
<option value="spanish">Español</option>
</select>
</div>
<div><span id="credits_button_span" class="clickable"></span>
</div>
</div>
<div id="credits_div" style="display: none;">
<div><span id="menu_button_span_from_credits" class="clickable"></span>
</div>
<br>
<table id="credits_table">
<tr>
<td id="credits_programming"></td>
<td>jmmut</td>
</tr>
<tr>
<td id="credits_art"></td>
<td>D. F. Marin<br>jmmut</td>
</tr>
<tr>
<td id="credits_design"></td>
<td>jmmut<br>D. F. Marin<br>hburriel</td>
</tr>
</table>
</div>
<div id="play_div" style="display: none;">
<div><span id="menu_button_span_from_play" class="clickable"></span>
</div>
<!-- size will be overwritten in the js side-->
<canvas id="mainCanvas" width="10" height="10" style="border:1px solid #777777;">
Your browser does not support the canvas element.
</canvas>
<div>
<span id="message_span"></span>
</div>
</div>
<canvas id="writingPage" width="10" height="10" style="display: none; border:1px solid #777777;">
Your browser does not support the canvas element.
</canvas>
<!-- <img id="img_typewriter" style="display: none;" width="853" height="480" src="assets/writ/graphics/img_typewriter_off.png"> -->
<img id="img_typewriter_off" style="display: none;" src="assets/writ/graphics/img_typewriter_off.png">
<img id="img_typewriter_on" style="display: none;" src="assets/writ/graphics/img_typewriter_on.png">
<img id="img_shelf_off" style="display: none;" src="assets/writ/graphics/img_shelf_off.jpg">
<img id="img_shelf_on" style="display: none;" src="assets/writ/graphics/img_shelf_on.jpg">
<img id="img_window_off" style="display: none;" src="assets/writ/graphics/img_window_off.jpg">
<img id="img_window_on" style="display: none;" src="assets/writ/graphics/img_window_on.jpg">
<img id="img_landscape_off" style="display: none;" src="assets/writ/graphics/img_landscape_off.png">
<img id="img_landscape_on" style="display: none;" src="assets/writ/graphics/img_landscape_on.png">
<img id="img_park_on" style="display: none;" src="assets/writ/graphics/img_park_on.png">
<img id="img_park_off" style="display: none;" src="assets/writ/graphics/img_park_off.png">
<img id="img_trees_on" style="display: none;" src="assets/writ/graphics/img_trees_on.png">
<img id="img_trees_off" style="display: none;" src="assets/writ/graphics/img_trees_off.png">
<img id="img_mainRoom_off" style="display: none;" src="assets/writ/graphics/img_landscape_off.png">
<img id="img_mainRoom_on" style="display: none;" src="assets/writ/graphics/img_landscape_on.png">
<script>
// these global variables shouldn't change, and as they are actually constants,
// that's my excuse to not pass them explicitly to most of the functions.
const unsortedAreas = [
{
name: "shelf", room: "mainRoom", isRoom: false, layer: 50
, size: { posX: 0.24, posY: 0.37, width: 0.087, height: 0.21 }
, imgSize: { posX: 0.0, posY: 0.0, width: 0.5, height: 1.0 }
},
{
name: "typewriter", room: "mainRoom", isRoom: false, layer: 30
, size: { posX: 0.31, posY: 5 / 8.0, width: 0.28, height: 5 / 8.0 }
, imgSize: {posX: 1 / 8.0, posY: 0.5, width: 5 / 8.0, height: 0.5 }
},
{
name: "window", room: "mainRoom", isRoom: true, layer: 50
, size: { posX: 0.56, posY: 0, width: 0.38, height: 0.66 }
, imgSize: { posX: 0.5, posY: 0.0, width: 0.5, height: 1.0 }
},
{
name: "landscape", room: "window", isRoom: false, isBackground: true, layer: 50
, size: { posX: 0, posY: 0, width: 1, height: 1 }
, imgSize: { posX: 0, posY: 0, width: 1, height: 1 }
},
{
name: "trees", room: "window", isRoom: false, layer: 40
, size: { posX: 1-0.2360679774997897, posY: 0.2360679774997897, width: 0.2360679774997897, height: 0.38196601125010515 }
, imgSize: {posX: 0.6627, posY: 0, width: 0.337, height: 1-0.14589803375031543}
},
{
name: "park", room: "window", isRoom: false, layer: 40
, size: { posX: 0.14589803375031543, posY: 0.38196601125010515, width: 0.38196601125010515, height: 0.2360679774997897 }
, imgSize: {posX: 0, posY: 0, width: 0.55, height: 1-0.14589803375031543}
},
{
name: "mainRoom", room: "window", isRoom: true, layer: 50
, size: { posX: 0, posY: 1-0.14589803375031543, width: 1, height: 0.14589803375031543 }
, imgSize: {posX: 0, posY: 0, width: 1, height: 1}
}
];
const ui = { posX: 23 / 32.0, posY: 0.75, width: 4 / 16.0, height: 3 / 16.0 };
const areas = unsortedAreas.sort((a, b) => compare(b.layer, a.layer));
function compare(a, b) {
if (a < b) {
return -1;
} else {
if (a > b) {
return 1;
} else {
return 0;
}
}
}
/**
* The sizes above are coefficients in [0, 1], so this helper multiplies by the actual size in pixels
*/
function getButtonSize(button, canvasSize) {
return {
posX: canvasSize.width * button.posX, posY: canvasSize.height * button.posY,
width: canvasSize.width * button.width, height: canvasSize.height * button.height
};
}
function addListener(dom_id, event_type, callback) {
let elem = document.getElementById(dom_id)
elem.addEventListener(event_type, event => { callback(event); });
}
addListener("play_button_span", "click", showPlay);
addListener("credits_button_span", "click", showCredits);
addListener("menu_button_span_from_credits", "click", showMainMenu);
addListener("menu_button_span_from_play", "click", showMainMenu);
function showView(viewToShow) {
const views = ["credits_div", "menu_div", "play_div"];
for (view of views) {
document.getElementById(view).style.display = view === viewToShow ? null : "none";
}
}
function showCredits(event) {
showView("credits_div");
}
function showMainMenu(event) {
showView("menu_div");
}
function showPlay(event) {
showView("play_div");
mainGameLoop();
}
const languages = {
available: {
english: {
language: "Language: ", inspiration: "Inspiration: ", progress: "Progress: ", pages: "Pages: ",
credits: "Credits", programming: "Programming: ", art: "Art: ", design: "Design: ",
play: "Play", menu: "Main menu",
messages: {
0: "",
1: "What are my sources of inspiration?",
2: "Am I enjoying this?",
"ending": "I'd rather be doing something else, but what?"
}
},
spanish: {
language: "Idioma: ", inspiration: "Inspiración: ", progress: "Progreso: ", pages: "Páginas: ",
credits: "Créditos", programming: "Programación: ", art: "Arte: ", design: "Diseño: ",
play: "Jugar", menu: "Menú principal",
messages: {
0: "",
1: "¿Cuáles son mis fuentes de inspiración?",
2: "¿Estoy disfrutando esto?",
"ending": "Preferiría estar haciendo otras cosas, pero ¿cuáles?"
}
}
}
};
const mainCanvas = document.getElementById("mainCanvas");
const mainCtx = mainCanvas.getContext("2d");
mainCtx.imageSmoothingEnabled = false;
mainCanvas.height = 480;
mainCanvas.width = mainCanvas.height * 16 / 9.0; // panoramic 16:9
const pageHeight = mainCanvas.height * 3 / 4.0
const pageSize = {
height: pageHeight,
width: pageHeight * 210 / 297.0, // paper proportions: A4
posY: mainCanvas.height / 8.0,
posX: mainCanvas.width / 16.0,
};
const pageCanvas = document.getElementById("writingPage");
const gameState = {
room: "mainRoom", areaHighlighted: null, areaChanged: false,
writing: false, inspiration: 0.5, progress: 0.0, pages: 0, numberOfLetters: 0
}
mainCanvas.addEventListener('click', event => { onClick(event, gameState); });
mainCanvas.addEventListener('mousemove', event => { onMouseMove(event, gameState); });
test();
function changeLanguage(event) {
console.log("changing language to " + event.target.value);
languages.selected = languages.available[event.target.value];
document.getElementById("language_label").innerText = languages.selected.language;
document.getElementById("credits_button_span").innerText = languages.selected.credits;
document.getElementById("play_button_span").innerText = languages.selected.play;
document.getElementById("menu_button_span_from_play").innerText = languages.selected.menu;
document.getElementById("menu_button_span_from_credits").innerText = languages.selected.menu;
document.getElementById("credits_programming").innerText = languages.selected.programming;
document.getElementById("credits_art").innerText = languages.selected.art;
document.getElementById("credits_design").innerText = languages.selected.design;
updateMessageOnPageCompleted(gameState.pages);
};
changeLanguage({ target: {value: "english" }})
addListener("language", "change", changeLanguage);
function mainGameLoop() {
drawRoom(gameState, mainCanvas);
if (gameState.writing) {
mainCtx.drawImage(pageCanvas, pageSize.posX, pageSize.posY);
}
}
function onClick(event, gameState) {
const x = event.pageX - mainCanvas.offsetLeft;
const y = event.pageY - mainCanvas.offsetTop;
console.log("in click event. x: " + x + ", y: " + y);
const needRedraw = updateGameStateFromClick(gameState, x, y);
drawRoom(gameState, mainCanvas);
if (gameState.writing) {
const pageComplete = drawPage(pageCanvas, pageSize, gameState.numberOfLetters);
mainCtx.drawImage(pageCanvas, pageSize.posX, pageSize.posY);
if (pageComplete) {
gameState.numberOfLetters = 0;
gameState.pages++;
console.log("page completed");
updateMessageOnPageCompleted(gameState.pages);
}
}
}
function updateMessageOnPageCompleted(numPages) {
span = document.getElementById("message_span");
const messages = languages.selected.messages;
span.innerText = (messages[numPages] !== undefined? messages[numPages] : messages["ending"]);
}
/**
* this function only changes game state, doesn't draw anything
* @return whether we need a redraw.
*/
function updateGameStateFromClick(gameState, clickX, clickY) {
if (gameState.writing) {
if (isInside(clickX, clickY, pageSize)) {
if (gameState.inspiration > 0) {
console.log("adding words");
gameState.inspiration = Math.max(gameState.inspiration - 1 / 16.0, 0);
++gameState.numberOfLetters;
}
} else {
gameState.writing = false;
console.log("stopped writing");
updateGameStateFromMouseMove(gameState, clickX, clickY);
}
} else {
for (const area of areas) {
if (gameState.room === area.room) {
if (isInside(clickX, clickY, getButtonSize(area.size, mainCanvas))) {
console.log("clicked on " + area.name);
if (area.name === "typewriter") {
console.log("starting writing");
gameState.writing = true;
} else if (area.isRoom) {
console.log("moving to room " + area.name);
gameState.room = area.name;
updateGameStateFromMouseMove(gameState, clickX, clickY);
} else if (!area.isBackground) {
console.log("getting inspiration");
// TODO: diminishing returns when spamming the same source of inspiration
gameState.inspiration = Math.min(gameState.inspiration + 1 / 16.0, 1);
}
}
}
}
}
}
function isInside(pointX, pointY, { posX, posY, width, height }) {
return pointX >= posX && pointX <= (posX + width)
&& pointY >= posY && pointY <= (posY + height);
}
function drawRoom(gameState, canvas) {
console.log("draw room")
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
for (const area of areas) {
if (area.room === gameState.room) {
const imgName = area.name;
const areaHighlighted = gameState.areaHighlighted? gameState.areaHighlighted : null;
const areaHighlightedName = areaHighlighted? areaHighlighted.name : null;
const img = document.getElementById("img_" + imgName + (area.name === areaHighlightedName? "_on" : "_off"));
if (img === undefined || area.imgSize === undefined) {
console.log("missing image for " + imgName);
const size = getButtonSize(area.size, mainCanvas);
//mainCtx.fillStyle = "#bbbbbb";
//// mainCtx.fillRect(size.posX, size.posY, size.width, size.height);
//mainCtx.fillStyle = "#000000";
//mainCtx.strokeRect(size.posX, size.posY, size.width, size.height);
//mainCtx.font = "20px Georgia";
//mainCtx.fillText(area.name, size.posX, size.posY + size.height / 2.0);
} else {
const imgSize = getButtonSize(area.imgSize, canvas);
ctx.drawImage(img, imgSize.posX, imgSize.posY, imgSize.width, imgSize.height);
}
}
}
if (gameState.writing) {
ctx.fillStyle = "#77777777";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const uiPos = getButtonSize(ui, canvas);
ctx.font = "20px Georgia";
ctx.fillStyle = "#bbbbbbbb";
ctx.fillRect(uiPos.posX, uiPos.posY, uiPos.width, uiPos.height);
ctx.fillStyle = "#000000";
const leftMargin = 0.1 * uiPos.width;
ctx.fillText(languages.selected.inspiration + (gameState.inspiration * 100).toFixed(0) + ' %',
uiPos.posX + leftMargin, uiPos.posY + 0.4 * uiPos.height);
// TODO: how to do a newline in the drawn text??
// ctx.fillText(languages.selected.progress + gameState.progress.toFixed(2), uiPos.posX, uiPos.posY + uiPos.height);
ctx.fillText(languages.selected.pages + gameState.pages, uiPos.posX + leftMargin, uiPos.posY + 0.8 * uiPos.height);
}
function onMouseMove(event, gameState) {
updateGameStateFromMouseMove(
gameState,
event.pageX - mainCanvas.offsetLeft,
event.pageY - mainCanvas.offsetTop);
if (!gameState.writing && gameState.areaChanged) {
console.log("mouseMove redraw")
drawRoom(gameState, mainCanvas);
}
}
function updateGameStateFromMouseMove(gameState, mousePosX, mousePosY) {
if (!gameState.writing) {
const xCoef = mousePosX / mainCanvas.width;
const yCoef = mousePosY / mainCanvas.height;
//console.log("in click move event. xCoef: " + xCoef + ", yCoef: " + yCoef);
const newPointing = is_the_mouse_over_any_element(gameState, xCoef, yCoef);
gameState.areaChanged = gameState.areaHighlighted !== newPointing;
if (gameState.areaChanged) {
const we_moved_out_of_an_element = gameState.areaHighlighted !== null;
const we_have_not_moved_to_another_room =
gameState.room === (gameState.areaHighlighted ? gameState.areaHighlighted.room : null);
if (we_moved_out_of_an_element) {
console.log("moving out of " + gameState.areaHighlighted.name);
mainCanvas.style.cursor = "default";
}
const we_moved_into_an_element = newPointing !== null;
if (we_moved_into_an_element) {
console.log("moving into " + newPointing.name);
mainCanvas.style.cursor = "pointer";
}
}
gameState.areaHighlighted = newPointing;
}
}
function is_the_mouse_over_any_element(gameState, xCoef, yCoef) {
let anyPointing = null;
for (const area of areas) {
if (!area.isBackground) {
if (gameState.room === area.room) {
if (isInside(xCoef, yCoef, area.size)) {
anyPointing = area;
}
}
}
}
return anyPointing;
}
/**
* returns true if the page was completed, false otherwise
*/
function drawPage(canvas, { width, height }, numberOfLetters = -1) {
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "#eeeeee";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#888888";
const verticalMargin = canvas.width / 12.0;
const horizontalMargin = canvas.height / 12.0;
const letterWidth = horizontalMargin * 1.25;
const letterHeight = letterWidth / 1.618;
const letterVertSpacing = letterHeight / 2.0;
const letterHorSpacing = letterWidth / 2.0;
let posX = horizontalMargin;
let posY = verticalMargin;
const moveToNewLine = bakeMoveToNewLine(horizontalMargin, letterHeight, letterVertSpacing);
let pageComplete = false;
for (rectangleOrCircle of rectangleOrCircleGenerator(numberOfLetters)) {
if (wouldWriteOutsideHorizontally(posX, canvas.width, letterWidth, horizontalMargin)) {
[posX, posY] = moveToNewLine(posX, posY);
}
if (wouldWriteOutsideVertically(posY, canvas.height, letterHeight, verticalMargin)) {
pageComplete = true;
break;
}
if (rectangleOrCircle) {
posX = drawRectangle(ctx, posX, posY, letterWidth, letterHeight, letterHorSpacing);
} else {
posX = drawCircle(ctx, posX, posY, letterHeight / 2.0, letterHorSpacing);
}
}
return pageComplete;
}
/**
* ctx: obtain from
* `const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d");`
*/
function drawRectangle(ctx, posX, posY, width, height, horizontalSpacing) {
ctx.fillRect(posX, posY, width, height);
posX += width + horizontalSpacing;
return posX;
}
/**
* ctx: obtain from
* `const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d");`
* posX, posY: coordinates of the top left corner of a square circumscribing the circle.
*/
function drawCircle(ctx, posX, posY, radius, horizontalSpacing) {
ctx.beginPath();
ctx.arc(posX + radius, posY + radius, radius, 0, 2 * Math.PI);
ctx.fill();
posX += radius * 2 + horizontalSpacing;
return posX;
}
/**
* Note the inner function returns an array to be able to use destructuring assignment:
* `[posX, posY] = moveToNewLine(posX, posY);`
*/
function bakeMoveToNewLine(horizontalMargin, letterHeight, letterVertSpacing) {
return (posX, posY) => {
return [horizontalMargin, posY + letterHeight + letterVertSpacing];
}
}
/**
* Note that without arguments this will give an infinite sequence.
* User code is expected to break the loop or provide a finite count.
*/
function* rectangleOrCircleGenerator(count = -1) {
let i = 0;
while (i != count) {
yield Math.random() < 0.5;
i++;
}
}
function wouldWriteOutsideVertically(posY, canvasHeight, letterHeight, bottomMargin) {
return (posY + letterHeight + bottomMargin) > canvasHeight;
}
function wouldWriteOutsideHorizontally(posX, canvasWidth, letterWidth, rightMargin) {
return (posX + letterWidth + rightMargin) > canvasWidth;
}
function test(options = {}) {
let failedAssertions = 0;
let totalAssertions = 0;
console.log("Starting tests...");
function assertEquals(name, actual, expected) {
totalAssertions++;
if (actual !== expected) {
let assertionLocation = name;
if (!options.disableLineNumbers) {
function getCallerLineNumber() {
try { throw Error('') } catch (err) {
const callerLine = err.stack.split("\n")[2].split(":");
const lineNumber = callerLine[callerLine.length - 2];
return lineNumber;
}
}
assertionLocation += " at line " + getCallerLineNumber();
}
console.log("Failed test [" + assertionLocation + "]: expected " + expected
+ " but got " + actual);
failedAssertions++;
}
}
{
let shapes = 0;
const expectedShapes = 3;
for (rectangleOrCircle of rectangleOrCircleGenerator(expectedShapes)) {
shapes++;
}
assertEquals("limited rectangleOrCircleGenerator", shapes, expectedShapes);
}
{
let shapes = 0;
const expectedShapes = 3;
for (rectangleOrCircle of rectangleOrCircleGenerator()) {
shapes++;
if (shapes >= expectedShapes) {
break;
}
}
assertEquals("infinite rectangleOrCircleGenerator", shapes, expectedShapes);
}
/* //this doesn't work:
{
const size = {
height: 1,
width: this.height * 2
};
assertEquals("refer to other fields during construction", size.width, size.height * 2);
}
*/
{
assertEquals("isInside", isInside(10, 20, { posX: 0, posY: 0, width: 50, height: 50 }), true);
assertEquals("isInside", isInside(10, 20, { posX: 10, posY: 0, width: 50, height: 50 }), true);
assertEquals("isInside", isInside(10, 20, { posX: 10, posY: 20, width: 50, height: 50 }), true);
assertEquals("isInside", isInside(10, 20, { posX: 20, posY: 10, width: 50, height: 50 }), false);
assertEquals("isInside", isInside(10, 20, { posX: 10, posY: 30, width: 50, height: 50 }), false);
}
console.log("Finished tests. Number of failed assertions: " + failedAssertions + "/" + totalAssertions);
}
</script>
</body>