Python编译器IDE的wav声音文件小钢琴程序代码1

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()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

易软科技(河源)有限公司

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值