将pygame打地鼠封装成函数
时间: 2023-06-13 07:06:29 浏览: 102
python小游戏【打地鼠Whac-A-Mole小游戏】-pygame经典案例源码正常运行
好的,下面是一个简单的将 Pygame 打地鼠游戏封装成函数的示例代码:
```python
import pygame
import random
def play_whack_a_mole():
# 初始化 Pygame
pygame.init()
# 设置游戏窗口大小
window_size = (640, 480)
screen = pygame.display.set_mode(window_size)
# 设置游戏标题
pygame.display.set_caption('Whack-a-Mole')
# 加载图片资源
mole_image = pygame.image.load('mole.png')
mole_hit_image = pygame.image.load('mole_hit.png')
hammer_image = pygame.image.load('hammer.png')
# 设置游戏参数
mole_size = mole_image.get_size()
mole_hit_size = mole_hit_image.get_size()
hammer_size = hammer_image.get_size()
mole_speed = 5
mole_spawn_time = 1500
mole_spawn_timer = 0
mole_spawned = False
mole_x, mole_y = 0, 0
hammer_x, hammer_y = 0, 0
hammer_visible = False
score = 0
# 设置游戏循环
running = True
clock = pygame.time.Clock()
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if hammer_visible:
hammer_rect = pygame.Rect(hammer_x, hammer_y, hammer_size[0], hammer_size[1])
if hammer_rect.collidepoint(pygame.mouse.get_pos()):
score += 1
hammer_visible = False
# 更新游戏状态
mole_spawn_timer += clock.get_time()
if not mole_spawned and mole_spawn_timer > mole_spawn_time:
mole_x = random.randint(0, window_size[0] - mole_size[0])
mole_y = random.randint(0, window_size[1] - mole_size[1])
mole_spawned = True
mole_spawn_timer = 0
if mole_spawned:
mole_y += mole_speed
if mole_y > window_size[1]:
mole_spawned = False
if not hammer_visible:
hammer_x, hammer_y = pygame.mouse.get_pos()
hammer_x -= hammer_size[0] // 2
hammer_y -= hammer_size[1] // 2
# 绘制游戏界面
screen.fill((255, 255, 255))
if mole_spawned:
screen.blit(mole_image, (mole_x, mole_y))
else:
mole_spawned = False
if hammer_visible:
screen.blit(hammer_image, (hammer_x, hammer_y))
if score > 0:
font = pygame.font.Font(None, 36)
text = font.render(f'Score: {score}', True, (0, 0, 0))
screen.blit(text, (10, 10))
# 更新屏幕显示
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出 Pygame
pygame.quit()
```
使用该函数,只需要在你的 Python 代码中调用 `play_whack_a_mole()` 即可开始游戏。请注意,该示例代码需要保证当前工作目录下存在名为 `mole.png`、`mole_hit.png` 和 `hammer.png` 的图片资源文件。您可以根据自己的需求修改函数参数和游戏设置。
阅读全文