2015-09-25 1 views
0

ОШИБКА: Строка 29, на карте 'empty_room': Я пробовал переписывать свои классы и другие мелочи и не смог придумать ни одного решения. Мои отступы правильны (или так кажутся) в блокноте ++, они просто не очень хорошо перешли к SOF. Любое устранение неисправностей оценено :) СПАСИБО!ОШИБКА: EmptyRoom(), NameError: имя 'EmptyRoom' не определено

P.S. Я сам изучаю книгу «Learn Python the Hard Way», и я делаю упражнение, чтобы сделать игру похожей на zork. Надеюсь это поможет.

from sys import exit 

class Scene(object): 
def enter(self): 
    print "This scene is not configured" 
    exit(1) 


class Engine(object): 

##calling Engine(x) x is the mapScene 
def __init__(self, mapScene): 
    self.mapScene = mapScene 

def play(self): 
    currentScene = self.mapScene.openingScene() 

    while True: 

     print "\n-------------------" 
     nextSceneName = currentScene.enter() 
     currentScene = self.mapScene.nextScene(nextSceneName) 

class Map(object): 

scenes = { 
    'empty_room': EmptyRoom(), 
    'living_room': LivingRoom(), 
    'office': Office(), 
    'hallway': Hallway(), 
    'kitchen': Kitchen(), 
    'master_bedroom': MasterBedroom(), 
    'kids_bedroom': KidsBedroom(), 
    'attic': Attic() 
    } 

##when calling Map(x) x is the startscene 
def __init__(self, startScene): 
    self.startScene = startScene 


    ##When calling nextScene(x) x is the sceneName 
def nextScene(self, sceneName): 
    return Map.scenes.get(sceneName) 


    ##???? 
def openingScene(self): 
    return self.nextScene(self.startScene) 



class EmptyRoom(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "open door": 
     return 'living_room' 



class LivingRoom(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "kitchen": 
     return 'kitchen' 

    elif action == "stairs" or "go upstairs": 
     print "The steps creek as you ascend to the unknown..." 
     print "Are you sure you want to go up here?" 
     action = raw_input("> ") 

     if action == "yes" or "kinda": 
      return 'hallway' 

     else: 
      return 'living_room' 

    elif action == "empty room": 
     return 'empty_room' 


    else: 
     return 'living_room' 



class Kitchen(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "office" or "go right": 
     return 'office' 


    elif action == "living room": 
     return 'living_room' 

    else: 
     return 'kitchen' 


class Office(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "kitchen": 
     return 'kitchen' 



class MasterBedroom(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "hallway": 
     return 'hallway' 


class KidsBedroom(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "hallway": 
     return 'hallway' 


class Hallway(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "downstairs" or "stairs" or "living room": 
     return 'living_room' 

    elif action == "bedroom" or "master bedroom" or "left": 
     return 'master_bedroom' 

    elif action == "kids room" or "kids bedroom" or "right": 
     return 'kids_bedroom' 

    elif action == "pull string": 
     print"You have just opened the attic staircase would you like to go up?" 
     action = raw_input("> ") 

     if action == "yes": 
      return 'attic' 

     elif action == "no" or "nope": 
      return 'hallway' 

     else: 
      print "I wouldn't have went either\n" 
      print "SMASH, the attic door springs shut\n" 
      return 'hallway' 

    else: 
     return 'hallway' 


class Attic(Scene): 
def enter(self): 
    print "" 

    action = raw_input("> ") 

    if action == "downstairs" or "hallway": 
     return 'hallway' 

aMap = Map('empty_room') 
aGame = Engine(aMap) 
aGame.play() 
+0

Имена не существуют до тех пор, пока они не существуют. –

ответ

1

Определение класса должно быть первым, прежде чем оно будет использоваться.

class EmptyRoom(Scene): 
    def enter(self): 
     print "" 
     action = raw_input("> ") 
     if action == "open door": 
      return 'living_room' 

class Map(object): 
    scenes = { 
     'empty_room': EmptyRoom(), 
     ... 
    } 

То же самое для LivingRoom, Office, Hallway, Kitchen, MasterBedroom, KidsBedroom, Attic.

0

Определение scenes внутри Map выполняется, когда класс строится, а не когда вы позже вызываете класс для его создания. В то время EmptyRoom еще не существует - Python работает с верхней части вашего кода, поэтому EmptyRoom существует только после того, как он достиг конца отступающего блока под class EmptyRoom:. Поэтому для этого необходимо, чтобы Map должен был пойти после всех ваших других классов, а не раньше.

+0

Спасибо! Я чувствую себя настолько немым, что я этого не знал! Еще раз спасибо!! – Dramabeatz82