pygame鼠标射击训练小游戏
时间: 2023-08-05 07:03:13 浏览: 252
下面是一个使用Pygame制作的简单射击训练小游戏的示例代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置窗口大小和标题
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Shooting Training Game")
# 加载背景音乐
pygame.mixer.music.load("background_music.wav")
pygame.mixer.music.play(-1) # 无限循环播放背景音乐
# 加载射击音效
shoot_sound = pygame.mixer.Sound("shoot_sound.wav")
# 加载目标图片
target_image = pygame.image.load("target.png")
target_rect = target_image.get_rect()
# 设置目标初始位置
target_x = random.randint(0, screen_width - target_rect.width)
target_y = random.randint(0, screen_height - target_rect.height)
# 游戏主循环
running = True
score = 0
while running:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# 获取鼠标点击位置
mouse_x, mouse_y = pygame.mouse.get_pos()
# 检查鼠标点击是否命中目标
if target_x <= mouse_x <= target_x + target_rect.width and target_y <= mouse_y <= target_y + target_rect.height:
score += 1 # 增加分数
shoot_sound.play() # 播放射击音效
target_x = random.randint(0, screen_width - target_rect.width)
target_y = random.randint(0, screen_height - target_rect.height)
# 填充背景色
screen.fill((255, 255, 255))
# 在指定位置绘制目标
screen.blit(target_image, (target_x, target_y))
# 绘制分数文本
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
# 更新屏幕显示
pygame.display.flip()
# 退出游戏
pygame.quit()
```
在代码中,我们使用Pygame创建了一个窗口,并加载了背景音乐和射击音效。然后加载了目标图片,并设置了目标的初始位置。在游戏主循环中,处理鼠标点击事件。如果鼠标左键点击命中目标,则增加分数,播放射击音效,并将目标位置随机设置为窗口内的一个新位置。然后在主循环中,填充背景色,绘制目标和分数文本,并更新屏幕显示。
请确保将代码中的音乐和图片文件路径替换为你自己的文件路径。你可以使用任意图片作为目标,并根据需要调整窗口大小和其他游戏元素。
阅读全文
相关推荐















