我有一个经典的贪吃蛇游戏,我试图让蛇变得更大,所以我开始使用打印矩形来屏幕而不是像素。我尝试了这些代码(我不会编写整个代码,因为它可能会混淆):
class Worm(pygame.sprite.Sprite):
def __init__(self, surface,seg_width,seg_height):
self.surface = surface #this is ==> screen=pygame.display.set_mode((w, h))
self.x = surface.get_width() / 2
self.y = surface.get_height() / 2
self.length = 1
self.grow_to = 50
self.vx = 0
self.vy = -seg_width
self.body = []
self.crashed = False
self.color = 255, 255, 0
self.rect = pygame.Rect(self.x,self.y,seg_width,seg_height)
self.segment = pygame.Rect(0,0,seg_width,seg_height)
def move(self):
""" Move the worm. """
self.x += self.vx
self.y += self.vy
self.rect.topleft = self.x, self.y
if (self.x, self.y) in self.body:
self.crashed = True
self.body.insert(0, (self.x, self.y)) #Func of moving the snake
new_segment = self.segment.copy()
self.body.insert(0, new_segment.move(self.x, self.y))
if len(self.body) > self.length:
self.body.pop()
def draw(self):
for SEGMENT in self.body: #Drawing the snake
self.surface.fill((255,255,255), SEGMENT) #This is where I got error <-----
如果我使用像素,我的代码可以完美运行,但我想要一条更大的蛇(不是更长,我的意思是更粗),所以我想我可以使用矩形,我尝试了这个,但它给了我;
self.surface.fill((255,255,255), SEGMENT)
ValueError: invalid rectstyle object
SEGMENT实际上是一个坐标元组,为什么我会得到这个错误呢? 另外,在我按 f5 后,我首先看到这个屏幕,所以基本上我的理论是有效的,但它是一个奇怪的输出,一个矩形比其他矩形小? 为什么?那个“0”是记分板,我没有像我说的那样编写整个代码。
我只是不明白为什么,我能做些什么来解决它?
我想再说一遍,因为它也可能令人困惑,surface参数实际上代表screen = pygame.display.set_mode((w, h))
这个,其中 w = 宽度
和 h = 高度
。
这是带有像素的,所以我想要一条更粗的蛇,由矩形而不是像素构建。
Edit: From nbro's answer, I change this one
self.body.insert(0, (self.x, self.y,self.x, self.y))
现在它是一个有 4 个元素的元组,但输出很奇怪..
最佳答案
在某处使用简单的 print
即可轻松调试代码。我刚刚在下面放置了一个 print
:
def draw(self):
for SEGMENT in self.body:
print(SEGMENT)
self.surface.fill((255,255,255), SEGMENT) #This is where I got error <-----
我立即发现了你的问题。 SEGMENT
必须是基于矩形的形状,这意味着您必须指定 x
、y
、width
和height
,但是,在某些时候,SEGMENT
假定一个由 2 个元素组成的 tuple
值,这是不正确的,它必须是一个元组4个元素!
具体来说,当我收到错误时的输出是这样的:
<rect(320, 210, 30, 30)>
<rect(320, 180, 30, 30)>
(320.0, 180.0)
现在我认为即使没有我的帮助,您也可以尝试了解为什么它假设 2 个元素的第三个元组。
关于python - Pygame sprite 无效的 rectstyle 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27680525/