おそるおそるSwift 3-3 熱中時代ジャンケン編を作る ~勝敗判定を改良する~

Swift5+Xcode11.6

今回のゴール

 シリーズ3の3回目です。

 勝敗判定コードをよりスマートにします。内部処理のみの改良ですので、動作結果は前回と変わりません。

ユーザ定義関数を作る

 再利用するコードなので、ユーザ定義関数hanteiを作り、供用することにしました。ContentVIew.swiftの既存の2つのstructの他に、func hantei {}(52〜64行目)を作りました。
 hantei関数は、human1とcomp1の2つの引数から勝敗を判定します。コードをスマートにするために、(1)タプルと、(2)switch文を使用しました。タプルとは、複数の値を1個の値として扱う機能です。53行目でkekkaとして宣言しているのがそれです。また、条件分岐は「勝ち」「負け」「引き分け」の3種類と決まっているので、if~elseではなく、switch文を使って簡潔な記述にしました。
 最後にそれぞれのボタンのアクション文のif文をhantei(human1:self.human, comp1:self.comp)に書き換えました。

import SwiftUI

struct ContentView: View {
    @State var msg: String = "Jan Ken"
    @State var human: Int = 0
    @State var comp: Int = 0
    let choice = ["グー","チョキ","パー"]
    
    var body: some View {
        VStack {
            Image(choice[self.comp])
                .rotationEffect(.degrees(180))
            Image(choice[self.human])
            if self.human == 0 {
                Text("\(msg)")
            } else {
                Text("Pon!")
            }
            HStack {
                Button(action: {
                    self.human = 0
                    self.comp = Int.random(in: 0...2)
                    hantei(human1:self.human, comp1:self.comp)
                }) {
                    Text("グー")
                }
                Button(action: {
                    self.human = 1
                    self.comp = Int.random(in: 0...2)
                    hantei(human1:self.human, comp1:self.comp)
                }) {
                    Text("チョキ")
                }
                Button(action: {
                    self.human = 2
                    self.comp = Int.random(in: 0...2)
                    hantei(human1:self.human, comp1:self.comp)
                }) {
                    Text("パー")
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

func hantei(human1: Int, comp1: Int) {
    let kekka:(Int, Int) = (human1, comp1)
    switch  kekka {
    case (0, 0),(1, 1),(2, 2) :
        print("Draw!")
    case (0, 1),(1, 2),(2, 0) :
        print("Win!")
    case (0, 2),(1, 0),(2, 1) :
        print("Lose!")
    default :
        print("?")
    }
}

次回は

 勝敗の結果をデバッグウィンドウではなく、画面に表示できるようにします。

Bergamot

シェアする

コメントを残す

メールアドレスが公開されることはありません。

コメントする