你如何在python中创建一个新的线程?

时间:2015-12-21 22:52:04

标签: python multithreading

我正在用python构建一个游戏,我想创建一个事件监听器来检查主角的hp何时小于或等于0,然后执行游戏而不是函数。在其他语言(vb.net)中,我通过创建一个新的线程来实现这一点,该线程不断循环if语句直到满足条件,然后通过代码运行游戏,然后自行关闭。你如何在python中创建/启动/关闭线程?另外,有没有更好的方法来做到这一点,就在我面前?

1 个答案:

答案 0 :(得分:2)

from threading import Thread

def my_function():
    while True:
        if player.lives < 5:
            do_stuff()

Thread(my_function).start()

然而,大多数时候游戏是按照帧循环规则开发的,具有以下结构:

def my_game():
    should_continue = False
    while should_continue:
        should_continue = update_logic()
        update_graphics()

您在update_logic和update_graphics中定义的内容取决于您和您正在使用的图形库(因为您正在使用文本,您的功能只会在您的控制台中打印文本),但是一些示例逻辑就像这样:

def update_logic():
    if player.lives < 5:
        return False
    # these are just examples, perhaps not valid in your game
    player.xdirection = 0
    player.ydirection = 0
    player.speed = 0
    player.hitting = False
    if player.damage_received_timer > 0:
        player.damage_received_timer -= 1
    if right_key_pressed:
        player.xdirection = 1
    if left_key_pressed:
        player.xdirection = -1
    if up_key_pressed:
        player.ydirection = -1
    if down_key_pressed:
        player.ydirection = +1
    if player.ydirection or player.xdirection:
        player.speed = 20
    if space_key_pressed:
        player.hitting = True
    # bla bla bla more logic
    return True

如果发生多个事件,这不会使用线程并且使用线程大多数情况下都是不好的做法。然而,在你的文字游戏中,可能没有涉及太多的元素,因此不太可能出现竞争条件。但是要小心。我总是喜欢这些循环而不是线程。

相关问题