1 回答

TA貢獻1829條經驗 獲得超7個贊
要使代碼編輯您需要使用的變量globals
。當您在函數中使用括號調用變量時,它們只會在該變量的范圍內進行編輯,但是當您使用全局變量時,它們會針對整個程序進行編輯。下面是使用全局變量的代碼:
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack():
? ? global enemyHealth
? ? attack_damage = random.randint(1, 10)
? ? print("The player does " + str(attack_damage) + " damage points to the enemy.")
? ? enemyHealth -= attack_damage
? ? print("The enemy has " + str(enemyHealth) + " HP left!")
? ? enemyHealthCheck()
? ? pass
def enemyAttack():
? ? global playerHealth
? ? attack_damage = random.randint(1, 10)
? ? print("The enemy does " + str(attack_damage) + " damage points to the player.")
? ? playerHealth -= attack_damage
? ? print("The player has " + str(playerHealth) + " HP left!")
? ? playerHealthCheck()
? ? pass
def turnChoice():
? ? h = 1
? ? t = 2
? ? coin = ""
? ? while coin != "h" and coin != "t":
? ? ? ? coin = input("Player, flip a coin to decide who attack first.\n"
? ? ? ? ? ? ? ? ? ? ?"Heads or tails? H for heads. T for tails.\n")
? ? ? ? if coin == "h":
? ? ? ? ? ? print("You chose heads.\n"
? ? ? ? ? ? ? ? ? "Flip the coin. \n"
? ? ? ? ? ? ? ? ? ". . .")
? ? ? ? ? ? time.sleep(2)
? ? ? ? else:
? ? ? ? ? ? print("You chose tails.\n"
? ? ? ? ? ? ? ? ? "Flip the coin. \n"
? ? ? ? ? ? ? ? ? ". . .")
? ? ? ? time.sleep(2)
? ? ? ? choice = random.randint(1, 2)
? ? ? ? if choice == coin:
? ? ? ? ? ? print("Great choice. You go first.")
? ? ? ? ? ? playerAttack()
? ? ? ? else:
? ? ? ? ? ? print("Enemy goes first.")
? ? ? ? ? ? enemyAttack()
def replay():
? ? playAgain = ""
? ? while playAgain != "y" and playAgain != "n":
? ? ? ? playAgain = input("Do you want to play again? yes or no")
? ? if playAgain == "y":
? ? ? ? print("You chose to play again.")
? ? ? ? print(".")
? ? ? ? print(".")
? ? ? ? print(".")
? ? ? ? time.sleep(2)
? ? ? ? turnChoice()
? ? else:
? ? ? ? print("Game over. See you soon.")
? ? ? ? sys.exit()
def playerHealthCheck():
? ? global playerHealth
? ? if playerHealth <= 0:
? ? ? ? print("Player is dead. Game over.")
? ? ? ? replay()
? ? else:
? ? ? ? print("The player has " + str(playerHealth) + " HP points!")
? ? ? ? print("It is your turn to attack.")
? ? ? ? playerAttack()
def enemyHealthCheck():
? ? global enemyHealth
? ? if enemyHealth <= 0:
? ? ? ? print("Enemy is dead. You win.")
? ? ? ? replay()
? ? else:
? ? ? ? print("Enemy is not dead. The enemy has " + str(enemyHealth) + " HP points.")
? ? ? ? print("It is their turn to attack.")
? ? ? ? enemyAttack()
turnChoice()
添加回答
舉報