pygame做一个大鱼吃小鱼
时间: 2023-10-05 15:11:35 浏览: 199
Pygame 大鱼吃小鱼
5星 · 资源好评率100%
以下是一个使用Pygame实现的简单的大鱼吃小鱼游戏的代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义屏幕的宽度和高度
screen_width = 800
screen_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
# 设置游戏窗口标题
pygame.display.set_caption("Fish Eat Fish")
# 加载背景图像
background_image = pygame.image.load("background.jpg")
background_image = pygame.transform.scale(background_image, (screen_width, screen_height))
# 加载鱼的图像
player_image = pygame.image.load("player_fish.png")
player_rect = player_image.get_rect()
player_rect.centerx = screen_width / 2
player_rect.centery = screen_height / 2
# 加载小鱼的图像
fish_image = pygame.image.load("fish.png")
# 定义颜色变量
WHITE = (255, 255, 255)
# 创建游戏时钟
clock = pygame.time.Clock()
# 定义小鱼列表
fish_list = []
for _ in range(20):
fish_rect = fish_image.get_rect()
fish_rect.x = random.randint(0, screen_width - fish_rect.width)
fish_rect.y = random.randint(0, screen_height - fish_rect.height)
fish_list.append(fish_rect)
# 创建得分变量
score = 0
# 创建游戏循环
game_running = True
while game_running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
# 检测键盘按键状态
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_rect.x -= 5
if keys[pygame.K_RIGHT]:
player_rect.x += 5
if keys[pygame.K_UP]:
player_rect.y -= 5
if keys[pygame.K_DOWN]:
player_rect.y += 5
# 碰撞检测
for fish_rect in fish_list:
if player_rect.colliderect(fish_rect):
fish_list.remove(fish_rect)
score += 1
# 填充背景颜色
screen.fill(WHITE)
# 绘制背景图像
screen.blit(background_image, (0, 0))
# 绘制玩家鱼
screen.blit(player_image, player_rect)
# 绘制小鱼
for fish_rect in fish_list:
screen.blit(fish_image, fish_rect)
# 绘制得分文本
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, WHITE)
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.update()
# 设置游戏帧率
clock.tick(60)
# 关闭Pygame
pygame.quit()
```
请注意,这只是一个基本的示例,游戏中可能还需要添加更多的功能和逻辑来使其更完整和有趣。你可以根据自己的需求进行修改和扩展。同时,你需要准备背景图像、鱼的图像以及玩家鱼的图像,并将它们与代码中的文件名相对应。
阅读全文