我有一个非常简单的python问题,因为我对这门语言非常陌生。我开始写一个快速的程序只是为了练习,但现在变得沮丧,因为我不能让它工作。你知道吗
import random
import sys
class Meta:
turncounter = 1
class Enemy:
life = 10
wis = 1
str = 3
def heal(self):
healscore = self.wis + random.randrange(1, 7, 1)
self.life += healscore
print "Enemy healed for " + str(healscore) + ".\n"
self.checklife()
Meta.turncounter += 1
def attack(self, player):
damage = self.str + random.randrange(1, 5, 1)
player.life -= damage
print "You took " + str(damage) + " damage.\n"
Player.checklife(player)
Meta.turncounter += 1
def checklife(self):
if self.life <= 0:
print "The enemy is dead.\n"
sys.exit(0)
else:
print "Enemy's HP: " + str(self.life) + ".\n"
class Player:
life = 50
wis = 3
str = 5
def heal(self):
healscore = self.wis + random.randrange(1, 7, 1)
self.life += healscore
print "You healed for " + str(healscore) + ".\n"
Meta.turncounter += 1
def attack(self, enemy):
damage = self.str + random.randrange(1, 5, 1)
enemy.life -= damage
print "You did " + str(damage) + " damage.\n"
Enemy.checklife(enemy)
Meta.turncounter += 1
def checklife(self):
if self.life <= 0:
sys.exit("You died!")
else:
print "HP: " + str(self.life) + ".\n"
paladin = Player()
hollow = Enemy()
turnmeta = Meta.turncounter % 2
move = random.randrange(1, 3, 1)
print turnmeta
print move
while turnmeta == 0:
if move == 1 and paladin.life <= 10:
paladin.heal()
print turnmeta
elif move != 0 or (move == 1 and hollow.life > 15):
paladin.attack(hollow)
print turnmeta
while turnmeta > 0:
if move == 1 and hollow.life <= 15:
print turnmeta
elif move != 0 or (move == 1 and hollow.life > 15):
hollow.attack(paladin)
print turnmeta
正如您所看到的,这个程序并不特别复杂;它只是用来理解python语法和循环之类的东西。出于某种原因,每当我运行这个程序时,转辙机不是递增的,圣骑士/空心人有一个来回的,转辙机保持锁定在1,导致空心人攻击,直到圣骑士死亡,立即结束程序。你知道吗
如果
move == 1
,则第二个while循环永远不会结束,因为变量turnmeta
的值永远不会更改,并且始终为1,变量“move”始终为1。你知道吗你需要在循环中给它们一个新值:
turnmeta = Meta.turncounter % 2
和move = random.randrange(1, 3, 1)
,如果我正确理解你的程序的话。你知道吗问题是while循环依赖于
turnmeta
,当您在类方法中增加Meta.turncounter
时,它不会改变。你知道吗注意:
只需使用
Meta.turncounter
。你知道吗也就是说,您的设计严重依赖于类属性,它不是一个好的设计,浏览一下您的代码,我不认为您正在做您认为您正在做的事情。Python类定义不同于Java。你知道吗
您需要使用
self.attribute
在__init__
方法(或任何其他方法)内部定义实例属性,而不是像在类定义中那样在类命名空间中定义。你知道吗阅读文档: https://docs.python.org/3.5/tutorial/classes.html
turnmeta
是计算的结果Meta.turncounter % 2
。你知道吗它不再引用你的
Meta.turncounter
。你知道吗你应该在每个回合后重新分配turnmeta。你知道吗
相关问题 更多 >
编程相关推荐