BlackJack App
Published in
4 min readDec 13, 2022
目的:練習UIAlertController、 UIAlertAction、MVC架構
重點整理:
創建五十二張卡片
let suits = ["♣️", "♦️", "♥️", "♠️"]
let ranks = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
var cards = [Card]()
struct Card {
var suit = ""
var rank = ""
}
func addCard() {
for rank in ranks {
for suit in suits {
var card = Card()
card.rank = rank
card.suit = suit
cards.append(card)
}
}
}
判斷卡片的數字
func calculateRankNumber(card: Card) ->Int {
var cardRankNumber = 0
switch card.rank{
case "A":
cardRankNumber = 1
case "J","Q","K":
cardRankNumber = 10
default:
cardRankNumber = Int(card.rank)!
}
return cardRankNumber
}
判斷輸贏,完整程式碼放在GitHub
if bankerScore > playerScore && bankerScore <= 21 {
let controller = UIAlertController(title: "You Lose", message: "Banker:\(bankerScore)\nPlayer:\(playerScore)", preferredStyle: .alert)
let action = UIAlertAction(title: "Play Again", style: .default) { action in
self.initGame() //這裡是closure所以funtion前面加self.
}
controller.addAction(action)
present(controller, animated: true)
賭金選擇使用UISegmentedControl
func betPlus() { //玩家贏
if betNum.selectedSegmentIndex == 0 {
bet += 50
betLabel.text = String(bet)
} else {
bet += 100
betLabel.text = String(bet)
}
}
func betMinus() { //玩家輸
if betNum.selectedSegmentIndex == 0 {
bet -= 50
betLabel.text = String(bet)
} else {
bet -= 100
betLabel.text = String(bet)
}
}