通过词典迭代确定玩家位置

时间:2017-10-29 09:25:23

标签: ios dictionary

我正在为四名玩家打牌。我将这些播放器对象保存在一个带有简单ID的字典中​​; 1,2,3,4。然后我随机确定首发球员。

在游戏视图中,我将四个玩家分配到屏幕的不同区域。当前设备的播放器始终是屏幕底部的播放器,下一个播放器位于屏幕上,第三个位于顶部,第四个位于屏幕右侧。

假设设备的播放器是播放器词典中ID为3的播放器。将球员放置在屏幕上将是; 1(上),2(右),3(下)和4(左)。它们根据它们在字典中的位置顺时针方向放置。

我有这个代码来确定位置。要清楚; bottom = 1,left = 2,top = 3,right = 4。

func determinePlayerPositions() {
    var playerPositionsCount = 0

    for i in 1...gamePlayers.count {
        let player = gamePlayers[i]

        if player?.playerID == playerOfThisDeviceId {
            playerOfThisDevice = i
            playerPositions[1] = playerOfThisDevice
            playerPositionsCount += 1

            if playerOfThisDevice == gamePlayers.count && playerPositionsCount != gamePlayers.count {

                for i in 1...gamePlayers.count-1 {

                    playerPositions[i] = i
                    playerPositionsCount += 1
                }
            }

            if playerOfThisDevice < gamePlayers.count && playerPositionsCount != gamePlayers.count {

                for i in playerOfThisDevice+1...gamePlayers.count {
                    playerPositions[i] = i
                    playerPositionsCount += 1
                }

                if playerPositionsCount != gamePlayers.count {
                    for i in 1...playerPositionsCount {
                        playerPositions[i] = i
                    }

                    playerPositionsCount = 0
                }
            }
        }
    }

    setLabelTexts()

}

底部玩家在玩游戏的四种不同设备上有所不同。

所以它有效,但我的问题是;是否有更有效的方法来确定头寸。这似乎只是一个简单任务的代码。

谢谢!

1 个答案:

答案 0 :(得分:1)

我们可以通过当前玩家拆分玩家阵列,以使当前玩家成为第一个元素。

[1, 2, 3, 4] -> [3, 4, 1, 2] // where current player has ID 3

当这样排列时,玩家的索引会映射到位置索引。

enum Position: Int {
    case bottom = 1
    case left = 2
    case top = 3
    case right = 4
}

struct Player {
    let id: Int
}

struct Game {
    let current: Player
    let players: [Player]

    func position(of player: Player) -> Position? {

        let slices = players.split(whereSeparator: { $0.id == current.id })
        let ordered = [current] + slices.last! + slices.first!
        let index = ordered.index(where: { $0.id == player.id })

        return index.flatMap { Position(rawValue: $0 + 1) }
    }
}

let game = Game(
    current: Player(id: 3),
    players: [
        Player(id: 1),
        Player(id: 2),
        Player(id: 3),
        Player(id: 4)
    ]
)

print(game.position(of: Player(id: 3)))