ios - 给定一个值列表,我如何选择大于前一个值的值?

标签 ios swift algorithm

这是问题所在。有一个机器人会玩石头,纸,剪刀。机器人应该选择会击败其前一个 Action 的 Action 。例如:第一轮:机器人挑纸,所以第二轮机器人应该挑剪刀。等等...

到目前为止我的代码是这样的: 使第一步随机移动的方法。

let randomizer = GKARC4RandomSource()
// TODO: - REFACTOR
func botRandomChoice() -> Symbol {
    let botSymbol = randomizer.nextInt(upperBound: 3) // or 2
    if botSymbol == 0 {
        print("RandomSymbol is rock")
        return .rock
    } else if botSymbol == 1 {
        print("Random Symbol is paper")
        return .paper
    } else {
        print("Random Symbol is scissor")
        return .scissor
    }
}

模型:
struct Game {
    var symbol: Symbol
    var state: GameState
}

enum Symbol: String {
    case rock = "👊"
    case paper = "🖐"
    case scissor = "✂️"

    func outcome(botChoice: Symbol) -> GameState {
        if self == botChoice {
            return .draw
        }
        switch self {
        case .rock:
            return botChoice == .scissor ? .win : .lose
        case .paper:
            return botChoice == .rock ? .win : .lose
        case .scissor:
            return botChoice == .paper ? .win : .lose
        }
    }
}

到目前为止我尝试了什么?
我试图想出最好的方法来做到这一点。我正在考虑一个看起来像这样的 if 或 switch 语句:
var moveNumber = 1
var symbol: Symbol
if moveNumber == 1 {
// It is the first move so pick a random choice.
let boySymbol = randomizer.nextInt(upperBound: 3)
}
if moveNumber == 2 {
// Look at previous move
let previous = botSymbol
// Use the move that would beat it.
if previous == .rock {
// play paper

我认为有更好的方法来解决或编码这个问题,但我迷路了。我什至在考虑一个链表?也许是一本字典?

最佳答案

我将首先向定义规则的枚举添加一个方法,该方法可用于选择“更大”的值。此方法返回击败 self 的符号

func beatenBy() -> Symbol {
    switch self {
    case .rock:
        return .paper
    case .paper:
        return .scissor
    case .scissor:
        return .rock
    }
}

现在我们也可以用它来简化 outcome方法
func outcome(other: Symbol) -> GameState {
    if self == other {
        return .draw
    }
    return self.beatenBy() == other ? .lose : .win
}

我不确定你想怎么玩游戏(用代码),所以这里有一个简单的例子,说明第一轮和使用 beatenBy 为第二轮做准备
var myChoice: Symbol!
var botChoice = botRandomChoice()

myChoice = .paper

let result = myChoice.outcome(other: botChoice)

//set next bot choice based on winning choice
botChoice = result == .win ? myChoice.beatenBy() : botChoice.beatenBy()

关于ios - 给定一个值列表,我如何选择大于前一个值的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59109415/

相关文章:

c++ - 找到最小的未使用号码

ios - UIGesture 返回 UIImageView 而不是自定义 View

ios - 如何禁用控制中心播放/暂停按钮?

ios - UIActivityIndi​​catorView 对话框概览

iOS 应用程序只能支持一个 tabBar 项目的横向方向吗?

c++ - 用c++写一个对数函数

ios - SpriteKit : node Y position and touch Y position not consistent

ios - 如何在 swift 3 中获取和更新 Healthkit 中的高度?

ios - 如何将自定义 NOT TINTED 图像添加到 UIBarButtonItem

javascript - 对数组数据求平均值