我将自己介绍给python和pygame库。我想先尝试一个非常基本的粒子发射器,但我收到了一个错误。
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
running = True
color = (128, 128, 128)
radius = 10
class Particle:
"""Represents a particle."""
def __init__(self, pos, vel):
self.pos = pos
self.vel = vel
def move(self):
self.pos += self.vel
def draw(self):
pygame.draw.circle(screen, color, self.pos, radius)
particles = list()
while running:
for e in pygame.event.get():
if e.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
if len(particles) < 10:
randvel = random.randint(-5, 5), random.randint(-5, 5)
p = Particle((0, 0), randvel)
particles.append(p)
for p in particles:
p.move()
p.draw()
pygame.display.flip()
clock.tick(60)
根据我的理解,这个错误说必须传递2个参数,而不是4个。
Traceback (most recent call last):
File "D:\data\eclipse\pythonscrap\main.py", line 44, in <module>
p.draw()
File "D:\data\eclipse\pythonscrap\main.py", line 24, in draw
pygame.draw.circle(screen, color, self.pos, radius)
TypeError: must be sequence of length 2, not 4
我怀疑这对初学者来说是一个常见错误,因为很容易忘记一组额外的()
来制作元组。但是当我查看文档时,我发现该方法的签名是:
circle Found at: pygame.draw
pygame.draw.circle(Surface, color, pos, radius, width=0): return Rect
draw a circle around a point
这是五个参数,其中一个给出了默认值。那么这里出了什么问题?
答案 0 :(得分:3)
你的论点数是正确的。 pos
元组是错误的,它的长度为4而不是2。
通过添加self.vel
,您可以向元组添加新元素,而不是对坐标求和:
self.pos += self.vel
改为对各个坐标求和:
self.pos = (self.pos[0] + self.vel[0], self.pos[1] + self.vel[1])
快速演示来说明问题:
>>> pos = (0, 0)
>>> vel = (1, 1)
>>> pos += vel
>>> pos
(0, 0, 1, 1)