问题遇到的现象和发生背景
想使用改变目标格子的class属性的方式来实现两色棋子按顺序移动到随机白色部分内,但以下代码不稳定,无法实现棋子移动到目标位置,然后原位置回到白色状态的期望
问题相关代码,请勿粘贴截图
var pieces = [
[ 0,-1, 0,-1, 0,-1, 0,-1],
[-1, 0,-1, 0,-1, 0,-1, 0],
[ 0,-1, 0,-1, 0,-1, 0,-1],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 1, 0, 1, 0, 1, 0, 1, 0],
[ 0, 1, 0, 1, 0, 1, 0, 1],
[ 1, 0, 1, 0, 1, 0, 1, 0],
];
var INI = 1;//show that what color can move now
function randomMove() {
document.getElementById("member3").innerHTML = "MaYiming";
do {
var r1=Math.floor(Math.random()*8)
var c1=Math.floor(Math.random()*8)
var r2=Math.floor(Math.random()*8)
var c2=Math.floor(Math.random()*8)
}
while
(pieces[r1][c1] == 0 ||
pieces[r2][c2] !=0 ||
(r2 + c2) % 2 == 0 ||
(pieces[r1][c1] == -1 && INI == 0) ||
(pieces[r1][c1] == 1 && INI == 1));//if the parameters did not met the requirment, continute until it does
pieces[r2][c2] = pieces[r1][c1];//movement of the checkers must be noticed in the array
if
(pieces[r1][c1] == 1 && INI == 0)
{document.getElementById(getCellID(8, r2, c2)).className = "Bc";INI += 1;pieces[r1][c1] = 0}
else if
(pieces[r1][c1] == -1 && INI == 1)
{document.getElementById(getCellID(8, r2, c2)).className = "Rc";INI -=1;}
pieces[r1][c1] = 0;
{if ((r1 + c1) % 2 != 0) {document.getElementById(getCellID(8, r1, c1)).className = 'W';}
else {document.getElementById(getCellID(8, r1, c1)).className = 'B';}
}
}
td{ text-align: center;width: 100px;height: 100px; border: pink 1px solid;}
.W{background-color: white; }
.B{background-color: darkgrey ; }
.Rc{background-image: url("../image/Rc.jpg"); background-size: cover}
.Bc{background-image: url("../image/Bc.jpg");background-size: cover}
运行结果及报错内容
会出现这种。。奇怪的棋子增加了的。。状况,而只有那个突出来的红色棋子是想要的状态
我想要达到的结果
从红色开始,依次移动到随机白色格子内,并且不移动到同色棋子的位置,会吃掉其他颜色的棋子