这段代码究竟发生了什么?
问题描述:
我试图重新创建一个基本上是极简主义Tomagatchi的东西。然而,当它被喂养,并听取,这是“心情”的价值不会改变。它仍然“疯狂”。任何帮助将不胜感激!这段代码究竟发生了什么?
{#Create name, hunger, boredom attributes. Hunger and Boredom are numberical attributes
class Critter(object):
def __init__(self, name, hunger = 0, boredom = 0):
self.name = name
self.hunger = hunger
self.boredom = boredom
#Creating a private attribute that can only be accessed by other methods
def __pass_time(self):
self.hunger += 1
self.boredom += 1
def __get_mood(self):
unhappiness = self.hunger + self.boredom
if unhappiness < 5:
mood = "happy"
if 5 <= unhappiness <= 10:
mood = "okay"
if 11 <= unhappiness <= 15:
mood = "frustrated"
else:
mood = "mad"
return mood
mood = property (__get_mood)
def talk(self):
print "Hi! I'm",self.name,"and I feel",self.mood,"now."
self.__pass_time()
def eat(self, food = 4):
print "Brrruuup. Thank you!"
self.hunger -= food
if self.hunger < 0:
self.hunger = 0
self.__pass_time()
def play(self, play = 4):
print "Yaaay!"
self.boredom -= play
if self.boredom < 0:
self.boredom = 0
self.__pass_time()
def main():
crit_name = raw_input("What do you want to name your critter? ")
crit = Critter (crit_name)
choice = None
while choice != "0":
print \
""" 0 - Quit
1 - Listen to your critter.
2 - Feed your critter
3 - Play with your critter
"""
choice = raw_input ("Enter a number: ")
#exit
if choice == "0":
print "GTFO."
#listen to the critter
elif choice == "1":
crit.talk()
#feed the crit crit critter
elif choice == "2":
crit.eat()
#play with the crit crit critter
elif choice == "3":
crit.play()
#some unknown choice
else:
print "\nwat"
main()
raw_input ("\n\nHit enter to GTFO")
答
在_getMood中,应该有elifs。
if unhappiness < 5:
mood = "happy"
elif 5 <= unhappiness <= 10:
mood = "okay"
elif 11 <= unhappiness <= 15:
mood = "frustrated"
else:
mood = "mad"
没有他们,它实际上只是检查不快乐是否在11和15之间,如果不是,设置心情变得疯狂。因此,从0到10不等,而从16开始,一个生物就会发疯。
答
我会说在这种情况下,替代一个变量并追踪代码。
不快= 3
if unhappiness < 5:
mood = "happy"
确定我们成为幸福
if 5 <= unhappiness <= 10:
mood = "okay"
什么都没有发生在3不在范围内的5 < = X < = 10
if 11 <= unhappiness <= 15:
mood = "frustrated"
什么都没有发生因为3不在11 < x的范围内15
else:
mood = "mad"
别的什么?这是指最后一个条件。所以如果它不是11 < x < 15那么我们很生气。
用值替换一个变量,然后逐行跟踪代码,这通常是您应该在这种情况下尝试的方法,至少在它变成第二性质之前。
1.您的缩进被打破。 2.代码开始处至少有一行丢失(类似于'class Critter:')。 – 2011-05-30 17:52:28
我已更正您的格式,但仍存在缩进问题? “choice = None”和“while”循环的代码级别是多少? – 2011-05-30 17:54:04