2011-02-13 58 views
0

我在練習43,在Learn Python The Hard Way做一些自我指導的工作。我設計了一個分佈在兩個python文件中的遊戲框架。練習的要點是遊戲中的每個「房間」都有不同的課程。我已經嘗試了很多東西,但我無法弄清楚如何使用返回的值從最初的選擇中將用戶推到適當的「房間」,該房間包含在一個類中。任何提示或幫助將不勝感激。如何使用返回的值在Python中打開另一個類的實例?

爲窮代碼道歉,我剛剛開始在Python中,但在我的智慧結束。

這是我開始遊戲時運行的ex43_engine.py代碼。


from ex43_map import * 
import ex43_map 
import inspect 

#Not sure if this part is neccessary, generated list of all the classes (rooms) I imported from ex43_map.py, as I thought they might be needed to form a "map" 
class_list = [] 
for name, obj in inspect.getmembers(ex43_map): 
    if inspect.isclass(obj): 
     class_list.append(name) 

class Engine(object): 

    def __init__(self, room): 
     self.room = room 


    def play(self): 
     # starts the process, this might need to go inside the loop below 
     next = self.room  
     start.transportation_choice() 

     while True: 
      print "\n-------------" 
      # I have tried numerous things here to make it work...nothing has 

start = StartRoom() 
car = CarRoom() 
bus = BusRoom() 
train = TrainRoom() 
airplane = AirplaneRoom() 
terminal = TerminalRoom() 

a_game = Engine("transportation_choice") 
a_game.play() 

這裏是ex43_map.py代碼


from sys import exit 
from random import randint 

class StartRoom(object): 
    def __init__(self): 
     pass 
    def transportation_choice(self): 
     print "\nIt's 6 pm and you have just found out that you need to get to Chicago by tomorrow morning for a meeting" 
     print "How will you choose to get there?\n" 
     print "Choices: car, bus, train, airplane" 
     choice = raw_input("> ") 

     if choice == "car": 
      return 'CarRoom' 

     elif choice == "bus": 
      return 'BusRoom' 

     elif choice == "train": 
      return 'TrainRoom' 

     elif choice == "airplane": 
      return 'AirplaneRoom' 

     else: 
      print "Sorry but '%s' wasn't a choice." % choice 
      return 'StartRoom' 


class CarRoom(object): 

    def __init__(self): 
     print "Welcome to the CarRoom" 

class BusRoom(object): 

    def __init__(self): 
     print "Welcome to the BusRoom" 

class TrainRoom(object): 

    def __init__(self): 
     print "Welcome to the TrainRoom" 

class AirplaneRoom(object): 

    def __init__(self): 
     print "Welcome to the AirplaneRoom" 

class TerminalRoom(object): 

    def __init__(self): 
     self.quips = [ 
      "Oh so sorry you died, you are pretty bad at this.", 
      "Too bad, you're dead buddy.", 
      "The end is here.", 
      "No more playing for you, you're dead." 
      ] 

    def death(self): 
      print self.quips[randint(0, len(self.quips)-1)] # randomly selects one of the quips from 0 to # of items in the list and prints it 
      exit(1) 

回答

1

而不是返回一個字符串,請返回一個對象,即

if choice == "car": 
     return CarRoom() 
0
  1. 製作Room類並從中派生出其他房間可能是個好主意。

  2. Room基類可以有一個類變量,它自動跟蹤所有實例化的房間。

我還沒有徹底測試以下,但希望它會給你一些想法:

# getters.py 
try: 
    getStr = raw_input # Python 2.x 
except NameError: 
    getStr = input  # Python 3.x 
getStr.type = str 

def typeGetter(dataType): 
    def getter(msg): 
     while True: 
      try: 
       return dataType(getStr(msg)) 
      except ValueError: 
       pass 
    getter.type = dataType 
    return getter 

getInt = typeGetter(int) 
getFloat = typeGetter(float) 
getBool = typeGetter(bool) 

def getOneOf(*args, **kwargs): 
    """Get input until it matches an item in args, then return the item 

    @param *args: items to match against 
    @param getter: function, input-getter of desired type (defaults to getStr) 
    @param prompt: string, input prompt (defaults to '> ') 

    Type of items should match type of getter 
    """ 
    argSet = set(args) 
    getter = kwargs.get('getter', getStr) 
    prompt = kwargs.get('prompt', '> ') 

    print('[{0}]'.format(', '.join(args))) 
    while True: 
     res = getter(prompt) 
     if res in argset: 
      return res 

# ex43_rooms.py 
import textwrap 
import random 
import getters 

class Room(object): 
    # list of instantiated rooms by name 
    ROOMS = {} 

    @classmethod 
    def getroom(cls, name): 
     """Return room instance 
     If named room does not exist, throws KeyError 
     """ 
     return cls.ROOMS[name] 

    def __init__(self, name): 
     super(Room,self).__init__() 
     self.name = name 
     Room.ROOMS[name] = self 

    def run(self): 
     """Enter the room - what happens? 
     Abstract base method (subclasses must override) 
     @retval Room instance to continue or None to quit 
     """ 
     raise NotImplementedError() 

    def __str__(self): 
     return self.name 

    def __repr__(self): 
     return '{0}({1})'.format(self.__class__.__name__, self.name) 

class StartRoom(Room): 
    def __init__(self, name): 
     super(StartRoom,self).__init__(name) 

    def run(self): 
     print textwrap.dedent(""" 
      It's 6 pm and you have just found out that you need to get to Chicago 
      by tomorrow morning for a meeting! How will you get there? 
     """) 
     inp = getters.getOneOf('car','bus','train','airplane') 
     return Room.getroom(inp) 

class CarRoom(Room): 
    def __init__(self,name): 
     super(CarRoom,self).__init__(name) 

class BusRoom(Room): 
    def __init__(self,name): 
     super(BusRoom,self).__init__(name) 

class TrainRoom(Room): 
    def __init__(self,name): 
     super(TrainRoom,self).__init__(name) 

class PlaneRoom(Room): 
    def __init__(self,name): 
     super(PlaneRoom,self).__init__(name) 

class TerminalRoom(Room): 
    def __init__(self,name): 
     super(TerminalRoom,self).__init__(name) 

    def run(self): 
     print(random.choice((
      "Oh so sorry you died, you are pretty bad at this.", 
      "Too bad, you're dead buddy.", 
      "The end is here.", 
      "No more playing for you, you're dead." 
     ))) 
     return None 

# create rooms (which registers them with Room) 
StartRoom('start') 
CarRoom('car') 
BusRoom('bus') 
TrainRoom('train') 
PlaneRoom('airplane') 
TerminalRoom('terminal') 

# ex43.py 
from ex43_rooms import Room 

def main(): 
    here = Room.getroom('start') 
    while here: 
     here = here.run() 

if __name__=="__main__": 
    main() 
相關問題