给我写一个有敌人的python吃豆人小游戏
时间: 2024-05-11 11:19:33 浏览: 175
基于Python实现的吃豆人游戏设计.zip
5星 · 资源好评率100%
好的,以下是一个简单的Python吃豆人小游戏,有敌人:
```python
import pygame
import random
# 初始化 pygame
pygame.init()
# 游戏窗口大小
window_size = (800, 600)
# 颜色定义
white = (255, 255, 255)
black = (0, 0, 0)
yellow = (255, 255, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
# 创建游戏窗口
game_display = pygame.display.set_mode(window_size)
pygame.display.set_caption('Python吃豆人小游戏')
# 加载资源
player_img = pygame.image.load('player.png')
enemy_img = pygame.image.load('enemy.png')
bean_img = pygame.image.load('bean.png')
game_icon = pygame.image.load('game_icon.png')
pygame.display.set_icon(game_icon)
# 定义游戏字体
font = pygame.font.SysFont(None, 25)
# 定义计分板
def score(score):
score_text = font.render("Score: "+str(score), True, white)
game_display.blit(score_text, [0,0])
# 定义游戏主循环
def game_loop():
# 初始化游戏状态
game_exit = False
game_over = False
# 定义玩家和敌人初始位置
player_x = window_size[0] / 2
player_y = window_size[1] / 2
enemy_x = random.randrange(0, window_size[0])
enemy_y = random.randrange(0, window_size[1])
# 定义玩家和敌人初始速度
player_speed = 5
enemy_speed = 3
# 定义豆子数量和每个豆子的初始位置
bean_count = 25
bean_list = []
for i in range(bean_count):
bean_x = random.randrange(0, window_size[0])
bean_y = random.randrange(0, window_size[1])
bean_list.append([bean_x, bean_y])
# 定义分数
score_count = 0
# 游戏主循环
while not game_exit:
# 游戏结束后等待用户操作
while game_over == True:
game_display.fill(black)
game_over_text = font.render("Game Over! Press Q to Quit or C to Continue", True, white)
game_display.blit(game_over_text, [window_size[0]/2-150, window_size[1]/2])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
elif event.key == pygame.K_c:
game_loop()
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x -= player_speed
elif event.key == pygame.K_RIGHT:
player_x += player_speed
elif event.key == pygame.K_UP:
player_y -= player_speed
elif event.key == pygame.K_DOWN:
player_y += player_speed
# 移动玩家和敌人
player_rect = game_display.blit(player_img, [player_x, player_y])
enemy_rect = game_display.blit(enemy_img, [enemy_x, enemy_y])
enemy_x += enemy_speed
if enemy_x > window_size[0]:
enemy_x = 0 - enemy_img.get_width()
enemy_y = random.randrange(0, window_size[1])
# 玩家和敌人碰撞检测
if player_rect.colliderect(enemy_rect):
game_over = True
# 显示豆子并检测是否被吃掉
for bean in bean_list:
bean_rect = game_display.blit(bean_img, bean)
if player_rect.colliderect(bean_rect):
bean_list.remove(bean)
score_count += 1
# 显示分数
score(score_count)
# 更新画面
pygame.display.update()
# 退出 pygame
pygame.quit()
quit()
# 启动游戏主循环
game_loop()
```
游戏规则:
- 玩家使用方向键控制吃豆人的移动;
- 敌人会随机移动,如果玩家和敌人碰撞,则游戏结束;
- 场景中有若干个豆子,玩家需要吃掉它们,每吃掉一个豆子得1分;
- 游戏结束后,玩家可以选择退出游戏或重新开始。
阅读全文