写一个格斗游戏的代码
以下是一个简单的格斗游戏的代码示例:
import random
class Fighter:
def __init__(self, name, health, attack_damage):
self.name = name
self.health = health
self.attack_damage = attack_damage
def attack(self, opponent):
damage = random.randint(1, self.attack_damage)
opponent.health -= damage
print(f"{self.name}攻击了{opponent.name},造成了{damage}点伤害")
if opponent.health <= 0:
print(f"{opponent.name}被击败了!")
def main():
fighter1 = Fighter("战士1", 100, 20)
fighter2 = Fighter("战士2", 100, 20)
while fighter1.health > 0 and fighter2.health > 0:
# 随机决定哪个战士先攻击
if random.randint(0, 1) == 0:
fighter1.attack(fighter2)
else:
fighter2.attack(fighter1)
if __name__ == "__main__":
main()
这个代码创建了一个Fighter类,其中包含了格斗游戏中战士的属性和方法。attack方法用于执行战士的攻击动作,随机生成攻击伤害并减少对手的生命值。main函数创建了两个战士对象并循环执行攻击动作,直到其中一个战士的生命值降为0
原文地址: http://www.cveoy.top/t/topic/iVQE 著作权归作者所有。请勿转载和采集!