I have some code in main.py
:
import pygame, char
def move(char):
#movement code
#friction
if char.xaccel == 0:
if abs(char.xvel) < char.xvelfalloff: char.xvel = 0
elif abs(char.xvel) == char.xvel: char.xvel -= char.xvelfalloff
elif abs(char.xvel) != char.xvel: char.xvel += char.xvelfalloff
#acceleration
char.xvel += char.xaccel
#max speed
if abs(char.xvel) > char.xmaxvel: char.xvel = math.copysign(char.xmaxvel,char.xvel)
#position/collision detection
char.x += char.xvel
char.xaccel = 0
char.yaccel = char.ygravity
char.yvel += char.yaccel
char.y += char.yvel
if char.y < 0: #TODO: more collision detection
char.yvel = 0
char.y = 0
char.onground = True
if char.jumping:
char.yvel = char.jumpstrength
char.jumping = False
char.onground = False
#no more movement code
charObj = char.Char()
charObj = move(charObj)
screen.blit(char.currentanimation, pygame.Rect(char.x, (screen_height-char.y)-char.height, char.width, char.height))
pygame.display.flip()
and some code in char.py
:
import pygame
class Char():
spritesheet = pygame.image.load("images/spritesheet.png")
walkanim = []
for i in range(7):
spritesheet.set_clip(pygame.Rect(((sprite_width-7)*i)+3,12,sprite_width,sprite_height))
spritesheetsubsurface = spritesheet.subsurface(spritesheet.get_clip())
walkanim.append(pygame.transform.scale(spritesheetsubsurface, (width, height)))
spritesheet.set_clip(pygame.Rect(0,577,sprite_width,sprite_height))
spritesheetsubsurface = spritesheet.subsurface(spritesheet.get_clip())
idleanim = pygame.transform.scale(spritesheetsubsurface, (width, height))
lastanim = "right"
currentanimation = idleanim
animationframeindex = 0
animationframepause = 6 #how many frames go by between animation frames
animationframetime = 0 #how many frames we have been on the same animation frame
Note that I've cut out everything unrelated here. So, I get an error when I run this code that says:
Traceback (most recent call last):
File "C:\Users\spng453\scripts\super smash feminist\main.py", line 90, in <module>
screen.blit(char.currentanimation, pygame.Rect(char_x, (screen_height-char_y)-char_height, char_width, char_height))
AttributeError: 'module' object has no attribute 'currentanimation'
I literally have no idea where I could have gone wrong here. Any help with understanding where this problem stems from would be appreciated.
If you define a class to have an attribute (ie, self.currentanimation
), you can access it like so:
charObj = char.Char()
charObj.currentanimation
What you're doing in your code is looking inside the module char
, not inside your instance of Char (charObj
). The char
module has no attribute/variable/etc named currentanimation
. But instances of Char
do – or, rather, they will once you define an __init__()
method in your class definition, and start using self
:-)
For more on setting and accessing attributes, take a look at this section of the docs.