将一个pygame打地鼠游戏封装成函数
时间: 2023-06-13 13:06:16 浏览: 103
简单的打地鼠游戏主函数
好的,以下是一个简单的示例代码,将pygame打地鼠游戏封装成了一个名为`whack_a_mole`的函数。你可以在此基础上进行修改和扩展,以适应你的具体需求。
```python
import pygame
import random
# 游戏配置
WIDTH = 640
HEIGHT = 480
FPS = 30
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
# 初始化 pygame
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Whack-a-Mole")
clock = pygame.time.Clock()
def whack_a_mole():
# 加载游戏资源
mole_image = pygame.image.load("mole.png")
hammer_image = pygame.image.load("hammer.png")
whack_sound = pygame.mixer.Sound("whack.wav")
# 初始化游戏状态
score = 0
running = True
mole_pos = (WIDTH // 2, HEIGHT // 2)
mole_speed = 5
mole_visible = False
# 游戏循环
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and mole_visible:
if mole_rect.collidepoint(event.pos):
score += 1
whack_sound.play()
# 更新游戏状态
mole_visible = not mole_visible
if not mole_visible:
mole_pos = (random.randint(0, WIDTH), random.randint(0, HEIGHT))
mole_rect = mole_image.get_rect()
mole_rect.center = mole_pos
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
mole_pos = (mole_pos[0] - mole_speed, mole_pos[1])
elif keys[pygame.K_RIGHT]:
mole_pos = (mole_pos[0] + mole_speed, mole_pos[1])
elif keys[pygame.K_UP]:
mole_pos = (mole_pos[0], mole_pos[1] - mole_speed)
elif keys[pygame.K_DOWN]:
mole_pos = (mole_pos[0], mole_pos[1] + mole_speed)
# 绘制游戏界面
screen.fill(BLACK)
if mole_visible:
screen.blit(mole_image, mole_rect)
screen.blit(hammer_image, pygame.mouse.get_pos())
font = pygame.font.Font(None, 36)
text = font.render("Score: {}".format(score), True, WHITE)
screen.blit(text, (10, 10))
pygame.display.flip()
# 控制游戏帧率
clock.tick(FPS)
# 游戏结束,卸载资源
pygame.quit()
```
你可以将此代码复制到你的 Python 文件中,并在需要调用游戏时,直接调用`whack_a_mole()`函数即可。例如:
```python
if __name__ == "__main__":
whack_a_mole()
```
阅读全文