为多个玩家修改快速蛇和梯子游戏

时间:2015-10-24 16:32:36

标签: ios swift

我正在尝试修改我为一个玩家在Swift中为蛇和梯子的简单游戏创建的代码。下面是一个成功运作的代码:

let finalSquare = 25
var playersLocation: Int = 0

var won = false

var board = [Int](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

//roll the dice
func rollDice ()->Int {
    let value = Int(arc4random_uniform(6)+1)
    return value
}

while won == false {
//roll the dice
    var advanceplayer = rollDice()
//check the position
    var advance: Int = playersLocation + advanceplayer
//check if it hits the magic number
    if playersLocation < board.count{
        var magicNumber: Int = board[playersLocation]
        advance + magicNumber
    }

    //check if player won
    if playersLocation >= board.count {
        won == true
        print("you won")
        break
    }else{
        playersLocation = playersLocation + advanceplayer
    }
}

现在代码正常工作,我希望以一种我有3个玩家(a,b,c)的方式进行修改,我想将它们插入到游戏中。我几乎被困在这里:

let finalSquare = 25
var playersLocation: Int = 0
var players: [String: Int] = ["a": 0, "b": 0, "c":0]

var won = false

var board = [Int](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08

board

//roll the dice
func rollDice ()->Int {
    let value = Int(arc4random_uniform(6)+1)
    return value
}

var count: Int = 0

while won == false {
    for player in players.values{


        var advanceplayer = rollDice()
        var advance: Int = player + advanceplayer


        if advance < board.count{
            var magicNumber: Int = board[advance]
            advance + magicNumber
        }

        if advance >= board.count {
            won == true
            print("you won")
            break
        }else{

        advance + advanceplayer

        }
    }
}

不知何故,玩家位置不会增加,我不知道如何跟踪a,b或c是否赢得比赛。哪里出错了?

2 个答案:

答案 0 :(得分:0)

当您更新每个玩家的位置时,您不会将其重新分配到players地图中该玩家的位置。这对您当前的代码很难处理,因为您正在迭代players映射的值并忽略其键。相反,枚举键和值,更新每个玩家的位置,然后将新值粘贴回players

答案 1 :(得分:0)

您永远不会将玩家的新位置存储回players字典,因此在while循环的每次迭代中,每个玩家的位置都会重置为零。

此外,你永远不会使用magicNumber;以下表达式的结果永远不会存储在任何地方:

advance + magicNumber

也许您打算将结果存回advance,如下所示:

advance += magicNumber