Python 控制台格斗游戏:火柴人对战
这是一个简单的控制台格斗游戏的代码示例,两个火柴人角色通过键盘控制进行攻击,直到一方血条清空获胜:
class Fighter:
def __init__(self, name, hp, attack_power):
self.name = name
self.hp = hp
self.attack_power = attack_power
def attack(self, opponent):
opponent.hp -= self.attack_power
def is_alive(self):
return self.hp > 0
def main():
fighter1 = Fighter('Fighter 1', 100, 10)
fighter2 = Fighter('Fighter 2', 100, 10)
while fighter1.is_alive() and fighter2.is_alive():
# Fighter 1 Controls
print(f'{fighter1.name}'s turn:')
print('Press 'a' to attack')
choice = input().lower()
if choice == 'a':
fighter1.attack(fighter2)
else:
print('Invalid input. Skip turn.')
# Check if Fighter 2 is defeated
if not fighter2.is_alive():
print(f'{fighter1.name} wins!')
break
# Fighter 2 Controls
print(f'{fighter2.name}'s turn:')
print('Press 'a' to attack')
choice = input().lower()
if choice == 'a':
fighter2.attack(fighter1)
else:
print('Invalid input. Skip turn.')
# Check if Fighter 1 is defeated
if not fighter1.is_alive():
print(f'{fighter2.name} wins!')
break
if __name__ == '__main__':
main()
代码中,Fighter 类代表火柴人战斗者,拥有姓名、生命值和攻击力属性。战斗者可以进行攻击行为,减少对手生命值造成伤害。is_alive 方法用于判断战斗者是否存活。
main 函数创建两个战斗者对象,使用循环模拟战斗过程。每个战斗者依次控制攻击行为,通过按下键盘上的 'a' 键进行攻击。当一方生命值降为零时,游戏结束,输出获胜者的信息。
原文地址: https://www.cveoy.top/t/topic/qBQy 著作权归作者所有。请勿转载和采集!