cuốn sách gpt4 ai đã làm

javascript - 重复无效的用户输入,直到其有效(伪)

In lại Tác giả: Walker 123 更新时间:2023-11-28 18:31:03 28 4
mua khóa gpt4 Nike

出于某种原因,我很难在 JS 中为我的游戏执行以下代码:

假设我们要求用户在棋盘上移动一个棋子。他们可以做的位置是位置A、位置B或位置C。每个位置一次只能容纳一件。否则为无效移动。

第一个用户决定移动位置 A。第二个用户想要移动到位置 A,但当然不能,因为它已经被占用了。直到第二个用户正确输入有效的移动,第一个用户必须等到那时。

在我的代码中,我能够创建一个函数来检查用户的输入是否有效,board.validMove(position)( bool 值)。

我本以为这样的东西是有效的,但它似乎陷入了无限循环:

Game.prototype.playerTurn = function(player){
$(".cell").click(function(){
var position = #(this).attr("id");
var isItValid = board.validMove(position) // this will return true or false if it is valid
while( isItValid === false) { // I'd thought until isItValid becomes true, it will ask the user to choose another position
game.playerTurn(player) //call again
if (isItValid === true){
phá vỡ;
}
}
board.updateBoard(position, player) // updates the board
game.switchPlayer() //switch the currentPlayer
}

我错过了什么?

câu trả lời hay nhất

这里的基本思想是,当您使用 while 循环时,用户永远没有机会更改任何内容。只要 JavaScript 正在主动运行,它就无法接受来自用户的任何输入。

相反,您想要验证移动是否有效,并且仅在有效时才继续。否则,您想通知用户他们所做的事情是无效的。

这是该想法的一个基本示例:

// Track which players turn it is
var whosTurn = 1;

// Only setup the event handler once
// Setting up the handler multiple times will cause problems
$('div').click(function() {
var $el = $(this);
var playerClass = 'player-' + whosTurn;
if ($el.hasClass('taken')) {
// Alert the user that it isn't a valid move and allow them to change their move
alert('That spot is already taken');
trở lại;
}

// Mark the spot and switch the players
$el.addClass('taken ' + playerClass);
whosTurn = (whosTurn === 1) ? 2 : 1;
});
div {
chiều rộng: 100px;
chiều cao: 100px;
màu sắc: #FFF;
màu nền: #333;
nổi: trái;
margin-right: 2em;
margin-bottom: 2em;
}
.player-1 {
background-color: #F00;
}
.player-2 {
background-color: #0F0;
}

1

2

3

4

5

6

关于javascript - 重复无效的用户输入,直到其有效(伪),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38001357/

28 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress