2013-10-24 102 views
0

我试图添加一个媒体文件,所以当你按下键是播放,你放开它停下来,任何帮助将不胜感激!我一直得到一个“自我”没有定义的错误

我得到错误代码自我没有定义,我只需要一个正确的方向。

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

发布完整的错误追溯请 – RyPeck

+0

错误消息指向一个行号? – shx2

+0

错误会告诉你它到底在哪一行。此外,我期待“语法无效”,而不是“自我未定义”。 – Izkata

回答

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来确认这一点,并切换到使用四个空格进行缩进。大多数编辑器允许您配置它。

相关问题