-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
358 lines (303 loc) · 12.2 KB
/
app.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
/* Trek
* Copyright© 2002. Vedagiri Vijayakumar. All Rights Reserved.
*/
'use strict';
var AppViewModel = function () {
var self = this;
self.rows = 20;
self.cols = 3;
self.numVariables = 10;
self.literals = [];
self.gridRows = [];
self.selectedLiterals = [];
self.messageTimeout = undefined;
self.buzzerAudio = new Audio('mixkit-wrong-electricity-buzz-955.wav');
// see: https://graphicdesign.stackexchange.com/questions/3682/where-can-i-find-a-large-palette-set-of-contrasting-colors-for-coloring-many-d
self.colors = [
"#e6194B",
"#f58231",
"#ffe119",
"#bfef45",
"#3cb44b",
"#4363d8",
"#911eb4",
"#808000",
"#800000",
"#a9a9a9"
]
AppViewModel.prototype.flip = function () {
if (Math.random() < 0.5)
return true;
else
return false;
}
// generate a random int in the range (min, max) both inclusive
AppViewModel.prototype.getRandomInt = function (min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
AppViewModel.prototype.initialize = function () {
// initialize the set of literals for this game
for (let idx = 1; idx <= self.numVariables; idx++) {
/*
if (self.flip()) {
// include both
self.literals.push(idx)
self.literals.push(-idx)
} else {
if (self.flip()) {
// include only positive literal
self.literals.push(idx)
} else {
// include only negative literal
self.literals.push(idx)
}
}*/
// include both
self.literals.push(idx)
self.literals.push(-idx)
}
// add the first three rows
self.gridRows = [];
self.addRow();
self.addRow();
self.addRow();
// preload the audio
self.buzzerAudio.autoplay = false;
self.buzzerAudio.load();
}
AppViewModel.prototype.getRandomLiteral = function () {
const distinct = (value, index, thisObj) => {
return thisObj.indexOf(value) === index;
}
const arrayUnique = (array) => array.filter(distinct);
let uniqueSelectedLiterals = arrayUnique(self.selectedLiterals);
if(self.gridRows.length >= 5 && uniqueSelectedLiterals.length >= 3) {
let litIdx = self.getRandomInt(0, uniqueSelectedLiterals.length-1);
return -uniqueSelectedLiterals[litIdx];
} else {
let litIdx = self.getRandomInt(0, self.literals.length-1);
return self.literals[litIdx];
}
}
AppViewModel.prototype.addRow = function () {
let row = [];
for (let idx = 0; idx < self.cols; idx++) {
let lit;
let found;
do {
found = false;
lit = self.getRandomLiteral();
for(let idx2 = 0; idx2 < row.length; idx2++) {
if(Math.abs(row[idx2]) == Math.abs(lit)) {
found = true;
break;
}
}
} while(found);
if(!found)
row.push(lit);
}
self.gridRows.push(row);
self.selectedLiterals.push(undefined);
}
AppViewModel.prototype.getLiteralColor = function(literal) {
let variable = Math.abs(literal);
return self.colors[variable];
}
AppViewModel.prototype.showMessage = function(msgText, hapticFeedback = true) {
let msgBlock = document.getElementById('messageBlock');
msgBlock.innerText = msgText;
if(hapticFeedback)
self.hapticFeedback();
self.messageTimeout = setTimeout(function() {
msgBlock.innerText = "";
}, 1200);
}
AppViewModel.prototype.showStatus = function(msgText) {
let statusBlock = document.getElementById('statusBlock');
statusBlock.innerText = msgText;
}
AppViewModel.prototype.clearMessage = function() {
if(self.messageTimeout != undefined) {
clearTimeout(self.messageTimeout)
self.messageTimeout = undefined;
}
let msgBlock = document.getElementById('messageBlock');
msgBlock.innerText = "";
}
AppViewModel.prototype.allSelectionsDone = function() {
for(let idx = 0; idx < self.selectedLiterals.length; idx++) {
if(self.selectedLiterals[idx] == undefined) {
return false;
}
}
return true;
}
AppViewModel.prototype.getIdForButton = function(row, col) {
return `btn_${row}_${col}`;
}
AppViewModel.prototype.clearSelections = function() {
for(let idx = 0; idx < self.selectedLiterals.length; idx++) {
self.selectedLiterals[idx] = undefined;
self.display();
}
}
AppViewModel.prototype.display = function () {
// get the table node from the DOM
let gameGrid = document.getElementById("gameGrid");
// ensure that the child rows are all cleared
while (gameGrid.firstChild) {
gameGrid.firstChild.remove()
}
// render the grid by adding the rows
for (let idx = 0; idx < self.gridRows.length; idx++) {
let newRow = document.createElement("tr");
let gridRow = self.gridRows[idx];
for (let cidx = 0; cidx < self.cols; cidx++) {
let newCell = document.createElement("td");
newRow.appendChild(newCell);
// add the button
let btn = document.createElement("button");
btn.id = self.getIdForButton(idx, cidx);
let literal = gridRow[cidx];
if (literal > 0) {
btn.innerText = "⚪"; // white circle emoji "⚪" +
} else {
btn.innerText = "✖️"; // medium multiply emoji "✖️" +
}
btn.style = `background-color: ${self.getLiteralColor(literal)}`;
btn.classList.add('piece');
// show previous selection
if(self.selectedLiterals[idx] == literal) {
btn.classList.add('selected');
}
// click handler
btn.onclick = function() {
// clear the message, if any
self.clearMessage();
// check if a given selection is valid
function isValidSelectionEx(selections, literal) {
return selections.find(x => x == -literal) == undefined
}
// helper for checking if current selection is valid
function isValidSelection(selLit) {
return isValidSelectionEx(self.selectedLiterals, selLit);
}
if(self.selectedLiterals[idx] == undefined) {
// there is no prior selection
if(isValidSelection(literal)) {
self.selectedLiterals[idx] = literal;
btn.classList.toggle('selected');
} else {
// do nothing
self.showMessage(`Invalid selection`);
}
}
else {
// there is a prior selection in the row 'idx'
if(isValidSelection(literal)) {
// need to clear the other buttons in the row
for(let c = 0; c < self.cols; c++) {
let btnToClear = document.getElementById(self.getIdForButton(idx, c));
btnToClear.classList.remove('selected');
}
// make the selection for the current button
self.selectedLiterals[idx] = literal;
btn.classList.toggle('selected');
} else {
// do nothing
self.showMessage(`Invalid selection`);
}
}
if(self.allSelectionsDone()) {
// add a row only if the grid rows are less
// than the max allowed rows
if(self.gridRows.length < self.rows) {
self.addRow();
self.display();
} else {
// player wins
self.showMessage("You win!")
}
} else {
// check if all rows have been shown and if
// all possibilities in the current row lead
// to an invalid selection
if(self.gridRows.length == self.rows) {
let foundValid = false;
for(let cidx = 0; cidx < self.cols; cidx++) {
let potentialChosenLiteral = self.gridrows[cidx];
let selections = [...self.selectedLiterals, potentialChosenLiteral];
if(isValidSelection(selections, potentialChosenLiteral)) {
foundValid = true;
break;
}
}
if(!foundValid) {
self.showMessage("Do you forfeit?");
}
}
}
self.showStatus(`${self.rows - self.selectedLiterals.filter(x => x != undefined).length}`)
}
newCell.appendChild(btn);
}
gameGrid.appendChild(newRow);
}
// show the game status
self.showStatus(`${self.rows - self.selectedLiterals.filter(x => x != undefined).length}`)
}
AppViewModel.prototype.soundBuzzer = function() {
self.buzzerAudio.play().then(() => {
self.buzzerAudio.currentTime = 0;
}, (reason) => {
console.log(reason);
});
}
AppViewModel.prototype.hapticFeedback = function() {
if(navigator) {
if("vibrate" in navigator) {
navigator.vibrate(200);
}
self.soundBuzzer();
return;
} else {
// fallback
self.soundBuzzer();
}
}
return self;
};
var model = new AppViewModel();
function srcToFile(src, fileName, mimeType){
return (fetch(src)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], fileName, {type:mimeType});})
);
};
document.addEventListener("DOMContentLoaded", function (event) {
model.initialize();
model.display();
// add the event handler for clear selections
document.getElementById('linkClearSelections').addEventListener('click', function() {
model.clearSelections();
});
// add the event handler for web share
document.getElementById('linkShare').addEventListener('click', async function() {
const shareData = {
title: 'Trek',
text: 'Trek: A single-player strategy game',
url: 'https://vivegi.github.io/Trek'
};
if(navigator.canShare(shareData)) {
try {
await navigator.share(shareData);
model.showMessage('Shared successfully', false);
} catch(err) {
model.showMessage('Error: ' + err)
}
}
});
});