编一个大鱼吃小鱼的游戏
时间: 2023-08-26 15:07:01 浏览: 278
好的,下面是一个大鱼吃小鱼的游戏的基本代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置屏幕大小和标题
screen_width = 600
screen_height = 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Fish Eat Fish')
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 加载游戏图片
fish_img = pygame.image.load('fish.png')
fish_img = pygame.transform.scale(fish_img, (50, 50))
fish_small_img = pygame.image.load('fish_small.png')
fish_small_img = pygame.transform.scale(fish_small_img, (30, 30))
# 定义鱼类
class Fish(pygame.sprite.Sprite):
def __init__(self, x, y, speed):
super().__init__()
self.image = fish_img
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = speed
def update(self):
self.rect.x += self.speed
if self.rect.left > screen_width:
self.rect.right = 0
# 定义小鱼类
class SmallFish(pygame.sprite.Sprite):
def __init__(self, x, y, speed):
super().__init__()
self.image = fish_small_img
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.speed = speed
def update(self):
self.rect.x += self.speed
if self.rect.left > screen_width:
self.rect.right = 0
self.rect.y = random.randint(0, screen_height - self.rect.height)
# 创建鱼
player_fish = Fish(0, screen_height // 2, 5)
small_fish_group = pygame.sprite.Group()
for i in range(10):
small_fish = SmallFish(random.randint(0, screen_width - 30), random.randint(0, screen_height - 30), random.randint(1, 3))
small_fish_group.add(small_fish)
# 设置游戏帧率
clock = pygame.time.Clock()
FPS = 30
# 游戏循环
game_over = False
while not game_over:
# 事件处理
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 更新鱼的位置
player_fish.update()
small_fish_group.update()
# 碰撞检测
small_fish_hit_group = pygame.sprite.spritecollide(player_fish, small_fish_group, True)
for small_fish in small_fish_hit_group:
player_fish.image = fish_img
player_fish.rect = player_fish.image.get_rect()
player_fish.rect.x = 0
player_fish.rect.y = screen_height // 2
small_fish = SmallFish(random.randint(0, screen_width - 30), random.randint(0, screen_height - 30), random.randint(1, 3))
small_fish_group.add(small_fish)
# 绘制游戏界面
screen.fill(white)
small_fish_group.draw(screen)
player_fish_group = pygame.sprite.Group(player_fish)
player_fish_group.draw(screen)
# 刷新屏幕
pygame.display.flip()
clock.tick(FPS)
# 退出游戏
pygame.quit()
```
这个游戏中,你是一条大鱼,需要吃掉屏幕上的小鱼,每吃掉一条小鱼,你就会变得更大更强。如果你被小鱼碰到,那么你就会变得更小更弱。游戏很简单,但是却很有趣,希望你喜欢!
阅读全文