python pygame打地鼠图片计时游戏代码
时间: 2023-11-09 17:04:11 浏览: 76
Python打地鼠小游戏源代码
5星 · 资源好评率100%
以下是一个简单的Python Pygame打地鼠图片计时游戏代码,其中包含了计时器、得分计算和随机出现的地鼠图片:
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# 设置游戏窗口
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("打地鼠")
# 载入地鼠图片
mouse_image = pygame.image.load("mouse.png")
# 游戏开始时间
start_time = 0
# 游戏得分
score = 0
# 地鼠出现的时间间隔(单位:毫秒)
mouse_interval = 1000
# 游戏时钟
game_clock = pygame.time.Clock()
# 游戏结束标志
game_over = False
# 游戏主循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# 处理鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
# 判断是否点击到地鼠
if mouse_rect.collidepoint(mouse_x, mouse_y):
score += 1
# 绘制背景
game_window.fill((255, 255, 255))
# 绘制计时器
current_time = pygame.time.get_ticks()
if start_time == 0:
start_time = current_time
else:
elapsed_time = current_time - start_time
time_left = max(0, 30 - elapsed_time // 1000)
font = pygame.font.SysFont(None, 30)
text = font.render("Time: " + str(time_left), True, (0, 0, 0))
game_window.blit(text, (10, 10))
if time_left == 0:
game_over = True
# 绘制得分
font = pygame.font.SysFont(None, 30)
text = font.render("Score: " + str(score), True, (0, 0, 0))
game_window.blit(text, (WINDOW_WIDTH - 100, 10))
# 绘制地鼠
current_time = pygame.time.get_ticks()
if current_time - mouse_last_time >= mouse_interval:
mouse_x = random.randint(0, WINDOW_WIDTH - mouse_rect.width)
mouse_y = random.randint(0, WINDOW_HEIGHT - mouse_rect.height)
mouse_rect = mouse_image.get_rect().move(mouse_x, mouse_y)
mouse_last_time = current_time
game_window.blit(mouse_image, mouse_rect)
# 更新屏幕
pygame.display.update()
# 控制游戏帧率
game_clock.tick(60)
# 游戏结束
pygame.quit()
```
需要注意的是,此代码中需要提前准备好“mouse.png”地鼠图片。
阅读全文