import pygame
import sys
初始化 Pygame
pygame.init()
设置窗口大小
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
设置标题
pygame.display.set_caption(‘Play Sound Example’)
加载音乐文件
sound_files = [‘s1.wav’, ‘s2.wav’, ‘s3.wav’, ‘s4.wav’, ‘s5.wav’, ‘s6.wav’, ‘s7.wav’]
sounds = [pygame.mixer.Sound(file) for file in sound_files]
按钮的设置
buttons = [pygame.Rect(400 + i * 100, 100, 90, 400) for i in range(7)]
button_colors = [(0, 0, 255), (0, 255, 0), (255, 0, 0), (255, 255, 0), (0, 255, 255), (255, 0, 255), (0, 25, 25)]
button_clicked_states = [False] * 7
主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
sys.exit()
# 检测鼠标点击事件
if event.type == pygame.MOUSEBUTTONDOWN:
for i, button in enumerate(buttons):
if button.collidepoint(event.pos):
button_clicked_states[i] = True
for i, button_clicked in enumerate(button_clicked_states):
if button_clicked:
sounds[i].play()
button_clicked_states[i] = False
{}
# 绘制按钮
screen.fill((255, 255, 255)) # 填充背景色
for i, button in enumerate(buttons):
pygame.draw.rect(screen, button_colors[i], button)
pygame.display.flip()
# 控制游戏循环速度
pygame.time.Clock().tick(60)