user2917156
user2917156

Reputation: 1

I keep getting a "self" is not defined error

Im trying to add a media file, so that when you press the key a is plays and you let go it stops, any help would be appreciated!

I get the error code self is not defined and I just need a point the right direction.

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")

I keep getting a self is not defined error here

        #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()

Upvotes: 0

Views: 451

Answers (1)

DSM
DSM

Reputation: 353039

You're mixing tabs and spaces. This confuses Python about how far code is indented: your self.bg_color = 0, 0, 0 line isn't as indented as you think it is. Looking at your raw code:

'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'

Note the absence of tabs in two of the last four lines.

Use python -tt your_program_name.py to confirm this, and switch to using four spaces for indentation. Most editors allow you to configure this.

Upvotes: 1

Related Questions