我正在制作一个小型的Python控制台RPG。我有一个非常基本的战斗系统,但我player
和enemy
的健康值在他们受到伤害后会继续重置。关于为什么会发生这种情况的任何想法?我认为它可能与我的变量不是global
或者没有被正确声明有关,但是我找不到错误(我不太了解全局变量在Python中是如何工作的) 。我做了一些测试(你可以通过# Testing
注释看到),而attack()
函数确实消除了健康状况,但当它返回到fight()
函数时,健康状况又恢复到100两个变量的百分比。
import sys
import os
import random
def clear(): return os.system('clear')
# Program
class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
class Goblin:
def __init__(self, name):
self.name = name
self.max_health = 50
self.health = self.max_health
self.attack = 2
self.health_stat = "{}/{}".format(self.health, self.max_health)
goblin = Goblin("Goblin")
# all other enemies are the same as the Goblin
enemies = [wolf, goblin, rat, bandit]
# New game
def start0():
global player
player = Player('Mark')
start1()
def start1():
clear()
print("Name: {}\n"
"Health: {}\n"
"".format(player.name, player.health_stat,))
print(".1) Fight\n"
".4) Exit\n")
selection = input("-> ")
if selection == "1":
select_enemy_to_fight()
fight()
elif selection == "4":
sys.exit()
def select_enemy_to_fight():
global enemy
enemy = random.choice(enemies)
# Actions
def attack():
clear()
playerAttack = random.randint(0, player.attack)
enemyAttack = random.randint(0, enemy.attack)
#player attack
if playerAttack == 0:
print("You miss!")
else:
enemy.health -= playerAttack
print("You dealt {} damage!".format(playerAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
if enemy.health <= 0:
win()
clear()
# Enemy attack
if enemyAttack == 0:
print("The enemy missed!")
else:
player.health -= enemyAttack
print("The enemy dealt {} damage!".format(enemyAttack))
# Testing
print("PH = ", player.health)
print("EH = ", enemy.health)
input(" ")
# clear()
dead() if player.health <= 0 else fight()
def fight():
global enemy
global player
clear()
print("{} vs {}".format(player.name, enemy.name))
print("{}'s Health: {} {}'s Health: {}".format(player.name, player.health_stat, enemy.name, enemy.health_stat))
print(".1) Attack\n"
".3) Run Away\n")
selection = input("-> ")
if selection == "1":
attack()
elif selection == "3":
run()
main()
答案 0 :(得分:0)
您可以尝试在attack
函数中标记变量全局,就像您在fight
中看到的一样吗?
答案 1 :(得分:0)
刚发现问题:
class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
self.health_stat = "{}/{}".format(self.health, self.max_health)
self.health_stat
正在使用原始self.health
,因此在self.health
更改后self.health_stat
保持不变。
我做了这个解决方案:
class Player:
def __init__(self, name):
self.name = name
self.max_health = 100
self.health = self.max_health
self.attack = 5
def health_stat(self):
return "{}/{}".format(self.health, self.max_health)