python - 如何更改pygame中按键的名称?

标签 python python-3.x pygame

我有一个代码,R 和 P 键会发出声音,并将它们保存在按下按键时的列表中,我的问题是如何在每次按下按键时更改按键的名称?

这是部分代码:

from array import array 
import pygame 
from pygame.mixer import Sound, get_init,  pre_init

class Note(pygame.mixer.Sound): 

    def __init__(self,key, frequency, volume=.1): 
        self.frequency = frequency 
        Sound.__init__(self, self.build_samples()) 
        self.set_volume(volume)
        self.key=key
    def build_samples(self): 
        period = int(round(get_init()[0] / self.frequency)) 
        samples = array("h", [0] * period) 
        amplitude = 2 ** (abs(get_init()[1]) - 1) - 1 
        for time in range(period): 
            if time < period / 2: 
                samples[time] = amplitude 
            else: 
                samples[time] = -amplitude 
        return samples
    def __repr__(self):
        return 'Note({})'.format(self.key)
pre_init(44100, -16, 1, 1024)
pygame.init() 
screen = pygame.display.set_mode([640, 480], 0) 

sounds = {} 
keymap = {pygame.K_p: 880, pygame.K_r: 440} 
key_pressed=[]
while True:

    evt = pygame.event.wait() 
    if evt.type == pygame.QUIT: 
        break 
    elif evt.type == pygame.KEYDOWN: 
        if evt.key in keymap: 
            note = Note(keymap[evt.key]) 
            note.play(-1) 
            sounds[evt.key] = note
            key_pressed.append(note)

    elif evt.type == pygame.KEYUP: 
        if evt.key in sounds: 
            sounds.pop(evt.key).stop()
    print(key_pressed)

Image of how the keys come out when pressed

最佳答案

如果你想改变对象的表示,你必须给它们一个返回字符串的__repr__方法。

import pygame

pygame.init() 
screen = pygame.display.set_mode([640, 480], 0)

class Note:

    def __init__(self, key):
        self.key = key

    def __repr__(self):
        return 'Note({})'.format(self.key)

sounds = {} 
keymap = {pygame.K_p: 880, pygame.K_r: 440} 
key_pressed = []

while True:
    evt = pygame.event.wait() 
    if evt.type == pygame.QUIT: 
        break 
    elif evt.type == pygame.KEYDOWN: 
        if evt.key in keymap: 
            note = Note(keymap[evt.key])
            print(note)
            sounds[evt.key] = note
            key_pressed.append(note)
        print(key_pressed)

pygame.quit()

关于python - 如何更改pygame中按键的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47734648/

相关文章:

python - 为什么我的查询在参数化时会中断?

python - 显示解析的值时未显示正确的值

python - fb预言家 : Predict a future holiday

python - 带括号和不带括号的元组之间的区别?

Python 文件未正确关闭

python - 将 pygame 表面转换为图像?

python - python中的多维矩阵乘法

python - 从具有大量值的数据框中快速创建数组?

pygame Pong - 如何归因我的评分系统和碰撞检测

python - 当我有 x 和 y 坐标时,使物体在轨道上移动