iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 15
0
Mobile Development

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

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

今天來完成 UI 的部分,我會多宣告幾個變數,並調整之前宣告過的變數位置(例如把 user 改成按鈕按下才宣告)。

  • 在 SecondViewController 畫面中放入一個 Text Field 讓玩家輸入數字,也放入一個 Table View 來顯示玩家之前輸入過的數字與判斷結果。
    https://ithelp.ithome.com.tw/upload/images/20200929/20129680ewBPNljU2o.png

  • viewDidLoad 上方宣告的變數如下。

var str:[Int] = [] // 接收亂數
var numberList:[String] = [] // 在表格內顯示玩家輸入過的數字
var result:[String] = [] // 根據玩家輸入的數字顯示幾 A 幾 B
var count = 0 // 玩家嘗試的次數

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var input: UITextField!
  • 可以在 viewDidLoad 顯示出正確答案,使用者在手機畫面內並不會看見。
override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = #colorLiteral(red: 0.9194224477, green: 0.8519927263, blue: 0.7762778401, alpha: 1)
    print(str) // 可以在除錯區裡看到正確答案
}
  • 按下按鈕判斷幾 A 幾 B,但是我們可能會輸入非純數字的字串,所以必須先檢查,否則不能轉成整數型態。
@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("格式錯誤")
    }
    
}
    
func compare() {
    var a = 0, b = 0
    var user = [0, 0, 0, 0]
    
    user[0] = Int(input.text!)!/1000 % 10 // 取出千位
    user[1] = Int(input.text!)!/100 % 10 // 取出百位
    user[2] = Int(input.text!)!/10 % 10 // 取出十位
    user[3] = Int(input.text!)! % 10 // 取出個位
    
    
    for i in 0...3 {
        for j in 0...3 {
            if user[i] == str[j] && i == j {
                a += 1 // 位置與值都正確
                break
            }
            if user[i] == str[j] && i != j {
                b += 1 // 只有值正確,位置不正確
            }
        }
    }
        
    numberList.append(input.text!) // 把玩家輸入的數字加到陣列
    result.append("\(a)A\(b)B") // 把結果加到陣列
    tableView.reloadData() // 表格重新整理
    count += 1 // 玩家猜測次數加 1
    
    if a == 4 {
        print("遊戲結束,你共猜了\(count)次")
    }
}
  • 表格所需要的對話。
extension SecondViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return numberList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = numberList[indexPath.row]
        cell.detailTextLabel?.text = result[indexPath.row]
        return cell
    }
    
}
  • Table View Cell 的 Style 請選擇 Right Detail,否則 detailTextLabel 是顯示不出來的。
    https://ithelp.ithome.com.tw/upload/images/20200929/201296807mrwlcgFt8.png

  • 今日成果。


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

尚未有邦友留言

立即登入留言