おそるおそるSwift 4-4 ハイローゲームを作る ~敗者は去るのみ~

Swift5+Xcode11.6
今回のゴール
おそるおそる機能を追加していくことにして、今回は買ったら賞金を増額、1回でも負けたら全てを失って最初に戻る、というハイ&ローゲームのルールに沿った処理を作りたいと思います。
まあ、簡単です
大したことはしていません。Processorクラスに少し処理を足して、勝った時は報酬を倍に、負けた場合は報酬を没収して、履歴をリセットしています。最後に報酬額をきちんと出力できるよう、ContentVIew.swiftの”$1″部分を変数に置き換えました。”Lose! You Lost All Money!!”と言いながら、$1残しているのは、ゼロにしてしまうといつまで経っても0のままだからです(分岐処理が面倒なので妥協しました)。
//processorx.swift import Foundation class Processor : ObservableObject { @Published var history :[Int] = [5] //history:抽選数字履歴保持用配列 @Published var result: String = "" @Published var reward: Int = 1 var randNum: Int = 0 //randNum:乱数 // func judge(choice:String) -> String { func judge(choice:String) { randNum = Int.random(in:1...9) history.append(self.randNum) for (index, his) in history.enumerated() { print("history[\(index)]: \(his)") } print("endIndex:\(history.endIndex)") let prevNum:Int = history[history.endIndex - 2] //prevNum:1つ前の抽選数字 print ("prevNum:\(prevNum)") let nowNum:Int = history[history.endIndex - 1] //nowNum:今回の抽選数字 print ("NowNum:\(nowNum)") if (nowNum == prevNum) || ((nowNum >= prevNum)&&(choice == "high")) || ((nowNum <= prevNum)&&( choice == "low")) { result = "Win" reward *= 2 } else { result = "Lose! You Lost All Money!!" reward = 1 history = [5] } } func num(times:Int) -> String { if history.endIndex >= times { return String(history[history.endIndex - times]) } else { return "-" } } }
//ContentView.swift import SwiftUI struct ContentView: View { @ObservedObject var processor = Processor() var body: some View { VStack { Text("High&Low Game!") .font(/*@START_MENU_TOKEN@*/.largeTitle/*@END_MENU_TOKEN@*/) .fontWeight(.heavy) .foregroundColor(Color.white) .background(/*@START_MENU_TOKEN@*/Color.orange/*@END_MENU_TOKEN@*/) Spacer() HStack { Spacer() Text("3回前") .frame(width: 50.0) Text("2回前") .frame(width: 50.0) Text("前回") .frame(width: 50.0) Text("今回") .font(.title) .frame(width: 80.0) Spacer() } HStack { Spacer() Text(processor.num(times:4)) .frame(width: 50.0) Text(processor.num(times:3)) .frame(width: 50.0) Text(processor.num(times:2)) .frame(width: 50.0) Text(processor.num(times:1)) .font(.largeTitle) .frame(width: 80.0) Spacer() } Spacer() HStack { Spacer() Button(action: { self.processor.judge(choice: "high") }) { Text("High") .font(.largeTitle) .fontWeight(.bold) .foregroundColor(Color.white) } .frame(width: 100.0) .background(/*@START_MENU_TOKEN@*/Color.red/*@END_MENU_TOKEN@*/) Spacer() Button(action: { self.processor.judge(choice: "low") }) { Text("Low") .font(.largeTitle) .fontWeight(.bold) .foregroundColor(Color.white) } .frame(width: 100.0) .background(Color.blue) Spacer() } Spacer() Text(processor.result) .font(.title) .fontWeight(.heavy) .foregroundColor(Color.orange) .multilineTextAlignment(.center) Text("$\(processor.reward)") .font(.largeTitle) .fontWeight(.black) .foregroundColor(Color.red) Spacer() } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
次回は
データファイルを用意して、ハイスコアを記録してみようと思います。