Я создаю клон 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;
},
Проблема в том, что когда ИИ разыгрывает такую карту, как пропуск, он разыгрывает карту (пропускает), дважды запускает метод следующего хода (turnId + 2), но наблюдатель на повороте не запускается во второй раз, поэтому ИИ прекращает играть.
Если это ошибка, как я могу заставить наблюдателя работать?
Наблюдатель выполняется только один раз в цикле событий, второй вызов следует выполнять асинхронно.
добавить
пример:
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)
}
Таким образом, наблюдатель будет выполняться дважды, но это приведет к непредвиденным результатам, и вам нужно будет подумать, как настроить
Мне удалось решить эту проблему, изменив метод воспроизведения:
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();
}
},
Как мне это сделать?