我开始用PyGame在Python中创建一个新游戏,我把我的雪碧的所有图像都放在一个列表中,所以当我用箭头移动雪碧时,它会读取包含精灵图像的列表,并给出一个真实的效果(因为我们会看到精灵的腿移动)。问题是,显然,get_rect
我们不能对列表中的图像使用:AttributeError: 'list' object has no attribute 'get_rect'
这是我的代码:
import os
import pygame
pygame.init()
current_path = os.path.dirname(__file__)
image_path = os.path.join(current_path, 'images')
screen = pygame.display.set_mode((1280,720))
pygame.display.set_caption("Shoot The Villains")
pygame.display.set_icon(pygame.image.load(os.path.join(image_path, 'icon.png')))
class Player (pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.x = 25
self.y = 640
self.health_Player = 100
self.reamaning_health_Player = self.health_Player / (20/13)
self.attackDMG = 10
self.speed = 7.5
self.jumpCount = self.speed
self.countSteps = 0
self.go_left = [pygame.image.load(os.path.join(image_path, 'Sprite_soldatGauche1-4.png')),pygame.image.load(os.path.join(image_path, 'Sprite_soldatGauche2-4.png')),pygame.image.load(os.path.join(image_path, 'Sprite_soldatGauche3-4.png')), pygame.image.load(os.path.join(image_path, 'Sprite_soldatGauche4-4.png'))]
self.go_right = [pygame.image.load(os.path.join(image_path, 'Sprite_soldatDroit1-4.png')),pygame.image.load(os.path.join(image_path, 'Sprite_soldatDroit2-4.png')),pygame.image.load(os.path.join(image_path, 'Sprite_soldatDroit3-4.png')), pygame.image.load(os.path.join(image_path, 'Sprite_soldatDroit4-4.png'))]
self.rectLeft = self.go_left[0:len(self.go_left)].get_rect ### THIS LINE ###
self.rectRight = self.go_right[0:len(self.go_right)].get_rect ### THIS LINE ###
这是最后两行。我没有把所有的代码都放进去,因为我认为它是没用的。--这不是我第一次用编写代码,但我也不是一个经验丰富的程序员,所以除了最后两行之外,不要惊讶地看到其他错误。
谢谢你抽出时间回顾我的问题!
发布于 2020-08-06 00:42:50
假设self.rectLeft
是self.go_left
中图像的矩形列表,那么您就不能以这种方式初始化它。
引发的错误告诉您不能将方法get_rect
应用于列表对象。如果您想在列表的图像上应用get_rect
,那么您必须对每个项目单独执行,而不是在列表本身上。
有几种方法可以做到这一点。一种是使用列表理解:
self.rectLeft = [img.get_rect() for img in self.go_left]
https://stackoverflow.com/questions/63273637
复制相似问题