我正在尝试使用类在 pygame
中为屏幕上的对象设置动画。
我在没有类(class)的情况下尝试过这个并且工作得很好,但是在类(class)中它不起作用。
class Car:
def __init__(self):
self.locx = 20
self.locy = 90
self.x = 20
self.y = 90
def draw_car(self):
pygame.draw.circle(screen, RED, [self.locx, self.locy], 20, 8)
def animator(self):
self.locx += 5
def main_game(): # main game loop, for all code related to the simulation
game_play = False
while not game_play:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_play = True
pygame.quit()
clock.tick(60)
screen.fill(BLACK)
pygame.draw.line(screen, BLUE, [1, 450], [800, 450], 5)
draw_road()
Car()
绘制一个圆圈并使用类将其在屏幕上设置动画。
最佳答案
调用 Car()
只是创建一个 Car
对象。在您调用 Car.draw_car
或 Car.animator
之前,它不会被绘制或移动。您需要做的是在 while
循环之前创建 Car
对象,并将其分配给变量 my_car
say。要绘制和移动汽车,您需要在 while
循环中调用 my_car.animator()
和 my_car.draw_car
,即
def main_game(): # main game loop, for all code related to the simulation
game_play = False
my_car = Car()
while not game_play:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_play = True
pygame.quit()
clock.tick(60)
screen.fill(BLACK)
pygame.draw.line(screen, BLUE, [1, 450], [800, 450], 5)
draw_road()
my_car.animator()
my_car.draw_car()
关于python - 调用类并不运行方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56680176/