python大鱼吃小鱼_python 游戏编程 大鱼吃小鱼
时间: 2023-10-12 12:15:36 浏览: 345
用pygame制作大鱼吃小鱼游戏
大鱼吃小鱼是一个经典的游戏,可以用 Python 编程实现。下面是一个简单的示例代码:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
window_width = 640
window_height = 480
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Big Fish Eats Small Fish")
# 加载图像资源
bg_image = pygame.image.load("background.jpg")
fish_image = pygame.image.load("fish.png")
# 设置游戏参数
fish_size = 50
fish_speed = 5
fish_x = window_width / 2 - fish_size / 2
fish_y = window_height / 2 - fish_size / 2
fish_direction = "right"
fish_score = 0
small_fish_size = 20
small_fish_speed = 3
small_fishes = []
# 随机生成小鱼
def generate_small_fish():
x = random.randint(0, window_width - small_fish_size)
y = random.randint(0, window_height - small_fish_size)
small_fishes.append({"x": x, "y": y})
# 游戏循环
running = True
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 更新游戏状态
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
fish_x -= fish_speed
fish_direction = "left"
elif keys[pygame.K_RIGHT]:
fish_x += fish_speed
fish_direction = "right"
elif keys[pygame.K_UP]:
fish_y -= fish_speed
elif keys[pygame.K_DOWN]:
fish_y += fish_speed
# 碰撞检测
for small_fish in small_fishes:
if fish_x < small_fish["x"] + small_fish_size and \
fish_x + fish_size > small_fish["x"] and \
fish_y < small_fish["y"] + small_fish_size and \
fish_y + fish_size > small_fish["y"]:
small_fishes.remove(small_fish)
fish_score += 1
# 生成新的小鱼
if len(small_fishes) == 0:
generate_small_fish()
# 绘制游戏界面
window.blit(bg_image, (0, 0))
for small_fish in small_fishes:
pygame.draw.rect(window, (0, 0, 255), (small_fish["x"], small_fish["y"], small_fish_size, small_fish_size))
if fish_direction == "right":
fish_image = pygame.transform.flip(fish_image, True, False)
window.blit(fish_image, (fish_x, fish_y))
pygame.display.update()
# 更新小鱼位置
for small_fish in small_fishes:
if fish_x < small_fish["x"]:
small_fish["x"] -= small_fish_speed
elif fish_x > small_fish["x"]:
small_fish["x"] += small_fish_speed
if fish_y < small_fish["y"]:
small_fish["y"] -= small_fish_speed
elif fish_y > small_fish["y"]:
small_fish["y"] += small_fish_speed
# 游戏结束条件
if fish_score >= 10:
running = False
# 结束游戏
pygame.quit()
```
这个示例代码实现了一个简单的大鱼吃小鱼游戏。在游戏中,玩家控制大鱼移动,吃掉屏幕上随机生成的小鱼,直到获得足够的分数。游戏过程中需要注意碰撞检测和小鱼的移动。
阅读全文