1A2B,許多人都有聽過或玩過這個遊戲,遊戲規則如下:
學過程式語言的可能都寫過這個遊戲,不過我們要把它換成 Swift 的語法!
首先要有一個陣列,裡面存放 4 個 0~9 的整數值,且每個整數值不同,在按下開始遊戲(按鈕)的時候會把亂數決定好,並且傳遞亂數到第二個畫面。
import UIKit
class ViewController: UIViewController {
    
    var pc = [0, 0, 0, 0] // 宣告成全域讓所有 func 可以讀到
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = #colorLiteral(red: 0.9194224477, green: 0.8519927263, blue: 0.7762778401, alpha: 1)
    }
    
    @IBAction func startGame(_ sender: UIButton) {
    
        pc[0] = Int.random(in: 0...9) // 產生 0~9 的數字
        while(true) {
            pc[1] = Int.random(in: 0...9)
            if (pc[1] != pc[0]) {
                break
            }
        }
        while(true) {
            pc[2] = Int.random(in: 0...9)
            if (pc[2] != pc[1] && pc[2] != pc[0]) {
                break
            }
        }
        while(true) {
            pc[3] = Int.random(in: 0...9)
            if (pc[3] != pc[0] && pc[3] != pc[1] && pc[3] != pc[2]) {
                break
            }
        }
        
        let myS = UIStoryboard(name: "Main", bundle: nil)
        let vc = myS.instantiateViewController(identifier: "SecondViewController") as! SecondViewController
        vc.str = pc // 傳遞亂數
        show(vc, sender: nil)
    }
}
import UIKit
class SecondViewController: UIViewController {
    
    var str:[Int] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        print(str) // 可以在除錯區裡看到結果
    }
}
我們已經產生亂數出來了,緊接著就是要根據我們的輸入判斷幾個 A 和幾個 B,這個部分留給明天繼續努力。