-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstr8ts.js
More file actions
429 lines (421 loc) · 12.3 KB
/
str8ts.js
File metadata and controls
429 lines (421 loc) · 12.3 KB
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
// Constants
const modes = { USER: 0, KNOWN: 1, BLACK: 2, BLACKKNOWN: 3 };
const colors = {
WRONG: '#b22222', SOLUTION: '#cc9900',
USER: '#003366', KNOWN: '#000000',
BUTTONDOWN: '#557055', BUTTONUP: '#8fbc8f',
WHITE: '#ffffff', BLACK: '#000000',
FIELDSELECTED: '#cfe2cf', FIELDUNSELECTED: '#ffffff'
};
const difficulties = ['Ultra', 'Sehr schwer', 'Schwer', 'Mittel', 'Leicht', 'Sehr leicht'];
const dialogs = { WELCOME: 1, GENERATED: 2, LOADING: 3, SOLUTION: 4, EMPTY: 5 };
// Variables
var starttime;
var timer = undefined;
var count = 0;
var noteMode = false;
var game;
var activeRow = undefined, activeCol = undefined;
var showSolution = false;
var actionHistory = [];
var gameCode = undefined;
var gameUrl = undefined;
var difficulty = 3;
// Element class
class Field{
constructor (row, col) {
if (col === undefined) {
this.selector = row;
} else {
this.selector = `#ce${row}${col}`;
}
this.value = undefined;
this.user = undefined;
this.notes = [];
this.mode = undefined;
this.wrong = false;
this.solution = false;
}
setUser (input) {
if (this.mode === modes.USER) {
this.wrong = false;
this.notes = [];
if (this.user === input) {
this.user = undefined;
} else {
this.user = input;
}
this.render();
}
}
setNote (value) {
if (this.mode === modes.USER) {
this.user = undefined;
if (this.notes.indexOf(value) > -1) {
this.notes.splice(this.notes.indexOf(value), 1);
} else {
this.notes.push(value);
}
this.render();
}
}
checkUser (setColor) {
if (this.mode !== modes.USER) return true;
if (!this.user) return false;
if (this.user === this.value) return true;
if (setColor) {
this.wrong = true;
this.render();
}
return false;
}
showSolution () {
this.solution = true;
this.render();
}
restart () {
this.user = undefined;
this.notes = [];
this.render();
}
copy () {
let field = new Field(this.selector);
field.mode = this.mode;
field.value = this.value;
field.user = this.user;
field.wrong = this.wrong;
field.notes = [...this.notes];
return field;
}
getElement() {
return $(this.selector);
}
reset () {
this.getElement().empty();
this.getElement().css('background-color', colors.WHITE);
}
render () {
this.getElement().empty();
if (this.mode === modes.USER) {
if (this.solution) {
if (this.user === this.value) {
this.getElement().css('color', colors.SOLUTION);
} else {
this.getElement().css('color', colors.WRONG);
}
this.getElement().text(this.value);
} else {
if (this.notes.length > 0) {
this.getElement().css('color', colors.USER);
var notes = '<table class="mini" cellspacing="0">';
for (let i = 1; i < 10; i++) {
if ((i - 1) % 3 === 0) notes += '<tr>';
if (this.notes.indexOf(i) >= 0) {
notes += `<td>${i}</td>`;
} else {
notes += `<td class="transparent">${i}</td>`;
}
if (i % 3 === 0) notes += '</tr>';
}
notes += '</table>';
this.getElement().append(notes);
} else if (this.user) {
if (this.wrong) {
this.getElement().css('color', colors.WRONG);
} else {
this.getElement().css('color', colors.USER);
}
this.getElement().text(this.user);
}
}
} else if (this.mode === modes.BLACKKNOWN) {
this.getElement().css('color', colors.WHITE);
this.getElement().css('background-color', colors.BLACK);
this.getElement().text(this.value);
} else if (this.mode === modes.KNOWN) {
this.getElement().css('background-color', colors.WHITE);
this.getElement().css('color', colors.KNOWN);
this.getElement().text(this.value);
} else {
this.getElement().css('background-color', colors.BLACK);
}
}
}
// class to store and modify the current game state
class Game {
constructor() {
this.data = [];
for (let r = 0; r < 9; r++) {
this.data.push([]);
for (let c = 0; c < 9; c++) {
this.data[r].push(new Field());
}
}
}
get(row, col) {
return this.data[row][col];
}
setValues(row, col, mode, value) {
this.data[row][col] = new Field(row, col);
this.data[row][col].mode = mode;
this.data[row][col].value = value;
this.data[row][col].render();
}
setField(field) {
const row = Number(field.selector.substring(3, 4));
const col = Number(field.selector.substring(4, 5));
this.data[row][col] = field;
this.data[row][col].render();
}
forEach (iteratorFunction) {
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
iteratorFunction(this.data[r][c], r, c);
}
}
}
}
// Button Functions
function restart () {
showDialog(false);
game.forEach(field => {
field.restart();
})
}
function toggleNoteMode () {
noteMode = !noteMode;
const color = (noteMode) ? colors.BUTTONDOWN : colors.BUTTONUP
$('#notes').css('background-color', color);
}
function check() {
count++;
$('#counter').text(count);
game.forEach(field => {
field.checkUser(setColor = true);
})
}
function solution () {
showDialog(false);
showSolution = true;
clearInterval(timer);
game.forEach(field => {
field.showSolution();
})
}
function back () {
if (actionHistory.length > 0 && !showSolution) {
const field = actionHistory.pop();
game.setField(field);
}
}
// Parse game
function parseGame (code) {
game = new Game();
const base64urlCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
var binary = '';
for (let i = 0; i < code.length; i++) {
b = base64urlCharacters.indexOf(code.charAt(i)).toString(2);
while (b.length < 6) b = '0' + b;
binary += b;
}
const encodingVersion = parseInt(binary.substring(0, 8), 2);
binary = binary.substring(8);
switch (encodingVersion) {
case 1:
if (binary.length < (6 * 81)) return; // Invalid data
for (let i = 0; i < 81; i++) {
const subBinary = binary.substring(i * 6, (i + 1) * 6);
const mode = parseInt(subBinary.substring(0, 2), 2);
const value = parseInt(subBinary.substring(2, 6), 2) + 1;
game.setValues(Math.floor(i / 9), i % 9, mode, value);
}
binary = binary.substring(6 * 81);
let counter = 0;
while (binary.length >= 7 && counter < difficulty * 3.5) {
const position = parseInt(binary.substring(0, 7), 2);
game.get(Math.floor(position / 9), position % 9).mode = modes.KNOWN;
game.get(Math.floor(position / 9), position % 9).render();
binary = binary.substring(7);
counter++;
}
break;
default:
if (binary.length < (6 * 81) || binary.length > (6 * 81 + 8)) return; // Invalid data
for (let i = 0; i < 81; i++) {
const subBinary = binary.substring(i * 6, (i + 1) * 6);
const mode = parseInt(subBinary.substring(0, 2), 2);
const value = parseInt(subBinary.substring(2, 6), 2) + 1;
game.setValues(Math.floor(i / 9), i % 9, mode, value);
}
}
}
// General Functions
function setup () {
for (let r = 0; r < 9; r++) {
var row = `<tr class="row" id="r${r}" row="${r}">`;
for (let c = 0; c < 9; c++) {
row += `<td class="cell" id="ce${r}${c}" row="${r}" col="${c}"></td>`;
}
row += '</tr>';
$('.container').append(row);
}
}
function restartTimer () {
starttime = (new Date()).getTime();
timer = setInterval(function () {
const diff = (new Date()).getTime() - starttime;
const minutes = Math.floor(diff / 60000);
const seconds = Math.round(diff / 1000 - minutes * 60);
$('#time').text(((minutes < 10) ? '0' : '') + minutes + ':' + ((seconds < 10) ? '0' : '') + seconds);
}, 1000);
}
function getURLParameter (name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
function loadNewGame () {
showDialog(dialogs.LOADING);
clearInterval(timer);
$.get(`https://luiswalter.me/str8ts/getGame?difficulty=${difficulty}`, data => {
if (data.length > 82) {
console.log('Game:', data);
gameUrl = window.location.href.split('?')[0] + '?code=' + data
gameCode = data;
showDialog(dialogs.GENERATED);
} else {
console.log(data);
loadNewGame();
}
})
}
function changeDifficulty () {
difficulty = Number($('#difficultySlider').val());
$('#difficulty').text(difficulties[difficulty]);
}
function copyGameURL () {
$('#share-game-url').val(gameUrl);
$('#share-game-url').focus();
$('#share-game-url').select();
document.execCommand('copy');
}
function startGame () {
if (gameCode && gameCode.length > 82) {
showSolution = false;
actionHistory = [];
activeCol = undefined;
activeRow = undefined;
count = 0;
$('#counter').text(count);
$('.container').removeClass('finished');
showDialog(false);
if (game) {
game.forEach(field => {
field.reset();
})
}
parseGame(gameCode);
restartTimer();
} else {
loadNewGame();
}
}
function loadNewGameAgain () {
showDialog(dialogs.WELCOME);
$('#cancelNewGame').show();
}
function showDialog (dialog) {
$('#welcome-dialog').hide();
$('#start-dialog').hide();
$('#loading-dialog').hide();
$('#solution-dialog').hide();
$('#empty-dialog').hide();
if (dialog) {
$('.dialogOuterContainer').show();
switch(dialog) {
case dialogs.LOADING:
$('#loading-dialog').show();
break;
case dialogs.WELCOME:
$('#welcome-dialog').show();
break;
case dialogs.GENERATED:
$('#start-dialog').show();
$('#share-game-url').val(gameUrl);
window.history.replaceState(null, 'Str8ts', gameUrl);
break;
case dialogs.SOLUTION:
if (!showSolution) {
$('#solution-dialog').show();
} else {
$('.dialogOuterContainer').hide();
}
break;
case dialogs.EMPTY:
if (!showSolution) {
$('#empty-dialog').show();
} else {
$('.dialogOuterContainer').hide();
}
break;
}
} else {
$('.dialogOuterContainer').hide();
}
}
$(document).ready(function(){
setup();
onResize();
const code = getURLParameter('code');
if (code && code.length > 82) {
gameUrl = window.location.href;
gameCode = code;
showDialog(dialogs.GENERATED);
} else {
showDialog(dialogs.WELCOME);
}
$('td[id^="ce"]').click(function () { // Game fields
const row = Number($(this).attr('row'));
const col = Number($(this).attr('col'));
if (!showSolution && game.get(row, col).mode == modes.USER) {
if (typeof activeRow !== 'undefined') {
game.get(activeRow, activeCol).getElement().css('background-color', colors.FIELDUNSELECTED); // Reset previously selected field
}
activeRow = row;
activeCol = col;
game.get(activeRow, activeCol).getElement().css('background-color', colors.FIELDSELECTED); // Change background of just selected field
}
})
$('td[id^="bn"]').click(function () { // Number buttons
if (!showSolution && typeof activeRow !== 'undefined' && game.get(activeRow, activeCol).mode == modes.USER) {
actionHistory.push(game.get(activeRow, activeCol).copy());
const num = Number($(this).text());
if (noteMode) {
game.get(activeRow, activeCol).setNote(num);
} else {
game.get(activeRow, activeCol).setUser(num);
let finished = true;
game.forEach(field => {
if (!field.checkUser(setColor = false)) finished = false;
})
if (finished) {
showSolution = true;
$('.container').addClass('finished');
clearInterval(timer);
}
}
}
})
})
$(window).resize(onResize);
function onResize() {
if (window.innerWidth/2 - 45 < $('.controls').position().left) { // Large screen
$('#buttons-small').hide();
$('#buttons-large').show();
$('.cell').css({ 'font-size': '22pt', 'width': '41px', 'height': '41px' });
$('.mini').css('font-size', '9pt');
} else { // Small screen
$('#buttons-small').show();
$('#buttons-large').hide();
$('.cell').css({ 'font-size': '17pt', 'width': '30px', 'height': '30px' });
$('.mini').css('font-size', '5pt');
}
}