每回合之后,我需要帮助来交换Player。即第一次点击是玩家1(X),然后第二次点击成为玩家2(0)。现在,每次点击都会放置一个X。
const player1 = 'X'
const player2 = 'O'
CurrentPlayer = 1
if(CurrentPlayer == 1) {
$("document").ready (function(){
$(".grid-item").click (function(){
$(this).html(player1);
$("#player").html("2")
CurrentPlayer = 2
})
});
}
if ( CurrentPlayer == 2) {
$("document").ready (function(){
$(".grid-item").click (function(){
$(this).html(player2);
$("#player").html("3")
})
});
}
答案 0 :(得分:0)
您的代码中有很多错误。首先,
$("document").ready (function(){
});
应该用于文件而不是每次单击,另一个问题是事件
$(".grid-item").click (function(){
//
});
只能init
一次,在该事件内,我们只需要检查玩家状态即可。
您的代码应该看起来像这样
$("document").ready (function(){
const player1 = 'X'
const player2 = 'O'
var CurrentPlayer = 1
$(".grid-item").click (function(){
if(CurrentPlayer == 1) {
//do your stuff for player 1
CurrentPlayer = 2
}
else if(CurrentPlayer == 2) {
//do your stuff for player2
CurrentPlayer = 1
}
});
});
答案 1 :(得分:0)
您要附加两次ready
函数,具体取决于您已用1初始化的CurrentPlayer
的当前值,因此播放器2的方法永远不会附加。
您可以尝试以下
const player1 = 'X';
const player2 = 'O';
let CurrentPlayer = 1;
$("document").ready(function () {
$(".grid-item").click(function () {
if (CurrentPlayer === 1) {
// put X for palyer-1
$(this).html(player1);
$("#player").html("2");
// finally toggle CurrentPlayer
CurrentPlayer = 2;
} else {
// put O for palyer-2
$(this).html(player2);
$("#player").html("3");
// finally toggle CurrentPlayer
CurrentPlayer = 1;
}
})
});