-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
480 lines (300 loc) · 12.5 KB
/
script.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
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
//Procedimentos realizados quando o documento está totalmente carregado
document.addEventListener("DOMContentLoaded", () => {
let boardNumbers = generateBoardNumbers();
generateBoard(boardNumbers);
let sudoku = new Sudoku(boardNumbers);
Validator.checkBoard(sudoku);
//Recarrega a página ao clicar no botão de "recarregar", resetando o tabuleiro
document.querySelector('#btn-reset').addEventListener('click', () => {
location.reload();
});
//Ao clicar em uma célula digitável, marca ela como selecionada
document.querySelectorAll('.cell').forEach((cell) => {
cell.addEventListener('click', () => {
document.querySelectorAll('.cell').forEach((cell) => {
cell.classList.remove('selected');
});
cell.classList.add('selected');
});
});
//Ao clicar em um dos números de 1 a 9 abaixo do tabuleiro, coloca o valor clicado na célula do sudoku que
//está selecionada
document.querySelectorAll('.numbers > div').forEach(function (div) {
div.addEventListener('click', () => {
if (document.querySelector('.selected')) {
document.querySelector('.selected').innerHTML = div.innerHTML;
let row = document.querySelector('.selected').getAttribute('rowKey');
let cell = document.querySelector('.selected').getAttribute('cellKey');
boardNumbers[row][cell] = ~~div.innerHTML;
document.querySelectorAll('td').forEach(function (cell) {
if (cell.classList.contains('error')) {
cell.classList.remove('error');
}
});
sudoku = new Sudoku(boardNumbers);
Validator.checkBoard(sudoku);
}
});
});
//Ao clicar no apagador abaixo do tabuleiro, limpa a célula do sudoku que está selecionada
document.querySelector('#btn-delete').addEventListener('click', () => {
if (document.querySelector('.selected')) {
document.querySelector('.selected').innerHTML = '';
let row = document.querySelector('.selected').getAttribute('rowKey');
let cell = document.querySelector('.selected').getAttribute('cellKey');
boardNumbers[row][cell] = 0;
document.querySelectorAll('td').forEach(function (cell) {
if (cell.classList.contains('error')) {
cell.classList.remove('error');
}
});
sudoku = new Sudoku(boardNumbers);
Validator.checkBoard(sudoku);
}
});
});
class Sudoku {
constructor(boardNumbers) {
this.rows = boardNumbers;
this.columns = this.takeNumbersOfColumns();
this.blocks = this.takeNumbersOfBlocks();
}
//Retorna um array com todas as linhas do Sudoku
get rows() {
let rows = [];
this.row.forEach((row, key) => {
rows[key] = row;
});
return rows;
}
//Gera os arrays apenas com as linhas do Sudoku
set rows(boardNumbers) {
this.row = [];
boardNumbers.forEach((row, key) => {
this.row[key] = row;
});
}
//Retorna um array com todas as colunas do Sudoku
get columns() {
return [
this.firstColumn,
this.secondColumn,
this.thirdColumn,
this.fourthColumn,
this.fifthColumn,
this.sixthColumn,
this.seventhColumn,
this.eighthColumn,
this.ninthColumn
]
}
//Gera separadamente arrays referentes a cada coluna do Sudoku
set columns(numbersOfColumns) {
this.firstColumn = numbersOfColumns[0];
this.secondColumn = numbersOfColumns[1];
this.thirdColumn = numbersOfColumns[2];
this.fourthColumn = numbersOfColumns[3];
this.fifthColumn = numbersOfColumns[4];
this.sixthColumn = numbersOfColumns[5];
this.seventhColumn = numbersOfColumns[6];
this.eighthColumn = numbersOfColumns[7];
this.ninthColumn = numbersOfColumns[8];
}
//Retorna um array com todos os blocos do Sudoku
get blocks() {
return [
this.firstBlock,
this.secondBlock,
this.thirdBlock,
this.fourthBlock,
this.fifthBlock,
this.sixthBlock,
this.seventhBlock,
this.eighthBlock,
this.ninthBlock
]
}
//Cria arrays com os blocos do Sudoku baseado nas linhas da classe do Sudoku
set blocks(numbersOfBlocks) {
this.firstBlock = numbersOfBlocks.firstBlock;
this.secondBlock = numbersOfBlocks.secondBlock;
this.thirdBlock = numbersOfBlocks.thirdBlock;
this.fourthBlock = numbersOfBlocks.fourthBlock;
this.fifthBlock = numbersOfBlocks.fifthBlock;
this.sixthBlock = numbersOfBlocks.sixthBlock;
this.seventhBlock = numbersOfBlocks.seventhBlock;
this.eighthBlock = numbersOfBlocks.eighthBlock;
this.ninthBlock = numbersOfBlocks.ninthBlock;
}
//Baseado nas linhas do Sudoku, gera um array multidimensional com as colunas
takeNumbersOfColumns() {
let columns = [[], [], [], [], [], [], [], [], []];
this.rows.forEach((row) => {
columns[0].push(row[0]);
columns[1].push(row[1]);
columns[2].push(row[2]);
columns[3].push(row[3]);
columns[4].push(row[4]);
columns[5].push(row[5]);
columns[6].push(row[6]);
columns[7].push(row[7]);
columns[8].push(row[8]);
});
return columns;
}
//Retorna um objeto com os números 3 pedaços do Sudoku, baseado nas linhas informadas, para dividí-los em blocos
rowsIntoSudokuPieces(rowNumber) {
return {
firstPiece: this.rows[rowNumber].slice(0, 3),
secondPiece: this.rows[rowNumber].slice(3, 6),
thirdPiece: this.rows[rowNumber].slice(6, 9)
}
}
//Retorna um objeto com os números de cada bloco do Sudoku
takeNumbersOfBlocks() {
let firstBlock = [],
secondBlock = [],
thirdBlock = [],
fourthBlock = [],
fifthBlock = [],
sixthBlock = [],
seventhBlock = [],
eighthBlock = [],
ninthBlock = [];
for (let i = 0; i < 9; i++) {
if (i < 3) {
firstBlock.push(this.rowsIntoSudokuPieces(i).firstPiece);
secondBlock.push(this.rowsIntoSudokuPieces(i).secondPiece);
thirdBlock.push(this.rowsIntoSudokuPieces(i).thirdPiece);
}
else if (i < 6) {
fourthBlock.push(this.rowsIntoSudokuPieces(i).firstPiece);
fifthBlock.push(this.rowsIntoSudokuPieces(i).secondPiece);
sixthBlock.push(this.rowsIntoSudokuPieces(i).thirdPiece);
}
else {
seventhBlock.push(this.rowsIntoSudokuPieces(i).firstPiece);
eighthBlock.push(this.rowsIntoSudokuPieces(i).secondPiece);
ninthBlock.push(this.rowsIntoSudokuPieces(i).thirdPiece);
}
}
return {
firstBlock: firstBlock.flat(),
secondBlock: secondBlock.flat(),
thirdBlock: thirdBlock.flat(),
fourthBlock: fourthBlock.flat(),
fifthBlock: fifthBlock.flat(),
sixthBlock: sixthBlock.flat(),
seventhBlock: seventhBlock.flat(),
eighthBlock: eighthBlock.flat(),
ninthBlock: ninthBlock.flat()
}
}
}
class Validator {
static checkBoard(sudoku) {
verifyWrongCells(sudoku.rows, 'row');
verifyWrongCells(sudoku.columns, 'column');
verifyWrongCells(sudoku.blocks, 'block');
}
}
//Verifica quais células do tabuleiro estão com números incorretos e marca elas
function verifyWrongCells(arrays, sudokuElement) {
arrays.forEach((array, key) => {
if (hasRepeatedNumbers(array)) {
let values = [];
let wrongIndexes = [];
array.forEach((number) => {
let wrongNumber = _.find(values, (arrayNumber) => {
return number === arrayNumber;
});
if (wrongNumber !== 0 && wrongNumber !== undefined) {
array.forEach(function (number, key) {
if (number === wrongNumber) {
wrongIndexes.push(key);
}
});
let indexWrong = _.findIndex(array, (number) => {
return number === wrongNumber;
});
let secondIndexWrong = _.findLastIndex(array, (number) => {
return number === wrongNumber;
});
switch (sudokuElement) {
case 'block':
for (let i = 0; i < 9; i++) {
if (key === i) {
paintCells(i, indexWrong, secondIndexWrong, sudokuElement);
}
}
break;
case 'column':
paintCells(key, indexWrong, secondIndexWrong, sudokuElement);
break;
case 'row':
paintCells(key, indexWrong, secondIndexWrong, sudokuElement);
break;
default:
break;
}
}
values.push(number);
});
}
});
}
//Altera a cor das células informadas, do elemento (linha, coluna ou bloco) informado
function paintCells(element, firstIndex, secondIndex, elementCase) {
switch (elementCase) {
case 'row':
document.querySelectorAll('tr')[element].children[firstIndex].classList.add('error');
document.querySelectorAll('tr')[element].children[secondIndex].classList.add('error');
break;
case 'column':
document.querySelectorAll(`table tr > td:nth-child(${element + 1})`)[firstIndex].classList.add('error');
document.querySelectorAll(`table tr > td:nth-child(${element + 1})`)[secondIndex].classList.add('error');
break;
case 'block':
document.querySelectorAll(`.block${element}`)[firstIndex].classList.add('error');
document.querySelectorAll(`.block${element}`)[secondIndex].classList.add('error');
break;
default:
break;
}
}
//Verifica se há números repetidos no array informado
function hasRepeatedNumbers(array) {
let rowWithoutEmptyCell = _.without(array, 0);
let uniqRow = _.without(_.uniq(array), 0);
return rowWithoutEmptyCell.length !== uniqRow.length;
}
//Gera manualmente um array multidimensional com os valores aleatórios entre 0 e 9 para cada célula do Sudoku
//Valor 0 significa célula vazia no tabuleiro
function generateBoardNumbers() {
return [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9],
];
}
//Completa o tabuleiro do Sudoku baseado no array multidimensional informado
function generateBoard(boardNumbers) {
boardNumbers.forEach((row, rowKey) => {
document.querySelectorAll('tr')[rowKey].querySelectorAll('td').forEach(function (cell, cellKey) {
cell.setAttribute('rowKey', rowKey);
cell.setAttribute('cellKey', cellKey);
if (row[cellKey] !== 0) {
cell.innerHTML = row[cellKey];
cell.classList.add('blocked');
} else {
cell.classList.add('cell');
}
});
});
}