我试图添加一个媒体文件,这样当你按下按键a播放时你就放开它,任何帮助都将不胜感激!
我得到错误代码self未定义,我只需要一个正确的方向点。
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()
答案 0 :(得分:1)
你正在混合制表符和空格。这会让Python混淆代码缩进的程度:你的self.bg_color = 0, 0, 0
行不像你想象的那样缩进。查看原始代码:
'class MyGame(object):'
'\tdef __init__(self):'
'\t\t"""Initialize a new game"""'
'\t\tpygame.init()'
'\t\t'
'\t\tself.width = 800'
'\t\tself.height = 600'
'\t\tself.screen = pygame.display.set_mode((self.width, self.height))'
'\t\t'
'\t\t#Load resources'
' sound = pygame.mixer.music.load("a.mp3")'
'\t\t#use a black background'
' self.bg_color = 0, 0, 0'
请注意最后四行中有两行没有制表符。
使用python -tt your_program_name.py
进行确认,然后切换为使用四个空格进行缩进。大多数编辑器都允许您配置它。