我正在尝试在浏览器中编写幻灯片拼图。当用户单击网格上与BLANK正方形相邻的正方形时,应将单击的正方形替换为BLANK。
编辑:这是完成后应该做的:https://en.wikipedia.org/wiki/15_puzzle
我正在尝试使用onclick触发器调用JavaScript函数来实现此目的,该函数首先检查正方形是否为有效移动,然后切换正方形的ID属性。我的CSS文件包含每个广场的图片,并链接到广场的ID。
按现状显示,点击正方形时,正方形什么也没做。
<html>
<head>
<link rel="stylesheet" type="text/css" href="Puzzle.css">
<title>Fifteen Puzzle</title>
<script type="text/javascript" src="Puzzle.js" defer="defer"></script>
</head>
<body onload="startPuzzle()">
<div class="container">
<div class="square" id="square0" onclick="A.slide(0, 0, this.id)"> </div>
<div class="square" id="square1" onclick="A.slide(1, 0, this.id)"> </div>
<div class="square" id="square2" onclick="A.slide(2, 0, this.id)"> </div>
/* And so on to the 16th square: */
<div class="square" id="squareBLANK" onclick="A.slide(3, 3, this.id)"> </div>
</div>
</body>
</html>
JAVASCRIPT文件:
class Puzzle {
constructor () {
this.board = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, "_"]];
}
slide (i, j, a){
x = this.board[i][j];
if (this.board[i+1][j] == "_") {
this.board[i+1][j] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i][j+1] == "_") {
this.board[i][j+1] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i][j-1] == "_") {
this.board[i][j-1] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
else if (this.board[i-1][j] == "_") {
this.board[i-1][j] = x;
this.board[i][j] = "_";
document.getElementById(a).id = "PLACEHOLDER";
document.getElementById("squareBLANK").id = a;
document.getElementById("PLACEHOLDER").id = "squareBLANK";
}
}
}
function startPuzzle() {let A = new Puzzle();}
那么,谁能说出阻止方块移动的原因?
答案 0 :(得分:0)
您已创建board Array
中的4 object
this.board = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, "_"]];
然后您设置squareBLANK slide method
参数3 LastObject ,3 第三值,this.id squareBLANK 。
<div class="square" id="squareBLANK" onclick="A.slide(3, 3, this.id)"> </div>
在Javascript中,您正在检查[i] LastObject 表示 [3 + 1] = 4 。您实际上在板数组中的第5个对象中检查了第3个值,该值不存在,并且还会返回 Uncaught TypeError:无法读取属性控制台中未定义的'3'。
if (this.board[i+1][j] == "_")