【发布时间】:2018-10-03 12:33:19
【问题描述】:
在这个简单的游戏中,有一个职业战士,其目的是让两个战士战斗。生命值低于 0 的人将输掉比赛。
为了战斗,有一个静态方法战斗(..)迭代直到一个战士赢得比赛,由另一个非静态方法攻击(..)支持
object Fighter 的生命值应该随着两个对象在游戏中使用fight(...) 和attack (...) 方法进行战斗而改变。问题是它总是打印相同的战斗机健康状况,并且游戏永远不会结束。我看不出问题出在哪里
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)
}
}
【问题讨论】:
-
战士的
damage和defense值是多少? -
你在问这个吗?
-
let david = Fighter(name: "David", 生命值: 100, 伤害: 30, 防御: 10, 主动性: 80) let goliath = Fighter(name: "Goliath", 生命值: 300,伤害:60,防御:14,先攻:90)
-
任一a)您需要为战士创建一个
mutating健康属性,并且需要在每次迭代后更新健康值;或 b) 使战士class并在每次迭代后更新健康值;或 c) 在评估期间将战士的健康值存储在本地范围内,以逐渐降低它们;或 d) 放弃 while 循环并计算每个战斗机的命中数,然后比较这些值以宣布获胜者。
标签: ios swift swift-structs swift-class