简体   繁体   English

如何在继续 Python 中脚本的其余部分的同时运行无限循环

[英]How to run an infinite loop while continuing the rest of the script in Python

I am a beginner Python developer and I am making a text-based adventure game.我是一名初级 Python 开发人员,我正在制作一个基于文本的冒险游戏。 I am at the point where I am setting up a time system for the game.我现在正在为游戏设置时间系统。 I want to add one minute to the game for every second that passes in real-time.我想为实时过去的每一秒增加一分钟。 So essentially, I want to run a loop indefinitely while the rest of the code is also executed.所以本质上,我想无限期地运行一个循环,同时执行其余的代码。

This is what I have so far.这是我到目前为止。 It seems that it is looping and adding time to stor_time, but it does not continue everything else below it.似乎它正在循环并向 stor_time 添加时间,但它不会继续下面的所有其他内容。 How can I fix this?我怎样才能解决这个问题? Thank you!谢谢!

I suggest you use multithreading concept.我建议您使用多线程概念。 By using multithreading what you can do is have this infinite loop running in your separate thread and the rest of the code will keep running without interruption.通过使用多线程,您可以做的是让这个无限循环在您的单独线程中运行,而其余代码将继续运行而不会中断。

Also if you want to share some variables in this thread and your script, don't forget to use global for variable.另外,如果您想在此线程和脚本中共享一些变量,请不要忘记对变量使用 global。

Some reference link : https://www.geeksforgeeks.org/multithreading-python-set-1/一些参考链接: https : //www.geeksforgeeks.org/multithreading-python-set-1/

Welcome to Stack Exchange!欢迎使用堆栈交换!

Try:尝试:

Mins = 0 ##Assign the variable Mins

def Update_Timer():
    Mins = Mins + 1 ##Add 1 to the Mins.

clock.schedule_interval(Update_Timer, 1.0) ##Every 1.0 Seconds, run Update_Timer()

To update the variable Mins every 1 second.每 1 秒更新一次变量 Mins。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM