import pygame
import sys
初始化pygame
pygame.init()
加载音频文件
sound_files = {
‘C’: pygame.mixer.Sound(‘s1.wav’),
‘D’: pygame.mixer.Sound(‘s2.wav’),
‘E’: pygame.mixer.Sound(‘s3.wav’),
‘F’: pygame.mixer.Sound(‘s4.wav’),
‘G’: pygame.mixer.Sound(‘s5.wav’),
‘A’: pygame.mixer.Sound(‘s6.wav’),
‘B’: pygame.mixer.Sound(‘s7.wav’)
}
设置窗口大小
screen_width = 800
screen_height = 200
screen = pygame.display.set_mode((screen_width, screen_height))
设置窗口标题
pygame.display.set_caption(“简易小钢琴”)
定义按键位置和大小
keys = {
‘C’: (50, 50, 100, 100),
‘D’: (160, 50, 100, 100),
‘E’: (270, 50, 100, 100),
‘F’: (380, 50, 100, 100),
‘G’: (490, 50, 100, 100),
‘A’: (600, 50, 100, 100),
‘B’: (710, 50, 100, 100)
}
定义按键被按下时的函数
def play_sound(key):
sound_files[key].play()
游戏主循环
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y = event.pos
for key, rect in keys.items():
if rect[0] <= mouse_x <= rect[0] + rect[2] and rect[1] <= mouse_y <= rect[1] + rect[3]:
play_sound(key)
# 填充背景色
screen.fill((255, 255, 255))
# 绘制按键
for key, rect in keys.items():
pygame.draw.rect(screen, (0, 0, 0), rect)
font = pygame.font.Font(None, 36)
text = font.render(key, True, (255, 0, 0))
text_rect = text.get_rect(center=(rect[0] + rect[2] // 2, rect[1] + rect[3] // 2))
screen.blit(text, text_rect)
# 更新屏幕显示
pygame.display.flip()
退出pygame
pygame.quit()
sys.exit()