写一个python飞机游戏代码
时间: 2023-08-24 17:32:09 浏览: 107
好的,下面是一个简单的Python飞机游戏代码示例:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小和标题
screen_width = 480
screen_height = 700
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("飞机大战")
# 加载游戏背景图和飞机图片
background = pygame.image.load("images/background.png").convert()
player_img = pygame.image.load("images/player.png").convert_alpha()
enemy_img = pygame.image.load("images/enemy.png").convert_alpha()
# 设置游戏时钟和帧率
clock = pygame.time.Clock()
FPS = 60
# 定义玩家飞机类
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = player_img
self.rect = self.image.get_rect()
self.rect.centerx = screen_width // 2
self.rect.bottom = screen_height - 10
self.speed_x = 0
self.speed_y = 0
def update(self):
self.rect.x += self.speed_x
self.rect.y += self.speed_y
if self.rect.left < 0:
self.rect.left = 0
elif self.rect.right > screen_width:
self.rect.right = screen_width
elif self.rect.top < 0:
self.rect.top = 0
elif self.rect.bottom > screen_height:
self.rect.bottom = screen_height
# 定义敌机类
class Enemy(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = enemy_img
self.rect = self.image.get_rect()
self.rect.x = random.randint(0, screen_width - self.rect.width)
self.rect.y = random.randint(-100, -40)
self.speed_y = random.randint(1, 3)
def update(self):
self.rect.y += self.speed_y
if self.rect.top > screen_height:
self.kill()
# 创建玩家飞机和敌机精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
# 游戏主循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.speed_x = -5
elif event.key == pygame.K_RIGHT:
player.speed_x = 5
elif event.key == pygame.K_UP:
player.speed_y = -5
elif event.key == pygame.K_DOWN:
player.speed_y = 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
player.speed_x = 0
elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player.speed_y = 0
# 生成敌机
if random.randint(1, 60) == 1:
enemy = Enemy()
all_sprites.add(enemy)
enemies.add(enemy)
# 更新精灵组
all_sprites.update()
# 检测敌机和玩家飞机的碰撞
hits = pygame.sprite.spritecollide(player, enemies, False)
if hits:
running = False
# 绘制游戏界面
screen.blit(background, (0, 0))
all_sprites.draw(screen)
# 刷新屏幕
pygame.display.flip()
# 控制帧率
clock.tick(FPS)
# 退出游戏
pygame.quit()
```
这个游戏会在窗口中显示一个玩家飞机和一些敌机,玩家可以使用箭头键控制飞机移动,避免和敌机撞击。当玩家撞到敌机时,游戏结束。
阅读全文