在这个简单的游戏中,有一类战斗机,其目的是使两名战斗机战斗。生命值低于0的人将失去游戏。
为了打架,需要进行静态方法打架(..),直到一个战斗机赢得游戏为止,并由另一种非静态方法打架(..)支持
对象战斗机的健康状况应随着两个对象在游戏中使用斗殴(...)和攻击(...)进行战斗而改变。问题在于它总是打印出相同的Fighter健康状况,并且游戏永远不会结束。我看不出问题在哪里
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let david = Fighter(name: "David", health: 100, damage: 30, defense: 10, initiative: 80)
let goliath = Fighter(name: "Goliath", health: 300, damage: 60, defense: 14, initiative: 90)
let myFight1 = Fighter.fight(fighter1: david, fighter2: goliath) // always executing same Fighters
print(myFight1)
}
}
import Foundation
struct Fighter {
var name: String
var health: Double
var damage: Int
var defense: Int
var initiative: Int
init (name: String, health: Double, damage: Int, defense: Int, initiative: Int) {
self.name = name
self.health = health
self.damage = damage
self.defense = defense
self.initiative = initiative
}
init (name: String, health: Double, damage: Int, defense: Int) {
self.name = name
self.health = health
self.damage = damage
self.defense = defense
self.initiative = 0
}
static func fight(fighter1: Fighter, fighter2: Fighter) -> Fighter {
let f1 = fighter1
let f2 = fighter2
if f1.health == f2.health {
return f1
}
if f2.initiative > f1.initiative {
f2.attack(f: f1)
}
var i = 0
while f1.health > 0 {
i += 1
print("--> i: \(i)")
f1.attack(f: f2 )
if f2.health <= 0 {
return f1
}
f2.attack(f: f1)
}
return f2
}
func attack(f: Fighter) -> Void {
var g = f
g.health = g.health - Double(g.damage * (1 - g.defense / 100))
print(g)
}
}
最佳答案
您正在使用struct
作为Fighter
,这是Swift中的值类型。
值类型最基本的区别在于复制-赋值,初始化和参数传递的效果-
创建一个具有其数据唯一副本的独立实例
解决方案:将Fighter
更改为class
,就可以了。
输出打印语句的:(第二个打印语句已更改为print(g.name, g.health)
)
大卫70.0
->我:1
巨人240.0
大卫40.0
->我:2
巨人180.0
大卫10.0
->我:3
巨人120.0
大卫-20.0
有关更多阅读:Value and Reference Types