// // ContentView.swift // DiceViewWithList // // Created by Guy Lapalme on 2023-07-28. // import SwiftUI struct ContentView: View { @State private var move:String = "Roll" @State private var nbRolls:Int = 0 @StateObject private var dice = Dice() @StateObject private var upper_section = Section(["Aces", "Twos", "Threes", "Fours", "Fives", "Sixes"]) @State private var upper_total:Int = 0 @State private var upper_bonus:Int = 0 @StateObject private var lower_section = Section(["3 of a kind", "4 of kind", "Full house", "Small straight", "Large straight", "Yahtzee","Chance"]) @State private var lower_total = 0 @State private var grand_total = 0 @StateObject var selectColor = SelectColor() func roll_dice(){ nbRolls += 1 if nbRolls <= 3 { dice.roll() if nbRolls == 3 { show_scores() move = "Score" } } } func show_scores(){ let (upper,lower) = yathzeeScores(dice: dice.dice) upper_section.set_scores(values:upper) lower_section.set_scores(values:lower) } func update_totals(){ upper_section.clear_unselected() lower_section.clear_unselected() upper_total = upper_section.total() upper_bonus = upper_total >= 63 ? 35 : 0 lower_total = lower_section.total() grand_total = upper_total + upper_bonus + lower_total dice.clear_fixed() move = "Roll" nbRolls=0 } func restart(){ upper_section.init_scores() lower_section.init_scores() update_totals() } var body: some View { VStack { HStack (spacing:3){ // top view with dice and buttons DiceView(dice: dice) Button (move,action:roll_dice) .frame(width: 90) .buttonStyle(.bordered) .fixedSize() Button ("C", action: selectColor.nextColor) } SectionView(section: upper_section,action: update_totals) CategoryView(kind: "Upper section total",score: $upper_total) CategoryView(kind: "Upper section bonus",score: $upper_bonus) SectionView(section: lower_section,action: update_totals) CategoryView(kind: "Lower section total", score: $lower_total) CategoryView(kind: "Grand total", score: $grand_total) if upper_section.all_selected() && lower_section.all_selected(){ // must call .init() so that Markdown string interpolation works Button (.init("*Game over: \(grand_total) points*\nClick to restart"), action:restart) .font(.title) .buttonStyle(.bordered) } }.environmentObject(selectColor) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }