おそるおそるSwift 3-2 熱中時代ジャンケン編を作る ~勝敗判定させる~
Swift5+Xcode11.6
シリーズ3の2回目です。
おそるおそるSwift 3-1 熱中時代ジャンケン編を作る ~ベース部分を作る~
Swift5+Xcode11.6 基本コンセプト 「じゃんけん」は何かを決めるときによく使われる手段です。誰が自治会長をやるのか、誰が金を払うのか、誰が市長になるのか……運命の行方は「じゃんけん」によって決まると言って […]
今回のゴール
とりあえず、勝敗判定させてみます。最初に言っておきますが、この回での方法はかなり非効率です。次回以降、徐々に改良していく予定です。下の動画のようにデバッグウィンドウに勝敗を表示させます。
コードを打ち込む
今回打ち込んだコードは下のとおりです(ContentView.swift)。ボタンアクションに、if文で勝敗を判定させ、printでデバッグウィンドウに結果を表示させました。
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)
if self.comp == 1 {
print("Win!")
} else if self.comp == 2 {
print("Lose!")
} else {
print("Draw!")
}
}) {
Text("グー")
}
Button(action: {
self.human = 1
self.comp = Int.random(in: 0...2)
if self.comp == 2 {
print("Win!")
} else if self.comp == 0 {
print("Lose!")
} else {
print("Draw!")
}
}) {
Text("チョキ")
}
Button(action: {
self.human = 2
self.comp = Int.random(in: 0...2)
if self.comp == 0 {
print("Win!")
} else if self.comp == 1 {
print("Lose!")
} else {
print("Draw!")
}
}) {
Text("パー")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
次回は
複数のボタンに同じような処理を書き込んだり、if~elseを繰り返すのはスマートではありません。この部分を改良したいと思います。