Swift3 從入門到精通Day3:猜數字
時間:5/9(二)
作品:猜數字
內容:Section3
- 20. If 判斷式18:48
- 21. If 判斷式210:48
- 22. Game 猜數字1: 文字置中的方法6:57
- 23. Game 猜數字2: 製作介面8:21
- 24. Game 猜數字3: 取亂數的方法7:00
- 25. Game 猜數字4: 取得使用者輸入的數字9:20
- 26. Game 猜數字5: 判斷猜的數字是否正確7:49
- 27. Game 猜數字6: 提示正確答案的功能7:09
- 28. Game 猜數字7: 重新玩遊戲的設定6:39
- 29. Game 猜數字8: 美化、重新設計畫面6:36
- 30. Switch 判斷式7:15
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var inputTextField: UITextField!
var maxNumber = 100
var minNumber = 1
var isOver = false
//Make a random number
var answer = Int(arc4random_uniform(100) + 1)
@IBAction func makeAGuess(_ sender: UIButton) {
if isOver == false{
//play game
print(“answer = \(answer)”)
let inputText = inputTextField.text!
//clear textfield
inputTextField.text = “”
//take input text out
let inputNumber = Int(inputText)
print(“inputNumber = \(String(describing: inputNumber))”)
if inputNumber == nil{
//no input
messageLabel.text = “No input! Guess a number between \(minNumber) ~ \(maxNumber)”
}else{
//got input
if inputNumber! > maxNumber{
//user input too large
messageLabel.text = “Too large! Guess a number between \(minNumber) ~ \(maxNumber)”
}else if inputNumber! < minNumber{
//user input too small
messageLabel.text = “Too small! Guess a number between \(minNumber) ~ \(maxNumber)”
}else{
//check answer
if inputNumber == answer{
//Bingo! right answer!
messageLabel.text = “You are right. Press[Guess] to play again”
isOver = true
}else{
//Wrong answer
if inputNumber!>answer{
//larger than answer
maxNumber = inputNumber!
}else{
//smaller than answer
minNumber = inputNumber!
}
messageLabel.text = “Try Again! Guess a number between\(minNumber)~\(maxNumber)”
}
}
}
}else{
//play is over
maxNumber = 100
minNumber = 1
messageLabel.text = “Try Again! Guess a number between\(minNumber)~\(maxNumber)”
answer = Int(arc4random_uniform(100) + 1)
isOver = false
}
func viewDidLoad() {
super.viewDidLoad()
//Push the keyboard up
inputTextField.becomeFirstResponder()
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
}