丟骰子

水餃
Oct 23, 2020

主要程式

struct Dice: Identifiable {

var id = UUID()

let max: Int

var number: Int

}

struct ContentView: View {

@State var number = Int.random(in: 1…6)

@State var dices = [Dice(max: 6, number: 1), Dice(max: 8, number: 1)]

var sum: Int {

var all = 0

for dice in dices {

all = all + dice.number

}

return all

}

var body: some View {

VStack {

HStack {

ForEach(dices) { (dice) in

Image(“\(dice.number)”)

.resizable()

.frame(width: 100, height: 100)

.background(Color.blue)

}

}

Button(action: {

for i in self.dices.indices {

self.dices[i].number = Int.random(in: 1…self.dices[i].max)

}

}) {

Text(“Roll”)

}

HStack {

Button(action: {

// self.dices.append(<#T##newElement: Dice##Dice#>)

}) {

Text(“4”)

}

Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {

Text(“6”)

}

Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {

Text(“8”)

}

Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {

Text(“10”)

}

Button(action: /*@START_MENU_TOKEN@*/{}/*@END_MENU_TOKEN@*/) {

Text(“12”)

}

}

Text(“總計\(sum)”)

}

}

}

struct ContentView_Previews: PreviewProvider {

static var previews: some View {

ContentView()

}

}

--

--