2017-07-07 142 views
2

我正在使用ReactJS構建德州撲克網絡應用程序。爲了跟蹤莊家的,我用下面的公式...在JavaScript中使用mod運算符以環繞

let currentPlayers = [ 
    {name: "Foo", position: 1}, 
    {name: "Bar", position: 2}, 
    {name: "Baz", position: 3} 
] 
let dealerButtonPos = 1 

dealerButtonPos = ((dealerButtonPos + currentPlayers.length) % currentPlayers.length + 1) 

我想在這裏做的就是確保經銷商按鈕開始在位置1和位置始終是正確的在每一輪開始時的位置。在這種情況下,莊家按鈕應始終落在位置1,然後是2,然後是3,然後是1。

帶公式的函數將在每一輪結束時調用。這應該正確旋轉莊家按鈕,最多8名玩家。 我會一直處於正確的球員位置嗎?我是否正確實施?我很難概念化並達到這一點。有人可以解釋模運營商的清晰度?

+1

'(a + b)%b'與'a%b'相同 – ASDFGerte

+2

'+ currentPlayers.length' ??? '+ 1'! –

+2

您可以使用'dealerButtonPos =(dealerButtonPos + 1)%currentPlayers.length'輕鬆地將其保存在數組的邊界內。但是,要注意玩家站起來或被淘汰的情況,留下一個「死」的地方,但必須出示牌。不管其他條件如何,莊家按鈕都比簡單地旋轉要複雜一些。 – jered

回答

1

iterator pattern

let currentPlayers = [ 
 
    {name: "Foo", position: 1}, 
 
    {name: "Bar", position: 2}, 
 
    {name: "Baz", position: 3} 
 
] 
 

 
function* currentPlayersIterator(players) { 
 
    let index = 0; 
 
    while(true) 
 
    if (index < players.length) { 
 
     yield players[index++] 
 
    } else { 
 
     index = 0 
 
     yield players[index++] 
 
    } 
 
} 
 

 

 
let i = currentPlayersIterator(currentPlayers) 
 

 
console.log(i.next().value) 
 
console.log(i.next().value) 
 
console.log(i.next().value) 
 
console.log(i.next().value) 
 
console.log(i.next().value)

1

我會做這種方式很好。

let currentPlayers = [ 
    {name: "Foo", position: 1}, 
    {name: "Bar", position: 2}, 
    {name: "Baz", position: 3} 
] 
let dealerButtonPos = 1 
var index = dealerButtonPos % currentPlayers.length 
dealerButtonPos = (index == 0) ? index + currentPlayers.length : index