#10 猜數字

成品:

code:

```swift

import UIKit

class ViewController: UIViewController {

// IBOutlet連結的元件
@IBOutlet weak var numberTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBOutlet weak var guessCountLabel: UILabel!
@IBOutlet weak var guessButton: UIButton!

// 存放隨機產生的答案
var answer = Int.random(in: 1...100)
var guessCount = 0
var minNumber = 0
var maxNumber = 100

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}

// 猜數字按鈕的動作
@IBAction func guess(_ sender: Any) {
let numberText = numberTextField.text!
let number = Int(numberText)

// 確認輸入的數字是否在範圍內
if number != nil, number! >= minNumber, number! <= maxNumber {
let guessNumber = number!

// 猜對了
if guessNumber == answer {
resultLabel.text = "答案是\(guessNumber)!\n恭喜你猜對了"
}
// 猜錯了,更新範圍
else if guessNumber < answer {
minNumber = guessNumber
resultLabel.text = "範圍\(minNumber)~\(maxNumber)"
numberTextField.text = ""
guessCount += 1
}
else if guessNumber > answer {
maxNumber = guessNumber
resultLabel.text = "範圍\(minNumber)~\(maxNumber)"
numberTextField.text = ""
guessCount += 1
}
guessCountLabel.text = "剩下 \(6 - guessCount) 次機會"
}
// 輸入超出範圍
if number != nil, number! > maxNumber {
numberTextField.text = ""
resultLabel.text = "超出範圍嘍!\n請重新輸入"
}
// 輸入非數字
if number == nil {
numberTextField.text = ""
resultLabel.text = "請輸入1~100的數字!!"
}
// 猜測次數用完
if guessCount == 6 {
numberTextField.text = ""
guessButton.isEnabled = false
guessCountLabel.text = "失敗"
resultLabel.text = "真可惜!!\n答案是\(answer)"

}
// 縮鍵盤
view.endEditing(true)
}

// 重新開始遊戲按鈕的動作
@IBAction func replay(_ sender: Any) {
answer = Int.random(in: 1...100)
guessButton.isEnabled = true
numberTextField.text = ""
minNumber = 0
maxNumber = 100
guessCount = 0
resultLabel.text = "請輸入 \(minNumber) ~ \(maxNumber) 的數字"
guessCountLabel.text = "有 \(6 - guessCount) 次機會"

}

}

Github:

--

--