我正在尝试进行文字冒险,以帮助保持兴趣,同时尝试学习Python的概念和细微差别。我最初跟随着YouTube教程(第6部分系列,第1部分提供了链接:https://www.youtube.com/watch?v=MFW8DJ6qsak)。
我创建了播放器类,如下所示:
class Player:
def __init__(self):
self.name = ''
self.jobclass = ''
self.currenthp = 0
self.totalhp = 0
self.currentmp = 0
self.totalmp = 0
self.physical_damage = 0
self.physical_defense = 0
self.magic_attack = 0
self.magic_defense = 0
self.speed = 0
self.luck = 0
self.status_effect = []
self.location ='b2'
self.game_over = False
myPlayer = Player()
我当前的问题是尝试根据玩家选择的角色工作为玩家分配某些统计信息,即:
def setup_game():
...
player_jobclass = input("> ")
myPlayer.jobclass = player_jobclass
valid_jobs = ['warrior', 'mage', 'thief', 'cleric']
while player_jobclass.lower() not in valid_jobs:
print("Please choose a valid class")
player_jobclass = input("> ")
if player_jobclass.lower() in valid_jobs:
myPlayer.jobclass = player_jobclass
print("Ah, the " +player_jobclass.lower()+ ". Fine choice!\n")
#Class Starting Stats
if myPlayer.jobclass is 'warrior':
self.currenthp = 20
self.totalhp = 20
self.currentmp = 10
self.totalmp = 10
self.physical_damage = 10
self.physical_defense = 10
self.magic_attack = 2
self.magic_defense = 3
self.speed = 4
self.luck = 4
self.location = 'd1'
elif myPlayer.jobclass is 'mage':
self.currenthp = 10
self.totalhp = 10
self.currentmp = 20
self.totalmp = 20
self.physical_damage = 2
self.physical_defense = 3
self.magic_attack = 10
self.magic_defense = 7
self.speed = 7
self.luck = 3
self.location = 'a1'
...
main_game_loop()
因为这一切都运行了,所以我可以很好地进入游戏,并且所有动作和小动作都可以正常工作,但是,如果我尝试通过以下方式打印玩家的“状态”:
def show_stats():
hpmpadarmPrint = ("" + str(myPlayer.currenthp) + "/" + str(myPlayer.totalhp) + " hp " + str(myPlayer.currentmp) + "/" + str(myPlayer.totalmp) + " mp " + str(myPlayer.physical_damage) + " ATK " + str(myPlayer.physical_defense) + " ARM \n")
mgclckspdPrint = ("" + str(myPlayer.magic_attack) + " AP " + str(myPlayer.magic_defense) + " MR " + str(myPlayer.speed) + " SPD " + str(myPlayer.luck) + " LCK \n")
所有打印的内容是:
0/0 hp 0/0 mp 0 ATK 0 ARM
0 AP 0 MR 0 SPD 0 LCK
我可以说有一个更大的概念使我难以理解,即使分配self.location = 'b2'
也必须存在值,否则游戏将无法运行,因为myPlayer实际上并未分配我相信的值这应该。这也使我的change_text_speed()
函数无法正常工作,而且……您得到了它。
猜测的主要问题是:一旦分配了新值,如何保持?
答案 0 :(得分:3)
self
和myPlayer
是两个不同的对象。您可以进行两种修复。首先,在设置统计信息时将self替换为myPlayer。
if myPlayer.jobclass is 'warrior':
myPlayer.currenthp = 20
myPlayer.totalhp = 20
myPlayer.currentmp = 10
...
第二种也是我的选择,更好的方法是在__init__
中设置统计信息。看起来像这样。
if self.jobclass is 'warrior':
self.currenthp = 20
self.totalhp = 20
self.currentmp = 10
...
要使代码更好,请阅读继承并为每个jobclass创建一个类。毕竟,您称它为工作班。
答案 1 :(得分:1)
is
检查两个变量是否指向完全相同的对象。在像您这样的情况下,输入用户字符串时,您很可能会有两个具有相同值的不同字符串对象。例如:
>>> x = input("")
ab
>>> x
'ab'
>>> x == "ab"
True
>>> x is "ab"
False
长话短说-在查看玩家==
时使用is
,而不是jobClass
。