2016-06-23 22 views
0

對於我在執行下面的代碼爲我的遊戲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 
} 

我缺少什麼?

+0

是什麼'game.playerTurn()'做。 「isItValid」如何改變? – charlietfl

+0

看起來您每次調用'playerTurn'時都會設置一個新的點擊處理程序。你確定這就是你想要做的?而且,用那個'while'循環,你永遠不會給玩家一個改變他們行動的機會。相反,您應該檢查它是否有效,如果不是,請指出移動無效並提前退出該功能。否則,執行該回合的其餘邏輯。 –

回答

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

+2

謝謝邁克!這真的很有幫助。 我沒有意識到每次函數調用時我都設置了處理函數。 歡呼! – Alejandro

相關問題