首页 > 解决方案 > 为什么这个重复循环没有停止?

问题描述

伙计们,我写了这个小代码来模拟口袋妖怪的捕捉,有三种类型的精灵球和两种类型的浆果。我想重复使用浆果来降低口袋妖怪的 kp,以便用减少后足够强的精灵球来捕捉它。该功能正在启动,但重复循环并未停止!口袋妖怪被抓住了,但它并没有停下来。有人可以帮助我使这段代码正常工作吗?提前致谢!

struct Pokeball {
    var name: String
    var power: Int
}
var pokeball = Pokeball(name: "Pokeball", power: 5)
var superball = Pokeball(name: "superball", power: 7)
var hyperball = Pokeball(name: "Hyperball", power: 10)

struct Berries {
    var name: String
    var power: Int
}
var himmihberry = Berries(name: "himmihberry", power: 1)
var goldenBerry = Berries(name: "golden Berry", power: 3)

struct Pokemon {
    var name: String
    var wp: Int
    var kp: Int
}
var glumanda = Pokemon(name: "Glumanda", wp: 10, kp: 6)
var dialga = Pokemon(name: "Dialga", wp: 30, kp: 25)

struct Poketrainer {
    var name: String
    var balls: Int
    var berries: Int
    var pokemons: [Pokemon]
    mutating func Catching(pokemonToCatch: Pokemon, usingBall: Pokeball, usedBerry: Berries) {
        var pokemonToCatch = pokemonToCatch
        repeat {
            print("\(name) is using \(usedBerry.name)...")
            pokemonToCatch.kp -= usedBerry.power
            berries -= 1
            
            print("\(name) is throwing a \(usingBall.name) to catch \(pokemonToCatch.name)")
            if usingBall.power > pokemonToCatch.kp {
                pokemons.append(pokemonToCatch)
                print("\(pokemonToCatch.name) was caught!")
                balls -= 1
            } else {
                print("Pokemon was to strong...")
            }
            
        } while balls > 0 || pokemons.count < 0
                print("Hunt is over...")
            }
    }
    
    
var ash = Poketrainer(name: "Ash", balls: 3, berries: 5, pokemons: [])
ash.Catching(pokemonToCatch: glumanda, usingBall: superball, usedBerry: himmihberry)
print("balls: \(ash.balls), pokemon: \(ash.pokemons.count)")

标签: swiftfunctionrepeat

解决方案


您可能想balls -= 1print("Pokemon was too strong"). 我假设无论你是否抓住了口袋妖怪,球都会被消耗掉


推荐阅读