pygame小游戏代码
时间: 2023-07-23 22:49:14 浏览: 83
以下是一个简单的 Pygame 小游戏代码示例,名为“打飞机”:
```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("background.png")
# 加载飞机图片
player = pygame.image.load("player.png")
player_width, player_height = player.get_rect().size
player_x = (screen_width - player_width) // 2
player_y = screen_height - player_height
# 定义敌机
enemy = pygame.image.load("enemy.png")
enemy_width, enemy_height = enemy.get_rect().size
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = 0
enemy_speed = 5
# 定义游戏循环
clock = pygame.time.Clock()
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 绘制背景
screen.blit(background, (0, 0))
# 移动飞机
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_x > 0:
player_x -= 5
if keys[pygame.K_RIGHT] and player_x < screen_width - player_width:
player_x += 5
if keys[pygame.K_UP] and player_y > 0:
player_y -= 5
if keys[pygame.K_DOWN] and player_y < screen_height - player_height:
player_y += 5
# 绘制飞机
screen.blit(player, (player_x, player_y))
# 移动敌机
enemy_y += enemy_speed
if enemy_y > screen_height:
enemy_x = random.randint(0, screen_width - enemy_width)
enemy_y = 0
# 绘制敌机
screen.blit(enemy, (enemy_x, enemy_y))
# 判断是否碰撞
player_rect = pygame.Rect(player_x, player_y, player_width, player_height)
enemy_rect = pygame.Rect(enemy_x, enemy_y, enemy_width, enemy_height)
if player_rect.colliderect(enemy_rect):
running = False
# 刷新屏幕
pygame.display.update()
# 控制游戏帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
该游戏包括一个玩家飞机和一个敌机,玩家通过键盘控制飞机移动,敌机会从屏幕顶部往下移动。当玩家和敌机发生碰撞时,游戏结束。
阅读全文