python打地鼠游戏代码
时间: 2023-06-13 11:08:53 浏览: 227
打地鼠游戏代码
以下是一个简单的Python打地鼠游戏代码示例:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置屏幕宽高和背景色
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BG_COLOR = (255, 255, 255)
# 创建屏幕对象
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
# 设置窗口标题
pygame.display.set_caption("打地鼠")
# 加载地鼠图片
mouse_img = pygame.image.load("mouse.png")
# 地鼠的位置和状态(0-未出现, 1-出现, 2-被打中)
mouse_pos = (-100, -100)
mouse_status = 0
# 分数
score = 0
# 游戏时钟
clock = pygame.time.Clock()
# 游戏循环标志
game_running = True
# 游戏主循环
while game_running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
# 判断是否打中了地鼠
if mouse_status == 1 and mouse_rect.collidepoint(event.pos):
mouse_status = 2
score += 1
# 清空屏幕
screen.fill(BG_COLOR)
# 绘制地鼠
if mouse_status == 0:
# 地鼠未出现,随机生成位置
mouse_pos = (random.randint(0, SCREEN_WIDTH - mouse_img.get_width()), random.randint(0, SCREEN_HEIGHT - mouse_img.get_height()))
mouse_status = 1
elif mouse_status == 1:
# 地鼠出现,绘制地鼠
screen.blit(mouse_img, mouse_pos)
mouse_rect = pygame.Rect(mouse_pos[0], mouse_pos[1], mouse_img.get_width(), mouse_img.get_height())
else:
# 地鼠被打中,重置状态
mouse_status = 0
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制游戏帧率
clock.tick(60)
# 退出Pygame
pygame.quit()
```
在运行前,需要准备一张地鼠图片,并将其命名为"mouse.png"并放在与代码文件同一目录下。运行代码后,就可以开始打地鼠游戏了。
阅读全文