用Python定义一个飞机类,创建两个飞机对象,F22和J20,模拟两机空战
时间: 2024-03-16 22:41:30 浏览: 145
使用python实现飞机大战游戏
5星 · 资源好评率100%
好的,下面是用Python定义飞机类的代码:
```python
class Plane:
def __init__(self, name, speed, attack):
self.name = name
self.speed = speed
self.attack = attack
self.health = 100
def attack_plane(self, plane):
plane.health -= self.attack
def __str__(self):
return f'{self.name} (speed: {self.speed}, attack: {self.attack}, health: {self.health})'
```
然后我们可以创建两个飞机对象,F22和J20:
```python
f22 = Plane('F22', 2000, 50)
j20 = Plane('J20', 1800, 60)
```
模拟两机空战,可以使用一个循环,每次让两架飞机互相攻击一次,直到有一架飞机的血量小于等于0:
```python
while f22.health > 0 and j20.health > 0:
f22.attack_plane(j20)
print(f'{f22.name} attacks {j20.name}! {j20.name} health: {j20.health}')
j20.attack_plane(f22)
print(f'{j20.name} attacks {f22.name}! {f22.name} health: {f22.health}')
if f22.health > 0:
print(f'{f22.name} wins!')
else:
print(f'{j20.name} wins!')
```
运行以上代码,就可以模拟两机空战了。
阅读全文