【发布时间】:2014-10-06 07:52:28
【问题描述】:
我正在开发一个简单的基于文本的战斗游戏,但遇到了一个(另一个)问题。我有一个主要功能和一个战斗功能,在战斗功能中,一旦您完成战斗,您将获得一定数量的 XP,然后(或应该)通过更改 player1.xp 的值来记住它。在战斗序列之后,我在代码中设置了它,如果 player1.xp >= 1,它会将 player1.level 的值更改为“2”。但是,每当我运行代码时,由于某种原因,战斗功能完成时 xp 值会丢失。我知道这是因为它在战斗功能后打印出 player1.xp 的值,并且显示为“0”。代码如下:
import random
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.health = health
self.strength = strength
self.defense = defense
self.name = name
self.potion = potion
self.xp = xp
self.level = level
def changeHealth(self, h):
self.health = h
def addLevel(self):
self.level += 1
def subHealth(self, num):
self.health -= num
return self.health
def subPotion(self):
self.potion -= 1
return self.health
def addPotion(self, num1):
self.potion += num1
def addHealth(self):
self.health +=2
def addXP(self):
self.xp += xp1
def battle1(enemy, player1, name1):
player1 = player(name1, player1.health, player1.strength, player1.defense, player1.potion, player1.xp, player1.level)
enemy = player("Rat", enemy.health, enemy.strength, enemy.defense, player1.potion, enemy.xp, enemy.level)
print("Fight!")
s = 0
while s == 0:
attack =input("Type 1 to attack, type 2 to use a potion.")
if attack == "1":
enemy.subHealth(15)
elif attack == "2":
if player1.potion > 0:
print("You used a potion.")
elif player1.potion <= 0:
print("You don't have any potions! You are forced to attack.")
enemy.subHealth(15)
else:
print("Your life depends on this!")
if enemy.health <= 0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player1.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player("Rat", 15, 0, 0, 0, 0, 0)
pick = input("You were walking along the path and found a potion! Press 'p' to pick it up.")
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion = 1
else:
print("You have no potions, you should probably pick this one up.")
print("You added a potion to your inventory.")
player1.addPotion = 1
battle1(enemy, player1, name1)
print(player1.xp)
if player1.xp >= 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
else:
print("You have 0 xp.")
main()
有人知道为什么会这样吗?谢谢!
【问题讨论】:
-
最简单的解释是,您认为正在发生的事情并非如此。我首先向
player.addXP添加一个打印语句以确认它被调用。 -
我试过了,但没有解决。
标签: python-3.x