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

时间:2016-06-23 20:36:10

标签: javascript loops input

出于某种原因,我很难在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
}

我错过了什么?

2 个答案:

答案 0 :(得分:2)

这里的基本思想是当你使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

变量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);