[英]How do you create a new thread in python?
I'm building a game in python, and I want to create an event listener that checks for when the main character's hp is smaller or equal to 0, and then executes a game over function. 我正在用python构建游戏,我想创建一个事件侦听器,以检查主要角色的hp小于或等于0的时间,然后执行游戏功能。 In other languages (vb.net) i have achieved this by creating a new thread that continuously loops an if statement until the condition is met, then runs the game over code, then closes itself.
在其他语言(vb.net)中,我通过创建一个新线程来实现此目的,该线程不断循环if语句直到满足条件,然后通过代码运行游戏,然后自行关闭。 How do you create/start/close threads in python?
如何在python中创建/启动/关闭线程? Also, is there a better way of doing this that is sitting right in front of me?
另外,有没有更好的方法可以做到这一点呢?
from threading import Thread
def my_function():
while True:
if player.lives < 5:
do_stuff()
Thread(my_function).start()
However most of the times the games are developed following a frame-loop rule, with the following structure: 但是,大多数情况下,游戏是按照以下框架规则开发的:
def my_game():
should_continue = False
while should_continue:
should_continue = update_logic()
update_graphics()
What you define in update_logic and update_graphics is up to you and the graphic library you're using (since you're using text, your function would just print text in your console), but some examples of the logic would be like this: 您在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
This does not make use of threads and using threads is most of the times a bad practice if multiple events occur. 这不使用线程,并且在大多数情况下,如果发生多个事件,则使用线程是一种不好的做法。 However in your text games, perhaps not so much elements are involved, so it's unlikely a race condition would occur.
但是,在您的文字游戏中,可能涉及的元素并不多,因此不太可能出现比赛条件。 Be careful, however.
但是要小心。 I always prefer these loops instead of threads.
我总是更喜欢这些循环而不是线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.