我当时正在开发黑白棋游戏,而我遇到的情况是要检测板上的空白处。我写的,但不完全正确。
var IsUserTurn = true;
var Empty;
function InsertBlack(x, y) {
var Temp1 = document.createElement("img");
Temp1.setAttribute("src", "http://www.uploadhosting.co/uploads/151.238.149.6/Black.png");
Temp1.style.position = "absolute";
var Temp3 = (x * 50) - 50;
var Temp4 = (y * 50) - 50;
Temp1.style.left = Temp3 + "px";
Temp1.style.top = Temp4 + "px";
var Temp2 = document.getElementById("panel");
Temp2.style.position = "relative";
Temp2.appendChild(Temp1);
}
function InsertWhite(x, y) {
var Temp1 = document.createElement("img");
Temp1.setAttribute("src", "http://www.uploadhosting.co/uploads/151.238.149.6/White.png");
Temp1.style.position = "absolute";
var Temp3 = (x * 50) - 50;
var Temp4 = (y * 50) - 50;
Temp1.style.left = Temp3 + "px";
Temp1.style.top = Temp4 + "px";
var Temp2 = document.getElementById("panel");
Temp2.style.position = "relative";
Temp2.appendChild(Temp1);
}
function SetClickEventListenerForPanel() {
var Temp1 = document.getElementById("panel");
if (Temp1.addEventListener) {
Temp1.addEventListener("click", PanelClickProcessor);
} else if (Temp1.attachEvent) {
Temp1.attachEvent("onclick", PanelClickProcessor);
}
}
function SetBooleanVariableStatus() {
if (IsUserTurn === true) {
document.getElementById("Boolean").innerHTML = "User's turn";
} else {
document.getElementById("Boolean").innerHTML = "Computer's turn";
}
}
function IsEmpty(x, y) {
var Temp1 = document.getElementsByTagName("img");
var i;
var xx, yy;
xx = (x * 50) - 50 + ("px");
yy = (y * 50) - 50 + ("px");
for (i = 0; i < Temp1.length; i++) {
if (Temp1[i].style.left != xx && Temp1[i].style.top != yy) {
Empty = true;
} else {
Empty = false;
break;
}
}
return Empty;
}
function Convert(data) {
if (data <= 50) {
return 1;
}
if (data <= 100) {
return 2;
}
if (data <= 150) {
return 3;
}
if (data <= 200) {
return 4;
}
if (data <= 250) {
return 5;
}
if (data <= 300) {
return 6;
}
if (data <= 350) {
return 7;
}
if (data <= 400) {
return 8;
}
}
function PanelClickProcessor(e) {
var X = e.pageX - this.offsetLeft;
var Y = e.pageY - this.offsetTop;
var xtocall, ytocall;
xtocall = Convert(X);
ytocall = Convert(Y);
alert(IsEmpty(xtocall, ytocall));
}
InsertBlack(4, 4);
InsertWhite(5, 4);
InsertWhite(4, 5);
InsertBlack(5, 5);
SetClickEventListenerForPanel();
SetBooleanVariableStatus();
演示:http://jsfiddle.net/huL3qoa3
当您单击板上的任意位置时,无论该位置是否为空,都会显示一条警报。运作不正常,这是什么问题?
最佳答案
比较坐标时,应使用||
运算符而不是&&
运算符:
if (Temp1[i].style.left != xx || Temp1[i].style.top != yy) {