如何在pygame中更改键的名称?

时间:2017-12-10 00:24:41

标签: 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

1 个答案:

答案 0 :(得分:2)

如果要更改对象的表示形式,则必须为它们提供返回字符串的__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()