Repository navigation
Expand file tree
/
Copy pathGame.js
More file actions
109 lines (88 loc) · 2.71 KB
/
Copy pathGame.js
File metadata and controls
109 lines (88 loc) · 2.71 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
window.onload = function initpage() {
"use strict";
var table = document.getElementById("puzzle");
var cells = table.getElementsByTagName("td");
for (var i=0; i<cells.length; i++) {
cells[i].onclick = tileClick;
}
}
function swapTiles (selectedCell,destinationCell) {
selectedImage = selectedCell.firstChild;
while (selectedImage.nodeName=="#text")
selectedImage = selectedImage.nextSibling;
destinationImage = destinationCell.firstChild;
while (destinationImage.nodeName=="#text")
destinationImage = destinationImage.nextSibling;
selectedCell.appendChild(destinationImage);
destinationCell.appendChild(selectedImage);
if (puzzleIsComplete()) {
alert("You win!");
}
}
function cellIsEmpty (cell) {
var image = cell.firstChild;
while (image.nodeName=="#text") {
image = image.nextSibling;
}
if (image.alt=="empty")
return true;
else
return false;
}
var tileOrder;
function puzzleIsComplete () {
var tiles = document.getElementsByTagName("img");
tileOrder = "";
for (var i=0;i<tiles.length; i++) {
var num = tiles[i].src.substr(-6,2);
if (num!="ty")
tileOrder+=num;
}
if (tileOrder=="010203")
return true;
return false;
}
function tileClick () {
if(cellIsEmpty(this)) {
alert("Click on a non-empty cell.");
return;
}
var currentRow = this.id.charAt(4);
var currentCol = this.id.charAt(5);
if (currentRow>0) {
var testRow = Number(currentRow) - 1;
var testCellId = "cell" + testRow + currentCol;
var testCell = document.getElementById(testCellId);
if (cellIsEmpty(testCell)) {
swapTiles(this,testCell);
return;
}
}
if (currentRow<1) {
var testRow = Number(currentRow) + 1;
var testCellId = "cell" + testRow + currentCol;
var testCell = document.getElementById(testCellId);
if (cellIsEmpty(testCell)) {
swapTiles(this,testCell);
return;
}
}
if (currentCol>0) {
var testCol = Number(currentCol) - 1;
var testCellId = "cell" + currentRow + testCol;
var testCell = document.getElementById(testCellId);
if (cellIsEmpty(testCell)) {
swapTiles(this,testCell);
return;
}
}
if (currentCol<1) {
var testCol = Number(currentCol) + 1;
var testCellId = "cell" + currentRow + testCol;
var testCell = document.getElementById(testCellId);
if (cellIsEmpty(testCell)) {
swapTiles(this,testCell);
return;
}
}
}