如何用布尔值使“无法定位”的选择?

时间:2018-11-27 10:45:06

标签: ios swift

我正在与2位玩家一起为学校制作RPG游戏,两位玩家都将选择3个角色进行战斗!当其中一个角色的生命值耗尽时,他就死了!

实际上我试图弄清楚我该怎么做,我已经使函数死亡了,这里是:

 public func death(to attacker: Character, of target: Character, from ennemyPlayer: Player){
    if healthpoint <= 0 {
        isDead = true
        print("\(target.name) is KO")
    }
}

但是我不知道在哪里放置我的函数以使其成为不可定向的选择,例如,如果一个玩家选择了一个0hp的角色,它说print(“此字符已死”)

我通过此功能选择了一个字符(此功能与死亡功能不在同一个文件夹中):

 //function to choose a fighter
func chooseChar(charac: inout[Character]){

    var attacker: Character
    var inputRole: Bool = false

    repeat{
        let choice = readLine()
        switch choice {
        case "1":
            attacker = self.playerTeam[0]
            charac.append(attacker)
            inputRole = true
        case "2":
            attacker = self.playerTeam[1]
            charac.append(attacker)
            inputRole = true
        case "3":
            attacker = self.playerTeam[2]
            charac.append(attacker)
            inputRole = true
        default:
            print("choose between 1, 2 or 3")
            inputRole = false
        }
    } while inputRole == false
}

非常感谢您的帮助!祝你有美好的一天

1 个答案:

答案 0 :(得分:1)

您可以将isDead作为计算属性添加到您的Character类中:

class Character {
    var hp: Int
    var isDead: Bool {
        return hp < 1
    }
}

通过调整数组大小,可以使chooseChar函数更加灵活。此函数还应该返回选定的字符,而不是使用inout数组:

func chooseChar(characters: [Character]) -> Character {

    var attacker: Character?

    repeat{
        let line = readLine()
        if let choice = Int(line), 
           choice > 0, 
           choice <= characters.count {
               let selection = characters[choice-1]
               if selection.isDead {
                   print("\(selection.name) is already dead!")
               } else {
                   attacker = selection
               }
        } else {
            print("Please enter a number between 1 and \(characters.count)"
        }
    } while attacker == nil
    return attacker
}