Ios 给定一个值列表,如何选择大于上一个值的值?
问题就在这里。有一个机器人可以玩石头,纸,剪刀。机器人应该选择能够击败上一个机器人的动作。例:第一轮:机器人拣纸,所以第二轮机器人应该拣剪刀。等等 到目前为止,我的代码是这样的:方法,它使第一次移动成为随机移动Ios 给定一个值列表,如何选择大于上一个值的值?,ios,swift,algorithm,Ios,Swift,Algorithm,问题就在这里。有一个机器人可以玩石头,纸,剪刀。机器人应该选择能够击败上一个机器人的动作。例:第一轮:机器人拣纸,所以第二轮机器人应该拣剪刀。等等 到目前为止,我的代码是这样的:方法,它使第一次移动成为随机移动 let randomizer = GKARC4RandomSource() // TODO: - REFACTOR func botRandomChoice() -> Symbol { let botSymbol = randomizer.nextInt(upperBoun
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 = "I would start by adding a method to the enum that defines the rules and that can be used to select the "greater" value. This method return the symbol that beats self
func beatenBy() -> Symbol {
switch self {
case .rock:
return .paper
case .paper:
return .scissor
case .scissor:
return .rock
}
}
struct游戏{
变量符号:符号
变量状态:游戏状态
}
枚举符号:字符串{
case rock=“我将首先向枚举添加一个方法,该方法定义规则并可用于选择“较大”值。此方法返回的符号超过self
func outcome(other: Symbol) -> GameState {
if self == other {
return .draw
}
return self.beatenBy() == other ? .lose : .win
}
现在我们还可以使用它来简化结果
方法
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()
我不太清楚你想如何玩这个游戏(在代码中),所以这里有一个简单的例子,第一轮和准备第二轮使用beatenBy
鉴于您已经开始创建游戏结构,我将使用它来包含所有组件以及轨迹状态。我还将引入一个结果
枚举,允许您返回一个.win
或.lose
。将符号
的所有比较逻辑移动到枚举中可以整理代码:使用e> nextMove
方法返回下一步,而“play(country:)”方法返回“play”回合
struct游戏{
枚举结果{
胜诉
败诉
}
枚举符号:字符串,可大小写{
case rock=“:@Joakim Danielson提出了一个非常类似的解决方案,并首先得到了它,所以给他荣誉:-)他已经解释了抽签,我完全忘记了!