import SwiftUI
struct Player: {
@State var name: String
@State var points: Int = 0
@State var setPoints: Int = 0
@State var allPoints: Int = 0
@State var didStart: Bool
mutating func plus() -> Void {
points += 1
allPoints += 1
}
mutating func minus() -> Void {
points -= 1
allPoints -= 1
}
func wonGame() -> Bool {
if setPoints == 5 {return true}
else {return false}
}
class Game: ObservableObject {
@Published var gracz1: Player = Player(name: "Player 1", didStart: true)
@Published var gracz2: Player = Player(name: "Player2", didStart: false)
var toWinSet: Int = 11
var toWinGame: Int = 5
func whoServes() -> String {
let suma = gracz1.points + gracz2.points
if gracz1.didStart {
if suma % 4 == 2 || suma % 4 == 3 {return gracz2.name}
else {return gracz1.name}
} else {
if suma % 4 == 2 || suma % 4 == 3 {return gracz1.name}
else {return gracz2.name}
}
}
func whoWonSet() -> Void {
if gracz1.points == 11 {
gracz1.points = 0
gracz1.allPoints += 1
gracz1.didStart = false
gracz2.didStart = true
}
if gracz2.points == 11 {
gracz2.points = 0
gracz2.allPoints += 1
gracz2.didStart = false
gracz1.didStart = true
}
}
func didSomeoneWin() -> String? {
if gracz1.setPoints == toWinGame {return gracz1.name}
if gracz2.setPoints == toWinGame {return gracz2.name}
else {return nil}
}
struct ContentView: View {
let serves = "s.circle"
let notServes = ""
@ObservedObject var game = Game()
@State var showingSettings: Bool = false
let hh = UIScreen.main.bounds.height
var body: some View {
// MARK: - PLAYER SECTION
ZStack{
VStack{
Text(String(game.gracz2.points))
.font(.system(size: hh/3))
.frame(width: hh/2.5, height: hh/3)
Text(String(game.gracz2.setPoints))
.font(.system(size: hh/15))
}
HStack{
Button(action: {
game.gracz2.minus()
}, label: {
Text("-")
.foregroundColor(.primary)
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
})
Button(action: {
game.gracz2.plus();
game.whoWonSet()
}, label: {
Text("+")
.foregroundColor(.primary)
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing)
})
}
}
.background(Color("C2"))
.cornerRadius(26)
.padding()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Post
Replies
Boosts
Views
Activity
Hi,
I'd like to change the name of Player1 ("Marek") when I click save button on a setting view screen. On the main view screen, the new name only appears on a test Text (small yellow font), yet the change is not visible on the purple square (big white font).
It seems that player name from the playerView doesn't update. However adding points (which are also displayed from the playerView) work just fine.
Here is the code:
https://github.com/Voytsh/GameHelpPls
I'd extremely thankful for your help