#80 猜拳遊戲 — 洗刷刷

參考 Apple 猜拳的官方範例改寫

--

題目

洗刷刷
畫面上可選擇 1, 2, 3, 4, 5
5>4,4>3,3>2,2>1,1>5,
只有這五種可以分出勝負,
比方 5 跟 3 就不能比。

這次做了兩個版本,第一個只練了 enum 的 rawvalue,其他都跟以前寫的差不多,第二版就把 Apple 猜拳的官方範例拿來改成洗刷刷的版本,體驗一下厲害的寫法是長怎樣~果然是…需要花一些時間理解消化 R!

第一版:練習自己定義 enum 及應用 enum 的 rawvalue

用 enum 自定型別

若 enum 型別為 String,可以直接用 rawvalue 獲得與成員名稱相同的字串

完整程式碼

第二版:參考 Apple 的剪刀石頭布範例改寫

新增兩個 swift file 自訂型別

Sign.swift

import Foundationfunc randomSign() -> Sign {
let sign = Int.random(in: 1...5)

if sign == 1 {
return .one
} else if sign == 2 {
return .two
} else if sign == 3 {
return .three
} else if sign == 4 {
return .four
} else {
return .five
}
}
enum Sign: String {
case one
case two
case three
case four
case five

var image: String {
switch self {
case .one:
return Sign.one.rawValue
case .two:
return Sign.two.rawValue
case .three:
return Sign.three.rawValue
case .four:
return Sign.four.rawValue
case .five:
return Sign.five.rawValue
}
}

func gameState(against opponentSign: Sign) -> GameState {

switch self {
case .one:
if opponentSign == .five {
return .win
} else if opponentSign == .two {
return .lose
}
case .two:
if opponentSign == .one {
return .win
} else if opponentSign == .three {
return .lose
}
case .three:
if opponentSign == .two {
return .win
} else if opponentSign == .four {
return .lose
}
case .four:
if opponentSign == .three {
return .win
} else if opponentSign == .five {
return .lose
}
case .five:
if opponentSign == .four {
return .win
} else if opponentSign == .one {
return .lose
}
}
return .draw
}
}

GameState.swift

完整程式碼

遇到圖片無法顯示的問題

“Instance will be immediately deallocated because property ‘imageView’ is ‘weak’”error handling

參考以下文章,將 image 移到左邊即可

Github

--

--