[英]How can I create a while loop that runs all the time but doesn't interfere with the order that the code runs in?
我正在用 Python 制作一個文本冒險游戲來讓自己入門,因為我還不太擅長 Python。 我試圖實施一套健康規則:
while True:
if health == maxHealth:
playerAtMaxHealth = True;
elif health > maxHealth:
health = maxHealth;
elif health < 0:
health = 0
elif health == 0:
playerDead = True;
這是我的其余代碼:
def startUp():
StartPRINT("""╔═══╗
║╔══╝
║╚══╦══╦══╦══╦══╦══╗
║╔══╣══╣╔═╣╔╗║╔╗║║═╣
║╚══╬══║╚═╣╔╗║╚╝║║═╣
╚═══╩══╩══╩╝╚╣╔═╩══╝
─────────────║║
─────────────╚╝ \n""")
global gold
global health
global inventory
global berryCollected;
global maxHealth;
global playerAtMaxHealth;
global playerDead
berryCollected = False;
playerAtMaxHealth = True;
playerDead = False
gold = 0
health = 30
maxHealth = 30
inventory = []
time.sleep(2)
while True:
if health == maxHealth:
playerAtMaxHealth = True;
elif health > maxHealth:
health = maxHealth;
elif health < 0:
health = 0
elif health == 0:
playerDead = True;
forest()
基本上發生的事情是它打印出開始文本,但隨后它只是卡在 while 循環中並且不會移動到 Forest() 上。
我不知道您是否已經考慮過這一點,但是以面向對象的方式來執行此操作可能會更好。 所以,以英雄或玩家為類,他的屬性是金幣、健康等。 然后你可以很容易地擁有一個可以在戰斗或互動后運行的功能,以檢查玩家是否還活着
不要使用 while true 來覆蓋健康規則。 所以如果你想檢查玩家的健康是這樣的.. 而真正的 Forest() // 也許與怪物打架 // 健康檢查在這里......
它會在森林中進行一些操作后進行健康檢查......如果你像你一樣寫它只會卡在健康檢查中
您可以簡單地將 while 循環包裹在一個線程中。 然后啟動線程,它不會更改代碼的其他結構。 在 Python 中創建線程非常容易。 您需要導入threading
然后您可以使用threading.Thread()
函數創建一個線程您可以創建任意數量的線程,您可以使用start()
函數簡單地啟動它們。 它們都將在不干擾您的代碼的情況下執行。
有關 python 線程的更多詳細信息,請參閱 python 的這個線程示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.