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("练枪游戏")
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
# 定义目标类
class Target:
def __init__(self):
self.x = random.randint(50, screen_width - 50)
self.y = random.randint(50, screen_height - 50)
self.radius = 20
self.speed_x = random.randint(-3, 3)
self.speed_y = random.randint(-3, 3)
def draw(self):
pygame.draw.circle(screen, RED, (self.x, self.y), self.radius)
def move(self):
self.x += self.speed_x
self.y += self.speed_y
# 边界反弹
if self.x < 50 or self.x > screen_width - 50:
self.speed_x = -self.speed_x
if self.y < 50 or self.y > screen_height - 50:
self.speed_y = -self.speed_y
def is_hit(self, mouse_x, mouse_y):
distance = ((mouse_x - self.x) ** 2 + (mouse_y - self.y) ** 2) ** 0.5
if distance <= self.radius:
return True
return False
# 创建目标列表
targets = [Target() for _ in range(5)]
# 设置游戏时钟
clock = pygame.time.Clock()
# 得分
score = 0
# 游戏时长(秒)
game_duration = 30
start_time = pygame.time.get_ticks()
# 游戏主循环
running = True
while running:
current_time = pygame.time.get_ticks()
elapsed_time = (current_time - start_time) / 1000
if elapsed_time >= game_duration:
running = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = pygame.mouse.get_pos()
for target in targets:
if target.is_hit(mouse_x, mouse_y):
score += 1
targets.remove(target)
targets.append(Target())
screen.fill(WHITE)
for target in targets:
target.move()
target.draw()
# 显示得分
font = pygame.font.Font(None, 36)
score_text = font.render("得分: " + str(score), True, BLACK)
screen.blit(score_text, (10, 10))
# 显示倒计时
remaining_time = game_duration - elapsed_time
time_text = font.render("时间: {:.2f}".format(remaining_time), True, BLACK)
screen.blit(time_text, (screen_width - 100, 10))
pygame.display.flip()
clock.tick(60)
# 游戏结束显示最终得分
screen.fill(WHITE)
final_score_text = font.render("游戏结束!最终得分: " + str(score), True, BLACK)
screen.blit(final_score_text, (screen_width // 2 - 100, screen_height // 2))
pygame.display.flip()
pygame.time.delay(3000)
# 退出游戏
pygame.quit()