終極密碼…!

目的: 學習產生隨機數字,數字和字串之間的轉換。

到了一定年紀後,還是會玩這個遊戲嗎???

輸的喝一杯?還是直接一盤Shot了??

很陽春的介面…承認我沒有什麼審美觀..Orz

用到的功能:

  1. UIButton…沒了!!…滿滿的button…

能觸發的IBAction有

  1. 點擊數字後,會顯示輸入的文字
  2. 重新輸入文字
  3. 重新開始遊戲
  4. 判斷是否踩到炸彈

點擊數字後,會顯示輸入的文字

檢查字數是否大於2,否則會有錯誤訊息!!

//數字鍵
@IBAction func numberButton(_ sender: UIButton) {
//print(sender.currentTitle!)
if totalLabel.text!.count > 1 {
alert(title: "注意!", message: "最多2個字!", button: "收到")
} else {
totalLabel.text! += sender.currentTitle!
}
}

重新輸入文字

//重新輸入
@IBAction func clearLabel(_ sender: UIButton) {
clearTotalLabel()
}
//清空輸入的文字
func clearTotalLabel() {
totalLabel.text! = ""
}

重新開始遊戲

//重新一場遊戲
@IBAction func reStart(_ sender: UIButton) {
clearLabel()
getNewKey()
clearTotalLabel()
alert(title: "OK!", message: "已幫你從設密碼囉!!", button: "GoGO")
}
func clearLabel() {
minLabel.text = "0"
maxLabel.text = "100"
touchNumberLabel.text = "0"
}

//重新開始,產生新的炸彈
func getNewKey() {
key = Int.random(in: 1...99)
}

判斷是否踩到炸彈

判斷輸入的數字大於&小於&等於炸彈

否則會去更新對應的到欄位

//送出按鈕
@IBAction func submit(_ sender: UIButton) {
let tmpInput = Int(totalLabel.text!)! //把輸入值丟到tmpInput內
//先判斷輸入的是否 小於最小 && 大於最大
if tmpInput > Int(minLabel.text!)! && tmpInput < Int(maxLabel.text!)! {
//輸入值與炸彈比較
if tmpInput < key {
minLabel.text = "\(tmpInput)" //若比炸彈小 修改最小值
} else if tmpInput > key {
maxLabel.text = "\(tmpInput)" //若比炸彈大 修改最大值
} else {
//猜對後&清空字串&跳訊息&重新開始
alert(title: "完成!", message: "恭喜猜對囉~~", button: "結束")
clearLabel()
getNewKey()

}
touchNumberLabel.text = "\(Int(touchNumberLabel.text!)! + 1)" //使用次數累加
} else {
alert(title: "賣鬧!!", message: "看清楚再猜,這次放過你,不算你一次的機會!!", button: "對不起Orz")
}
print(key)
totalLabel.text = "" //清空輸入匡欄位
}

Demo

附上我的GitHub

--

--