我正在创建一个UNO克隆,我使用一个观察者在每个回合开始时执行代码:
watch: {
// on turn change
async turnId(val) {
const isUserTurn = val === 0;
if (isUserTurn) {
// reset has drawed flag
// this.hasDrawed = false;
} else {
await setTimeout(() => this.playAI(), 1000);
}
},
},当不是用户的时候,这段代码会运行:
await setTimeout(() => this.playAI(), 1000);playAI方法是:
playAI() {
// get the card and play it
this.play(card)
}, play(card) {
// play the card (delete from hand and put on piletop)
this.nextTurn();
if (card.value === '+4') {
this.currentPlayer.hand.push(...this.draw(4));
this.nextTurn();
} else if (card.value === '+2') {
this.currentPlayer.hand.push(...this.draw(2));
this.nextTurn();
} else if (card.value === 'skip') {
this.nextTurn();
}
}, nextTurn() {
// if the turn id is greater than the total number of players then back it up
if (this.turnId === this.playersNumber - 1) this.turnId = 0;
else this.turnId += 1;
},问题是,当AI玩像skip这样的牌时,它会玩这张牌(跳过),它会运行两次下一轮方法(turnId + 2),但是turnId上的观察者不会第二次运行,所以AI停止播放。
之前相同
如果这是错误,我如何才能强迫观察者运行?
发布于 2020-12-22 16:08:37
通过更改play方法,我设法解决了这个问题:
play(card) {
if (card.value === 'reverse') { // if card is reverse
this.isReversed = !this.isReversed; // inverse reversed flag
} else if (card.value === 'skip') { // if card is skip
this.skipTurn = true; // set skip flag
} else if (card.value === '+2') { // if card is +2
this.nextPlayer.hand.push(...this.draw(2)); // nextPlayer draws 2
this.nextPlayer.hand.sort(this.sortHandler); // sort the hand of the player who draws
this.skipTurn = true; // set skip flag
} else if (card.value === '+4') { // if card is +4
this.nextPlayer.hand.push(...this.draw(4)); // nextPlayer draws 4
this.nextPlayer.hand.sort(this.sortHandler); // sort the hand of the player who draws
this.skipTurn = true; // set skip flag
}
// next turn
this.nextTurn();
}中检查它。
turnId(turn) {
if (this.skipTurn) {
this.skipTurn = false;
this.nextTurn();
return;
}
if (turn !== 0) { // if it's bot's turn
this.playAI();
}
},发布于 2020-12-21 10:13:07
在事件循环中只执行一次观察者,您应该在异步中进行第二次调用。
追加
示例:
play(card) {
// play the card (delete from hand and put on piletop)
this.nextTurn();
setTimeout(() => {
if (card.value === '+4') {
this.currentPlayer.hand.push(...this.draw(4));
this.nextTurn();
} else if (card.value === '+2') {
this.currentPlayer.hand.push(...this.draw(2));
this.nextTurn();
} else if (card.value === 'skip') {
this.nextTurn();
}
}, 0)
}这样,观察者将执行两次,但这将导致意外的结果,您需要考虑如何调整。
https://stackoverflow.com/questions/65390288
复制相似问题