重复无效的用户输入,直到它有效为止(伪)

Repeat invalid user input until it is valid (pseudo)

本文关键字:有效 无效 用户 输入      更新时间:2023-09-26

由于某些原因,我很难在JS中执行以下代码:

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

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

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

我本以为这样的东西可以工作,但它似乎进入了一个无限循环:

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){
                break;
            }
        }
        board.updateBoard(position, player) // updates the board
        game.switchPlayer() //switch the currentPlayer
}

我错过了什么?

这里的基本思想是,当您使用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');
    return;
  }
  // Mark the spot and switch the players
  $el.addClass('taken ' + playerClass);
  whosTurn = (whosTurn === 1) ? 2 : 1;
});
div {
  width: 100px;
  height: 100px;
  color: #FFF;
  background-color: #333;
  float: left;
  margin-right: 2em;
  margin-bottom: 2em;
}
.player-1 {
  background-color: #F00;
}
.player-2 {
  background-color: #0F0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div style="clear: left">4</div>
<div>5</div>
<div>6</div>

变量isItValid在函数内定义,我没有看到任何修改它的代码。我猜你想让game.playerTurn(player)修改它,但它不能。您需要检查在while循环的每次迭代中移动是否有效。同时删除

if (isItValid === true){
                break;
}

这是相当多余的。

.click也不等待点击,它附加一个点击处理程序。下面是一个示例,说明如何附加一个处理程序并切换它的可用性

(function($) {
  // Flags
  var waitingForClick = flase;
  // Some action sets waitingForClick = true
  // Click handlers
  $('.cell').click(function(
    if(!waitingForClick) return;
    movePlayer(this);
  });
  function movePlayer(cell) {
    var position = $(cell).attr("id");
  }
})(jQuery);