如何在计时器事件后将返回值存储到变量中?

时间:2017-11-30 17:10:27

标签: python timer pygame

我希望在运行我的timer_event调用一秒后将最终的pong位置结果存储到变量中。我不知道该怎么做。这是我的功能

def get_final_position(self):

    return (pong.rect.centerx, pong.rect.centery)

def hard_AI_mode(self, pong, paddle):

    initial_pong_position = (pong.rect.centerx, pong.rect.centery)
    pygame.time.set_timer(self.get_final_position(), 1000)

    final_pong_position = ???

2 个答案:

答案 0 :(得分:1)

正如skrx所说,你以错误的方式使用set_timer

它必须发送你必须在mainloop中捕获的事件并执行你的功能。

import pygame

# --- constants ---

AFTER_SECOND = pygame.USEREVENT + 1

# --- functions ---

def get_final_position():
    print('one second later')

    # stop event AFTER_SECOND
    pygame.time.set_timer(AFTER_SECOND, 0)

    return pong_rect.center

# --- main ---

pygame.init()
screen = pygame.display.set_mode((400, 300))

# - objects -

pong_rect = pygame.Rect(0, 0, 10, 10)

# - start -

print('start game')

initial_pong_position = pong_rect.center
print('initial:', initial_pong_position)

# repeat sending event AFTER_SECOND every 1000ms
pygame.time.set_timer(AFTER_SECOND, 1000)

# --- mainloop ---

clock = pygame.time.Clock()
is_running = True

while is_running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            is_running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                is_running = False

        elif event.type == AFTER_SECOND:
            final_pong_position = get_final_position()
            print('initial:', initial_pong_position)
            print('  final:', final_pong_position)

    screen.fill((0,0,0))
    pygame.display.update()
    clock.tick(25)

pygame.quit()

答案 1 :(得分:0)

在这种情况下,你应该先为pong创建一个sprite,如果你还没有它,网上有几个指南。 在“pong”精灵类中,放置一个pos变量和一个vel变量。

Pos = (x, y) # x and y being position pong needs to be
Vel = (0, 0) # we will change this later

在pong sprites update函数中,将self.pos添加到self.vel并将self.rect.center设置为pos 按下某个键后,我们将vel更改为(x, y) # x is left/right, y is up/down 当一个键出现时,我们将vel改回(0,0) 在get_final_position内,设置centerx = pong.pos[1]centery = pong.pos[2],然后返回centerx和centery

我希望这是您正在寻找的回应。

修改

好吧,那很容易,只需创建一个名为dt的变量并将其设置为clock.tick(FPS_You_are_using) / 1000在游戏循环开始之前定义它。之后,当在get_final_position中,设置一个名为timer的变量,然后创建一个从timer中减去dt的循环,一旦timer = 0,退出该循环,然后完成其余的

相关问题