飞机大战 python 代码
时间: 2024-06-11 09:02:20 浏览: 121
飞机大战是一款经典的飞行射击游戏,下面是一个简单的 Python 实现:
1. 游戏初始化
```python
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 700))
pygame.display.set_caption("Plane Game")
```
2. 加载游戏素材
```python
bg = pygame.image.load("images/background.png")
player = pygame.image.load("images/me1.png")
```
3. 实现游戏循环
```python
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
screen.blit(bg, (0, 0))
screen.blit(player, (190, 500))
pygame.display.update()
```
4. 实现玩家移动
```python
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_x -= 5
if keys[pygame.K_RIGHT]:
player_x += 5
if keys[pygame.K_UP]:
player_y -= 5
if keys[pygame.K_DOWN]:
player_y += 5
screen.blit(player, (player_x, player_y))
```
5. 实现敌机生成
```python
enemy = pygame.image.load("images/enemy1.png")
enemies = []
for i in range(5):
enemy_x = random.randint(0, 480 - enemy.get_width())
enemy_y = random.randint(-400, -enemy.get_height())
enemies.append((enemy_x, enemy_y))
for enemy_x, enemy_y in enemies:
screen.blit(enemy, (enemy_x, enemy_y))
```
6. 实现敌机移动
```python
for i in range(len(enemies)):
enemies[i] = (enemies[i], enemies[i] + 3)
if enemies[i][1] > 700:
enemy_x = random.randint(0, 480 - enemy.get_width())
enemy_y = random.randint(-400, -enemy.get_height())
enemies[i] = (enemy_x, enemy_y)
screen.blit(enemy, (enemies[i], enemies[i]))
```
7. 实现碰撞检测
```python
player_rect = pygame.Rect(player_x, player_y, player.get_width(), player.get_height())
for enemy_x, enemy_y in enemies:
enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy.get_width(), enemy.get_height())
if player_rect.colliderect(enemy_rect):
print("Game Over")
pygame.quit()
exit()
```
以上是一个简单的飞机大战 Python 实现。你可以在此基础上继续完善游戏,比如添加子弹、音效等功能。
阅读全文