-
Notifications
You must be signed in to change notification settings - Fork 0
/
sudoku.js
97 lines (85 loc) · 2.22 KB
/
sudoku.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
var numSelected = null;
var tileSelected = null;
var errors = 0;
var board = [
"--74916-5",
"2---6-3-9",
"-----7-1-",
"-586----4",
"--3----9-",
"--62--187",
"9-4-7---2",
"67-83----",
"81--45---"
]
var solution = [
"387491625",
"241568379",
"569327418",
"758619234",
"123784596",
"496253187",
"934176852",
"675832941",
"812945763"
]
window.onload = function() {
setGame();
}
function setGame() {
// Digits 1-9
for (let i = 1; i <= 9; i++) {
//<div id="1" class="number">1</div>
let number = document.createElement("div");
number.id = i
number.innerText = i;
number.addEventListener("click", selectNumber);
number.classList.add("number");
document.getElementById("digits").appendChild(number);
}
// Board 9x9
for (let r = 0; r < 9; r++) {
for (let c = 0; c < 9; c++) {
let tile = document.createElement("div");
tile.id = r.toString() + "-" + c.toString();
if (board[r][c] != "-") {
tile.innerText = board[r][c];
tile.classList.add("tile-start");
}
if (r == 2 || r == 5) {
tile.classList.add("horizontal-line");
}
if (c == 2 || c == 5) {
tile.classList.add("vertical-line");
}
tile.addEventListener("click", selectTile);
tile.classList.add("tile");
document.getElementById("board").append(tile);
}
}
}
function selectNumber(){
if (numSelected != null) {
numSelected.classList.remove("number-selected");
}
numSelected = this;
numSelected.classList.add("number-selected");
}
function selectTile() {
if (numSelected) {
if (this.innerText != "") {
return;
}
// "0-0" "0-1" .. "3-1"
let coords = this.id.split("-"); //["0", "0"]
let r = parseInt(coords[0]);
let c = parseInt(coords[1]);
if (solution[r][c] == numSelected.id) {
this.innerText = numSelected.id;
}
else {
errors += 1;
document.getElementById("errors").innerText = errors;
}
}
}