现在在python中显示的错误是
Traceback (most recent call last):
File "C:\Users\Eduardo.Graglia\AppData\Local\Programs\Python\Python37\Start.py", line 66, in <module>
snake = snake(self) # create an instance
File "C:\Users\Eduardo.Graglia\AppData\Local\Programs\Python\Python37\Start.py", line 17, in __init__
food.image = pygame.image.load("food.png")
AttributeError: 'str' object has no attribute 'image'
我是python和pygame的新手,所以我一直在使用的大多数代码都是我从堆栈溢出中获取并改编的内容
我尝试对food对象进行处理的原因是将其全部放在一个播放器类中,因为我对如何调用其他类的方法以及如何在一个类中使用其他类的对象感到困惑。如果有人对我所做的事情有其他选择,请告诉我。 导入pygame 导入操作系统 导入时间 导入数学 随机导入
length = 650
width = 400
headx = 0
heady = 0
class snake(object):
def __init__(self, food):
self.image = pygame.image.load("head.png")
self.x = 0
self.y = 0
food.image = pygame.image.load("food.png")
food.x = 0
food.y = 0
def handle_keys(self):
""" Handles Keys """
key = pygame.key.get_pressed()
dist = 25 # distance moved in 1 frame, try changing it to 5
if key[pygame.K_DOWN]: # down key
self.y += dist # move down
heady = heady - dist
elif key[pygame.K_UP]: # up key
self.y -= dist # move up
heady = heady - dist
if key[pygame.K_RIGHT]: # right key
self.x += dist # move right
headx = headx - dist
elif key[pygame.K_LEFT]: # left key
self.x -= dist # move left
headx = headx - dist
def fooddrop(food, surface):
newfoodx = 1
newfoody = 1
while newfoodx % 25 != 0 or newfoodx !=0:
newfoodx = random.randint(0,650)
while newfoody % 25 != 0 or newfoody !=0:
newfoody = random.randint(0,400)
food.x = newfoodx
food.y = newfoody
surface.blit(food.image,(food.x,food.y))
def draw(self, surface):
""" Draw on surface """
# blit yourself at your current position
surface.blit(self.image, (self.x, self.y))
self = 'null'
food = 'null'
pygame.init()
screen = pygame.display.set_mode((length, width))
snake = snake(self) # create an instance
food = snake(food)
running = True
while running:
# handle every event since the last frame.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
if snake.y > width or snake.y < 0 or snake.x > length or snake.x < 0: #Border Created
pygame.quit() # quit the screen
running = False
time.sleep(0.125)
snake.handle_keys() # handle the keys
screen.fill((0,0,0)) # fill the screen with white
snake.draw(screen) # draw the snake to the screen
snake.fooddrop(screen)
pygame.display.update() # update the screen
clock.tick(40)
由于我是新手并且需要学习,请随意完全破坏我的代码。 预先感谢!
答案 0 :(得分:1)
创建一个类Snake
(或其他名称)。请使用班级名称开头的大写字母以避免混淆(请参阅Style Guide for Python Code - Class Names)。
该类的构造函数具有1个参数(在self
旁边),即图像的名称:
class Snake(object):
def __init__(self, imagename):
self.image = pygame.image.load(imagename)
self.x = 0
self.y = 0
创建该类的2个实例:
snake = Snake("head.png")
food = Snake("food.png")