python - 调用类并不运行方法

标签 python pygame

我正在尝试使用类在 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_carCar.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/

相关文章:

python - 删除 Python 中的最后一个 STDOUT 行

python - 类型错误 : 'int' object has no attribute '__getitem__'

python - python pygame 中的分数没有变化

Python、Pygame 鼠标事件

python - 左边的pygame Sprite 碰撞

python - 如何加载动画 GIF 并获取 Pygame 中的所有单独帧?

python - 将多个 div 类中的数据抓取到 pandas 数据框中

python - Matplotlib 中的重复刻度标签

Python 日期工具 : Unable to calculate age from two dates (relativedelta)

Python 类型错误 : 'NoneType' object is not iterable