我正在創建一個互動式游戲,但我堅持讓“游戲”回圈正常作業。
我已要求用戶輸入以確定回圈數。該變數是一個整數,唯一接受的數字是 1-5(包括 1-5)。我期待的是,如果用戶輸入 2,那么游戲會回圈兩次(除非兩個角色都因健康下降到 0 而死亡)。
游戲中還有其他選項,例如重置角色健康等,然后用戶可以回傳戰斗選項并再次輸入他們想要玩的游戲數量。
我發現的是:
- 有時戰斗的數量與用戶輸入的匹配但有時它不起作用(即用戶輸入 2 但它玩 4 場游戲)
- 如果用戶輸入 1,它永遠不會起作用(我嘗試將 number_rounds != 1 周圍的行更改為 0 但這也不起作用
我只粘貼了相關的代碼片段,希望更熟悉 Python 的人能發現問題。提前致謝。
# Defining the function to display highest battles won
def do_battle(character_list, opponent1_pos, opponent2_pos):
# Requesting user input to select number of rounds to be played
number_rounds = int(input('Please enter number of battle rounds: '))
# While loop to validate input is a number between 1-5 inclusive
while number_rounds < 1 or number_rounds > 5:
print('Must be between 1-5 inclusive.')
number_rounds = int(input('Please enter number of battle rounds: '))
player1_health = character_list[opponent1_pos][-1]
player2_health = character_list[opponent2_pos][-1]
round_number = 0
for i in range(number_rounds):
while number_rounds != 1 and player1_health > 0 and player2_health > 0:
round_number = round_number 1
damage1 = random.randint(0, 50)
player1_health = max(0, player1_health - damage1)
character = character_list[opponent1_pos]
character[-1] = player1_health
damage2 = random.randint(0, 50)
player2_health = max(0, player2_health - damage2)
character = character_list[opponent2_pos]
character[-1] = player2_health
uj5u.com熱心網友回復:
用戶輸入 2 但它玩 4 個游戲
問題是你在while回圈中的for回圈——這就是為什么你得到比預期更多的回合,因為你在回圈中回圈。
如果我理解正確的意圖,你想要的是玩到 number_rounds幾局然后在其中一名玩家的生命值達到零時停止?
在那種情況下,你真正想要的只是一個if宣告。
此外,您不需要round_number變數,因為您有i來自 for 回圈。我看不出while number_rounds != 1兩者的意義。
我對固定版本的嘗試如下所示:
# Defining the function to display highest battles won
def do_battle(character_list, opponent1_pos, opponent2_pos):
# While loop to validate input is a number between 1-5 inclusive
number_rounds = 0
while True:
number_rounds = int(input('Please enter number of battle rounds: '))
if 1 <= number_rounds <= 5:
# exit the loop if they entered a valid value
break
print('Must be between 1-5 inclusive.')
player1_health = character_list[opponent1_pos][-1]
player2_health = character_list[opponent2_pos][-1]
for i in range(number_rounds):
print(f"Round #{i 1}")
damage1 = random.randint(0, 50)
player1_health = max(0, player1_health - damage1)
character = character_list[opponent1_pos]
character[-1] = player1_health
damage2 = random.randint(0, 50)
player2_health = max(0, player2_health - damage2)
character = character_list[opponent2_pos]
character[-1] = player2_health
# exit the battle if any of the players died
if player1_health == 0 or player2_health == 0:
break
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/441211.html
標籤:Python python-3.x 循环
