source: branches/active/character_customization/game/parpg/console.py @ 794

Revision 774, 7.6 KB checked in by aspidites, 9 years ago (diff)

Patch by Aspidites

  • removed shebang from all python files except launcher scripts
  • added shebang to pychan_designer
  • Property svn:eol-style set to native
Line 
1#   This program is free software: you can redistribute it and/or modify
2#   it under the terms of the GNU General Public License as published by
3#   the Free Software Foundation, either version 3 of the License, or
4#   (at your option) any later version.
5
6#   This program is distributed in the hope that it will be useful,
7#   but WITHOUT ANY WARRANTY; without even the implied warranty of
8#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9#   GNU General Public License for more details.
10
11#   You should have received a copy of the GNU General Public License
12#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
13
14import re
15import os
16import sys
17from StringIO import StringIO
18import code
19
20class Console:
21    def __init__(self, app_listener):
22        """
23        @type appListener: ApplicationListener
24        @param appListener: ApplicationListener object providing a link with
25        the Controller, the view and the GameModel"""
26        exit_help   = "Terminate application"
27        grid_help   = "Toggle grid display"
28        run_help    = "Toggle player run/walk"
29        help_help   = "Show this help string"
30        load_help   = "Usage: load directory file"
31        python_help = "Run some python code"
32        quit_help   = "Terminate application"
33        save_help   = "Usage: save directory file"
34        pause_help  = "Pause/Unpause the game"
35
36        self.commands = [
37            {"cmd":"exit"  ,"callback":self.handleQuit  ,"help": exit_help},
38            {"cmd":"grid"  ,"callback":self.handleGrid  ,"help": grid_help},
39            {"cmd":"help"  ,"callback":self.handleHelp  ,"help": help_help},
40            {"cmd":"load"  ,"callback":self.handleLoad  ,"help": load_help},
41            {"cmd":"pause" ,"callback":self.handlePause ,"help": pause_help},
42            {"cmd":"python","callback":self.handlePython,"help": python_help},
43            {"cmd":"run"   ,"callback":self.handleRun   ,"help": run_help},
44            {"cmd":"save"  ,"callback":self.handleSave  ,"help": save_help},
45            {"cmd":"quit"  ,"callback":self.handleQuit  ,"help": quit_help},
46        ]
47        self.app_listener = app_listener
48        self.view = self.app_listener.view
49        self.model = self.app_listener.model
50        self.game_state = self.app_listener.view.model.game_state
51        self.console_locals = {"__name__":"__paprg_console__",\
52                               "__doc__": None,\
53                               "app_listener":self.app_listener,\
54                               "model":self.app_listener.model,\
55                               "view":self.app_listener.view,\
56                               "engine":self.app_listener.engine}
57
58        self.console = code.InteractiveConsole(self.console_locals)
59
60    def handleQuit(self, command):
61        """Implements the quit console command
62           @type command: string
63           @param command: The command to run
64           @return: The resultstring"""
65        self.app_listener.quitGame()
66        return "Terminating ..."
67
68    def handlePause(self, command):
69        """Implements the pause console command
70           @type command: string
71           @param command: The command to run
72           @return: The resultstring"""
73        self.model.togglePause()
74        return "Game (un)paused"
75
76    def handleGrid(self, command):
77        """Implements the grid console command
78           @type command: string
79           @param command: The command to run
80           @return: The resultstring"""
81        self.app_listener.view.active_map.toggleRenderer('GridRenderer')
82        return "Grid toggled"
83
84    def handleRun(self, command):
85        """Toggles run/walk mode of the PC player
86           @type command: string
87           @param command: The command to run.
88           @return: The response"""
89        if self.app_listener.model.pc_run == 1:
90            self.app_listener.model.pc_run = 0
91            return "PC is now walking"
92        else:
93            self.app_listener.model.pc_run = 1
94            return "PC is now running"
95
96    def handleHelp(self, command):
97        """Implements the help console command
98           @type command: string
99           @param command: The command to run
100           @return: The resultstring"""
101        res = ""
102        for cmd in self.commands:
103            res += "%10s: %s\n" % (cmd["cmd"], cmd["help"])
104        return res
105
106    def handlePython(self,command):
107        user_code = command[7:len(command)]
108
109        codeOut = StringIO()
110
111        #make stdout and stderr write to our file, not the terminal
112        sys.stdout = codeOut
113        sys.stderr = codeOut
114
115        #Workaround it not being possible to enter a blank line in the console
116        if user_code == " ":
117            user_code = ""
118
119        #Process the code
120        self.console.push(user_code)
121        if len(self.console.buffer) == 0:
122            output = codeOut.getvalue()
123        else:
124            output =  "..."
125
126
127        #restore stdout and stderr
128        sys.stdout = sys.__stdout__
129        sys.stderr = sys.__stderr__
130
131        temp_output = output
132        output = ""
133        counter = 0
134
135        #Make the output fit in the console screen
136        for char in temp_output:
137            counter += 1
138            if char == "\n":
139                counter = 0
140            elif counter == 110:
141                output += "\n"
142                counter = 0
143            output += char
144
145        return output
146
147    def handleLoad(self, command):
148        """Implements the load console command
149           @type command: string
150           @param command: The command to run
151           @return: The resultstring"""
152        result = None
153        load_regex = re.compile('^load')
154        l_matches = load_regex.match(command.lower())
155        if (l_matches is not None):
156            end_load = l_matches.end()
157            try:
158                l_args = command.lower()[end_load + 1:].strip()
159                l_path, l_filename = l_args.split(' ')
160                self.app_listener.model.load_save = True
161                self.app_listener.model.savegame = os.path.join(l_path, l_filename)
162                result = "Load triggered"
163
164            except Exception, l_error:
165                self.app_listener.engine.getGuiManager().getConsole().println('Error: ' + str(l_error))
166                result="Failed to load file"
167
168        return result
169
170    def handleSave(self, command):
171        """Implements the save console command
172           @type command: string
173           @param command: The command to run
174           @return: The resultstring"""
175        save_regex = re.compile('^save')
176        s_matches = save_regex.match(command.lower())
177        if (s_matches != None):
178            end_save = s_matches.end()
179            try:
180                s_args = command.lower()[end_save+1:].strip()
181                s_path, s_filename = s_args.split(' ')
182                self.app_listener.model.save(s_path, s_filename)
183                result = "Saved to file: " + s_path + s_filename
184
185            except Exception, s_error:
186                self.app_listener.engine.getGuiManager().getConsole(). \
187                    println('Error: ' + str(s_error))
188                result = "Failed to save file"
189        return result
190
191    def handleConsoleCommand(self, command):
192        """Implements the console logic
193           @type command: string
194           @param command: The command to run
195           @return: The response string """
196        result = None       
197        for cmd in self.commands:
198            regex = re.compile('^' + cmd["cmd"])
199            if regex.match(command.lower()):
200                result=cmd["callback"](command)
201
202        if result is None:
203            result = self.handlePython("python " + command) 
204        return result
Note: See TracBrowser for help on using the repository browser.