编写程序简易大鱼吃小鱼(Python
时间: 2023-08-14 13:17:53 浏览: 103
好的,以下是一个简易的大鱼吃小鱼游戏的Python程序:
```python
import random
# 定义游戏区域大小
WIDTH = 800
HEIGHT = 600
# 定义颜色
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化pygame
pygame.init()
# 创建游戏窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("大鱼吃小鱼")
# 加载图片
fish_image = pygame.image.load("fish.png")
fish_rect = fish_image.get_rect()
small_fish_image = pygame.image.load("small_fish.png")
small_fish_rect = small_fish_image.get_rect()
# 初始化小鱼位置和速度
small_fish_x = random.randint(0, WIDTH - small_fish_rect.width)
small_fish_y = random.randint(0, HEIGHT - small_fish_rect.height)
small_fish_speed = 5
# 初始化大鱼位置和速度
fish_x = WIDTH / 2
fish_y = HEIGHT / 2
fish_speed = 10
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 获取按键状态
keys = pygame.key.get_pressed()
# 处理按键事件
if keys[pygame.K_LEFT]:
fish_x -= fish_speed
if keys[pygame.K_RIGHT]:
fish_x += fish_speed
if keys[pygame.K_UP]:
fish_y -= fish_speed
if keys[pygame.K_DOWN]:
fish_y += fish_speed
# 处理小鱼移动
small_fish_x += small_fish_speed
if small_fish_x > WIDTH:
small_fish_x = 0 - small_fish_rect.width
small_fish_y = random.randint(0, HEIGHT - small_fish_rect.height)
# 判断是否吃到小鱼
if fish_rect.colliderect(small_fish_rect):
small_fish_x = 0 - small_fish_rect.width
small_fish_y = random.randint(0, HEIGHT - small_fish_rect.height)
# 绘制游戏界面
screen.fill(WHITE)
screen.blit(fish_image, (fish_x, fish_y))
screen.blit(small_fish_image, (small_fish_x, small_fish_y))
pygame.display.update()
```
在运行程序之前,你需要下载两张图片(分别为大鱼和小鱼的图片),并将它们保存在程序所在的目录下,然后在代码中将它们的路径替换成你自己的路径。
运行程序后,你可以使用方向键来控制大鱼的移动,当大鱼碰到小鱼时,小鱼会被吃掉并重新生成一个新的小鱼。
阅读全文