我正在与一些班级一起尝试编写小型游戏。我创建了一种在屏幕上移动对象的方法,并添加了键绑定。
我希望正方形移动,但是它只会发出错误。您能解释一下为什么会给我这个错误吗?
代码:
class shape():
def __init__(self, place, colour, x, y):
self.place = place
self.colour = colour
self.x = x
self.y = y
#class for a rectangle
class rectangle(shape):
def __init__(self, place, colour, x, y, length, width):
super().__init__(place, colour, x, y)
self.length = length
self.width = width
pygame.draw.rect(screen, colour, pygame.Rect(x, y, length, width))
def move_up():
self.y = self.y + 3
def move_down():
self.y = self.y - 3
def move_right():
self.x = self.x + 3
def move_left():
self.x = left.x - 3
#creating a rectangle
Rectangle = rectangle(screen, yellow, x, y, 60, 60)
#main loop
while not done:
#checking for game events
for event in pygame.event.get():
#quitting gamw when window is closed
if event.type == pygame.QUIT:
done = True
#detecting key presses
key_press = pygame.key.get_pressed()
if key_press[pygame.K_UP]: Rectangle.move_up()
if key_press[pygame.K_DOWN]:Rectangle.move_down()
if key_press[pygame.K_LEFT]:Rectangle.move_left()
if key_press[pygame.K_RIGHT]:Rectangle.move_right()
pygame.display.flip()
我收到此错误:
Traceback (most recent call last):
File "Pygame.py", line 73, in <module>
if key_press[pygame.K_RIGHT]:Rectangle.move_right()
TypeError: move_right() takes 0 positional arguments but 1 was given
,我不确定为什么。
答案 0 :(得分:1)
矩形是一个类,而move_right是该类的方法。因此,您必须将自身作为参数传递。
答案 1 :(得分:1)
所有这些方法
def move_up():
def move_down():
def move_right():
def move_left():
实际上是类矩形的方法,因此它们都需要“ self”参数,您必须将它们编辑为:
def move_up(self):
self.y = self.y + 3
def move_down(self):
self.y = self.y - 3
def move_right(self):
self.x = self.x + 3
def move_left(self):
self.x = left.x - 3