Hello everyone, quick question, in Swift, how to limit numbers? I'm practicing on the creation of a game between 2 players, and I want the limit of health points of my characters to be exactly between 0 and 100. If my character loses health points, I don't want it to fall to -10 (negative) and on the contrary if he gains health points, I don't want it to exceed 100 health points.
I'm an beginner, I'm starting with Swift
There is my code :
I'm an beginner, I'm starting with Swift
There is my code :
Code Block // MARK: - Characters class Character { var name: String var lives: Int // health points var power : Int init(name: String, lives: Int, power: Int) { self.name = name self.lives = lives self.power = power } convenience init(){ self.init(name:"", lives: 100, power: 0) } // get heal // func heal(anotherCharacter: Character){ if anotherCharacter.lives < 100{ anotherCharacter.lives += 20 } } // attack another character // func attack(otherCharacter: Character){ otherCharacter.lives -= power } } // MARK: - Soldier A class SoldierA: Character{ override init(name: String, lives: Int, power: Int) { super.init(name: "Daniel", lives: 100, power: 50) } } // MARK: - Soldier B class SoldierB: Character{ override init(name: String, lives: Int, power: Int) { super.init(name: "Mark", lives: 100, power: 50) } } // MARK: - Fight let player1 = SoldierA() let player2 = SoldierB() player1.attack(otherCharacter: player2) player1.attack(otherCharacter: player2) player1.attack(otherCharacter: player2) player2.lives player1.heal(anotherCharacter: player1) player1.lives