2016-07-11 2 views
0

저는 Learn Python the Hard Way을 통해 작업했으며 현재 텍스트 기반 게임을 코딩해야하는 섹션에 있습니다. 필자는 필자가 제공 한 게임에서 코드를 가져 와서 내 자신의 게임을 위해 파일로 가져올 수있는 일종의 템플릿을 얻을 때까지 "추상화"했습니다. 템플릿 모듈의 클래스와 메소드를 사용하고 내 게임과 관련된 세부 정보 만 제공하면됩니다. 이렇게하면 템플릿에있는 모든 것을 다시 작성할 필요가 없습니다. 의 I는 다음과 같습니다를 사용하고 템플릿 :모듈을 잘못 가져 왔습니까?

""" This module provides some classes for constructing an interactive, 
text-based game. You should ideally subclass what's provided here, and 
override methods or provide new methods as you see fit. 
""" 
from sys import exit 
from random import randint 

# TODO: keep Scene class and Map class here, move everything else outside and just import (?) 
# TODO: move dialogs to text files (?) 
# TODO: remove 'random' import, 'sys' probably needs to stay 

class Scene(object): 
    """ A basic class describing a scene in your game. You should subclass this and implement your own version of enter(). """ 
    def enter(self): 
     """ Play out the scene and return a string key referring to the next scene.""" 
     print "This scene is not yet configured. Subclass it and implement enter()." 
     exit(1) 

class Engine(object): 
    """ The main engine that runs the actual game. This is where scenes are 
    stepped through. You could add a system to change the starting point of 
    your game depending on a save state, etc. 
    """ 

    # initialize the engine with a map of scenes 
    def __init__(self, scene_map): 
     """ Initialize the engine with a map of all scenes in your game. """ 
     self.scene_map = scene_map 

    def play(self): 
     """ Start the game with the map set at the opening scene. 
     Also grab the final scene of your game. Continue through the game 
     as long as you aren't at the final scene. Then, make sure you 
     actually play the final scene. 
     """ 
     # current_scene is the results of scene_map's opening_scene() 
     current_scene = self.scene_map.opening_scene() 

     # last_scene is grabbing the next scene, with param of 'finished' 
     last_scene = self.scene_map.next_scene('scene') 

     # while you're not on the final scene/room 
     while current_scene != last_scene: 
      next_scene_name = current_scene.enter() 
      current_scene = self.scene_map.next_scene(next_scene_name) 

     # be sure to print out the last scene 
     current_scene.enter() 


# TODO: abstract this class 
class Map(object): 
    """ Essentially holds all the scenes for your game and provides methods for grabbing the opening scene and next scene. 
    Subclass this and provide your own scenes. 
    """ 
    #scenes = {"scene": Scene()} 

    def __init__(self, start_scene, scenes={"scene": Scene()}): 
     # set the dictionary of scenes 
     self.scenes = scenes 
     """ Initialize the map with whatever your starting scene is. """ 
     self.start_scene = start_scene 

    def next_scene(self, scene_name): 
     """ Get the value of scene_name and return it. """ 
     val = self.scenes.get(scene_name) 
     return val 

    def opening_scene(self): 
     """ Return the scene your game will start with. """ 
     return self.next_scene(self.start_scene) 

a_map = Map('scene') 
a_game = Engine(a_map) 
a_game.play() 

내 자신의 게임 파일은 다음과 같다 : I는 현재 Fail()을 테스트하고 있습니다

from sys import exit 
from random import randint 
from game_template import * 

scenes = { 
     "RudeWakeUp": RudeWakeUp(), 
     "Fridge": Fridge(), 
     "PlugFix": PlugFix(), 
     "PlumbingFix": PlumbingFix(), 
     "FridgeRelocation": FridgeRelocation(), 
     "Final": Final(), 
     "Fail": Fail() 
     } 
class Fail(Scene): 
    def enter(self): 
     print "Well, it looks like the fridge is staying right where it is." 
     exit(1) 

class RudeWakeUp(Scene): 
    pass 

class Fridge(Scene): 
    pass 

class PlugFix(Scene): 
    pass 

class PlumbingFix(Scene): 
    pass 

class FridgeRelocation(Scene): 
    pass 

class Final(Scene): 
    pass 

# TEST AREA 
game_map = Map('Fail', scenes) 
game = Engine(game_map) 
game.play() 

. 문제는 게임 파일을 실행할 때 Fail() 대신에 템플릿의 Scene() 기본 클래스에서 출력을 얻는다는 것입니다. 잘못 가져 오기했거나 잘못 상속했기 때문에입니까? 전에 파이썬으로 프로그래밍을 해봤지만, 중요한 것을 만들었으니 꽤 오랜 시간이 걸렸습니다. 그리고 클래스가 어떻게 작동하는지 잊어 버렸을 것입니다. 어떤 도움을 주시면 감사하겠습니다.

답변

0

오래 전에 python이 선언적 언어이며 코드가 줄 단위로 실행된다는 것을 알게되었을 것입니다. 당신이 문제를 해결해야하는 클래스를 지정하기 전에 Fail를 선언 할 수 있도록

class Fail(Scene): 
    def enter(self): 
     print "Well, it looks like the fridge is staying right where it is." 
     exit(1) 
scenes = { 
    "RudeWakeUp": RudeWakeUp(), 
    "Fridge": Fridge(), 
    "PlugFix": PlugFix(), 
    "PlumbingFix": PlumbingFix(), 
    "FridgeRelocation": FridgeRelocation(), 
    "Final": Final(), 
    "Fail": Fail() 
    } 

은 간단하게 순서를 변경. 실제로 다른 모든 클래스도 선언 된 후에 scenes을 설정할 수 있습니다.

+0

"그 클래스를 지정하기 전에"Fail()을 선언하는 것이 무슨 뜻인지 이해할 수 없다고 생각합니다. " 'Fail()'에 대한 클래스 정의를 나머지 장면 클래스의 맨 아래로 옮기고 그 아래 장면 사전을 옮겨 보았습니다. 그러나 여전히'Scene()'기본 클래스로부터 결과를 얻고 있습니다. – alyms108

+0

기본적으로 모든 클래스 정의 뒤에 * scenes 정의 *를 설정해야합니다. ** 템플릿 ** 코드는 ** 게임 ** 코드 전에로드됩니다. 이 모든 것을 [repl.it] (https://repl.it/CbHD)에 넣었고'장면 '정의 만 옮겼습니다. 나머지 코드는 정상적으로 작동하는 것 같습니다. –

+0

템플릿 코드는 클래스 정의와 함께 있고 다른 모든 파일은 같은 파일에있는 것처럼 보입니다. 템플릿을 자체 파일로 유지하고이 방법으로 사용하기 위해 가져 오거나 모든 파일이 동일한 파일에 있어야합니까? – alyms108

관련 문제