// // SectionView.swift // Yahtzee // // Created by Guy Lapalme on 2023-08-08. // import SwiftUI class Section:ObservableObject { var names:[String] @Published var scores:[Int] = [] @Published var selected:[Bool] = [] init(_ names:[String]){ self.names = names self.init_scores() } func init_scores(){ scores = [Int](repeating: -1, count: names.count) selected = [Bool](repeating: false, count: names.count) } func clear_unselected(){ for i in selected.indices { if !selected[i] { scores[i] = -1 } } } func set_scores(values:[Int]){ for i in values.indices { if !selected[i] { scores[i]=values[i] } } } func all_selected()->Bool { selected.allSatisfy {$0} } func any_selected()->Bool{ // for debugging end of game selected.contains(true) } func total() -> Int { zip(selected,scores).filter{$0.0}.map{$1}.reduce(0,+) } } struct CategoryView:View { var kind:String @Binding var score:Int var body: some View { HStack{ Text(kind) Spacer() Text(score<0 ? "—" : String(score)) } .padding(.horizontal) .font(.title2) } } struct SectionView:View { @ObservedObject var section:Section let action:()->Void // call back on parent... @EnvironmentObject var selectColor:SelectColor var body: some View { VStack{ ForEach(section.names.indices,id: \.self) { i in CategoryView(kind:section.names[i], score: $section.scores[i]) .background(section.selected[i] ? selectColor.color : .clear) .onTapGesture { if !section.selected[i]{ section.selected[i] = true action() } } } }.padding(.vertical).border(.black) } }