2011-05-30 108 views
0

我試圖重新創建一個基本上是極簡主義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") 
+0

1.您的縮進被打破。 2.代碼開始處至少有一行丟失(類似於'class Critter:')。 – 2011-05-30 17:52:28

+0

我已更正您的格式,但仍存在縮進問題? 「choice = None」和「while」循環的代碼級別是多少? – 2011-05-30 17:54:04

回答

7

在_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開始,一個生物就會發瘋。

2

我會說在這種情況下,替代一個變量並追蹤代碼。

不快= 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那麼我們很生氣。

用值替換一個變量,然後逐行跟蹤代碼,這通常是您應該在這種情況下嘗試的方法,至少在它變成第二性質之前。