【发布时间】:2020-10-08 14:37:25
【问题描述】:
我是 python 新手。我的长期项目是设计一款选择你自己的冒险文字游戏。
这个游戏的一个主要组成部分是攻击场景。考虑到这一点,我一直在构建一个 python 程序来模拟攻击场景。在这种情况下,通过抛硬币来首先判断是玩家先攻击还是敌人先攻击。之后,使用 1 到 10 之间的随机整数作为攻击伤害。一个函数(HealthCheck),检查玩家/敌人的健康状况以确定玩家/敌人是否死亡。
我的主要问题是敌人和玩家的健康在攻击后重新开始。我的程序如何在攻击后保存用户的健康,而不是重置为 10 HP?
下面是我的python代码。感谢您的帮助。
import random
import time
import sys
enemyHealth = 10
playerHealth = 10
def playerAttack(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(enemyHealth)
pass
def enemyAttack(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(playerHealth)
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(enemyHealth)
else:
print("Enemy goes first.")
enemyAttack(playerHealth)
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(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(enemyHealth)
def enemyHealthCheck(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(playerHealth)
turnChoice()
【问题讨论】:
-
您需要阅读
global关键字。或者可能更好的是创建一个class来保存您的数据 -
这能回答你的问题吗? Using global variables in a function
-
这回答了我的问题。非常感谢。我也会尝试创建一个类,因为它对我的长期项目更灵活。谢谢
标签: python text-based