我正在尝试添加一个媒体文件,这样当您按下键 a 时播放并且您松开它就会停止,任何帮助将不胜感激!
我得到错误代码 self is not defined 我只需要指出正确的方向。
from __future__ import division
import math
import sys
import pygame
pygame.mixer.init()
pygame.mixer.pre_init(44100, -16, 2, 2048)
class MyGame(object):
def __init__(self):
"""Initialize a new game"""
pygame.init()
self.width = 800
self.height = 600
self.screen = pygame.display.set_mode((self.width, self.height))
#Load resources
sound = pygame.mixer.music.load("a.mp3")
我在这里不断收到一个未定义的自我错误
#use a black background
self.bg_color = 0, 0, 0
#Setup a timer to refresh the display FPS times per second
self.FPS = 30
self.REFRESH = pygame.USEREVENT+1
pygame.time.set_timer(self.REFRESH, 1000//self.FPS)
# Now jusr start waiting for events
self.event_loop()
def event_loop(self):
"""Loop forever processing events"""
while 1 < 2:
event = pygame.event.wait()
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
sys.exit()
if event.type == pygame.KEYDOWN and event.key == pygame.K_A:
sound.play()
if event.type == pygame.KEYUP and event.key == pygame.K_A:
sound.stop()
elif event.type == self.REFRESH:
# time to draw a new frame
self. draw()
pygame.display.flip()
else:
pass #an event we dont handle
def draw(self):
"""Updating the display"""
self.screen.fill(self.bg_color)
MyGame().run()
pygame.quit()
sys.exit()