iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 16
0
Mobile Development

《菜鳥のSwift》持續30天開發挑戰系列 第 16

《DAY 16》我的第一個小遊戲 App,1A2B 猜數字遊戲(完)

之前的 1A2B 猜數字遊戲並沒有全部完成,當格式錯誤與遊戲結束僅僅只是在除錯區顯示而已,所以我今天會使用提示框(UIAlertController),來讓功能更完整,各位可以和前一篇的程式碼做比對。

  • 當輸入的格式錯誤時,跳出提示框告知玩家格式錯誤(在 else 裡增加程式碼)。
@IBAction func check(_ sender: Any) {
    
    let inputPre = NSPredicate(format: "SELF MATCHES %@", "^[0-9]{4}$") // 必須為 4 個 0~9 數字
    let bool = inputPre.evaluate(with: input.text) // 符合的話為 true
    
    if bool {
        compare()
    }
    else {
        print("格式錯誤")
        let alertController = UIAlertController(
            title: "警告",
            message: "格式錯誤",
            preferredStyle: .alert
        )
        let okAction = UIAlertAction(
            title: "重新輸入",
            style: .default,
            handler: { action in self.input.text = "" } // 按下後會清除玩家的輸入
        )
        alertController.addAction(okAction)
        present(alertController, animated: true, completion: nil)
    }
    
}
  • 當達成 4A0B 的時候告知玩家猜了幾次,點選「回首頁」回到開始遊戲的畫面。
if a == 4 {
    print("遊戲結束,你共猜了\(count)次")
    simpleHint(count)
}
// 在之前寫好的 compare() 內判斷 a == 4 為 true 時,呼叫 simpleHint()
func simpleHint(_ count: Int) {
    let alertController = UIAlertController(
        title: "遊戲結束",
        message: "你共猜了\(count)次",
        preferredStyle: .actionSheet
    )
    let okAction = UIAlertAction(
        title: "回首頁", style: .default, handler: { action in self.dismiss(animated: true, completion: nil)}
    )
    alertController.addAction(okAction)
    present(alertController, animated: true, completion: nil)
}


上一篇
《DAY 15》我的第一個小遊戲 App,1A2B 猜數字遊戲(三)
下一篇
《DAY 17》選取器
系列文
《菜鳥のSwift》持續30天開發挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言