我在其中有一些代码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()
和一些代码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
请注意,我在这里已经删除了所有无关的内容。因此,当我运行以下代码时出现错误:
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'
我真的不知道在哪里我会出错。任何了解此问题根源的帮助将不胜感激。
如果您定义一个具有属性的类(即self.currentanimation
),则可以这样访问它:
charObj = char.Char()
charObj.currentanimation
您在代码中所做的工作是在模块内部而char
不是在Char(charObj
)实例内部。该char
模块没有属性/变量/等命名currentanimation
。但是Char
do的实例–或者更确切地说,一旦您__init__()
在类定义中定义了一个方法并开始使用self
:-) ,它们便会实例化
有关设置和访问属性的更多信息,请参阅docs的本部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句