Apple 的剪刀石頭布(RPS)範例

先模仿製作類似的功能跟畫面,然後再參考 Apple 的範例寫法。

畫面 & 功能

特別功能:

  • 點選剪刀石頭布出拳時,將其它的拳隱藏。
  • Play Again
  • 依據猜拳結果顯示不同的背景顏色。

範例來源: Develop in Swift Explorations

Unit 4.2 Play With App Components 的 Rock,Paper,Scissors

範例下載。

從電子書第 16 頁點選 Download teacher materials。

程式重點

宣告 enum 型別

定義剪刀石頭布。

enum Sign {
case rock
case paper
case scissors

定義遊戲的結果。

enum GameState {
case start
case win
case lose
case draw

宣告 computed property & 使用 switch

  • 判斷 self,回傳對應的 emoji。
enum Sign {
case rock
case paper
case scissors

var emoji: String {
switch self {
case .rock:
return "👊"
case .paper:
return "✋"
case .scissors:
return "✌️"
}
}

另一種取得 enum case 對應字串的方法: 使用 enum 的 rawValue。

enum Sign: String {
case rock = "👊"
case paper = "✋"
case scissors = "✌️"
}

var sign = Sign.rock
print(sign.rawValue)
  • 判斷 self,回傳對應的遊戲結果訊息。
enum GameState {
case start
case win
case lose
case draw

var status: String {
switch self {
case .start:
return "Rock, Paper, Scissors?"
case .win:
return "You Won!"
case .lose:
return "You Lost!"
case .draw:
return "It's a Draw!"
}
}
}
  • 在 enum 裡宣告 function,function 參數宣告外部名和內容名(Argument Labels and Parameter Names)
enum Sign {
case rock
case paper
case scissors

func gameState(against opponentSign: Sign) -> GameState {
if self == opponentSign {
return .draw
}

switch self {
case .rock:
if opponentSign == .scissors {
return .win
}
case .paper:
if opponentSign == .rock {
return .win
}
case .scissors:
if opponentSign == .paper {
return .win
}
}
return .lose
}
}

將畫面更新的程式寫成 function updateUI,多個地方都可以呼叫

在以下三個地方呼叫:

  • viewDidLoad : 一開始畫面載入完成時。
  • play: 點選剪刀石頭布按鈕時。
  • playAgain: 點選 Play Again 再玩一次時。

剪刀石頭布的 IBAction 都呼叫 play,傳入不同的 enum case 區分

利用 isHidden 控制元件的顯示和隱藏,利用 isEnabled 控制元件是否可點選

作品集

--

--

彼得潘的 iOS App Neverland
彼得潘的 Swift iOS / Flutter App 開發教室

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com