source: trunk/PARPG/scripts/hud.py @ 159

Revision 159, 13.7 KB checked in by bretzel_parpg, 10 years ago (diff)

Fixed some resolution/options menu errors. Fixed some terrible line
lengths. Added some comments.

  • Property svn:eol-style set to native
Line 
1#!/usr/bin/python
2
3#   This file is part of PARPG.
4
5#   PARPG is free software: you can redistribute it and/or modify
6#   it under the terms of the GNU General Public License as published by
7#   the Free Software Foundation, either version 3 of the License, or
8#   (at your option) any later version.
9
10#   PARPG is distributed in the hope that it will be useful,
11#   but WITHOUT ANY WARRANTY; without even the implied warranty of
12#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13#   GNU General Public License for more details.
14
15#   You should have received a copy of the GNU General Public License
16#   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
17
18import shutil, fife, pychan
19from pychan.tools import callbackWithArguments as cbwa
20
21
22class Hud():
23    """Main Hud class"""
24    def __init__(self, engine, settings):
25        """Initialise the instance.
26           @type engine: fife.Engine
27           @param engine: An instance of the fife engine
28           @type settings: settings.Setting
29           @param settings: The settings data
30           @return: None"""
31        pychan.init(engine, debug = True)
32        # TODO: perhaps this should not be hard-coded here
33        self.hud = pychan.loadXML("gui/hud.xml")
34        self.settings = settings
35        self.actionsBox = self.hud.findChild(name="actionsBox")
36        self.actionsText = []
37        self.menu_displayed = False
38        self.initializeHud()
39        self.initializeMainMenu()
40        self.initializeOptionsMenu()
41        self.initializeHelpMenu()
42
43    def initializeHud(self):
44        """Initialize and show the main HUD
45           @return: None"""
46        self.events_to_map = {"menuButton":self.displayMenu,}
47        self.hud.mapEvents(self.events_to_map) 
48        # set HUD size accoriding to screen size
49        screen_width = int(self.settings.readSetting('ScreenWidth'))
50        self.hud.findChild(name="mainHudWindow").size = (screen_width, 65)
51        self.hud.findChild(name="inventoryButton").position = (screen_width-59, 7)
52        # add ready slots
53        ready1 = self.hud.findChild(name='hudReady1')
54        ready2 = self.hud.findChild(name='hudReady2')
55        ready3 = self.hud.findChild(name='hudReady3')
56        ready4 = self.hud.findChild(name='hudReady4')
57        actions_scroll_area = self.hud.findChild(name='actionsScrollArea')
58        # annoying code that is both essential and boring to enter
59        if (screen_width == 1440):
60            ready1.position = (screen_width-1235, 7)
61            ready2.position = (screen_width-1175, 7)
62            ready3.position = (screen_width-215, 7)
63            ready4.position = (screen_width-155, 7)
64            actions_scroll_area.position = (325, 5)
65            actions_width = screen_width - 550
66        elif (screen_width == 1280):
67            ready1.position = (screen_width-1075, 7)
68            ready2.position = (screen_width-1015, 7)
69            ready3.position = (screen_width-215, 7)
70            ready4.position = (screen_width-155, 7)
71            actions_scroll_area.position = (325, 5)
72            actions_width = screen_width - 550
73        elif (screen_width == 1024):
74            ready1.position = (screen_width-820, 7)
75            ready2.position = (screen_width-760, 7)
76            ready3.position = (screen_width-215, 7)
77            ready4.position = (screen_width-155, 7)
78            actions_scroll_area.position = (325, 5)
79            actions_width = screen_width - 550
80        elif (screen_width == 800):
81            ready1.position = (screen_width-640, 7)
82            ready2.position = (screen_width-580, 7)
83            ready3.position = (screen_width-185, 7)
84            ready4.position = (screen_width-125, 7)
85            actions_scroll_area.position = (280, 5)
86            actions_width = screen_width - 475
87        else:
88            ready1.position = (screen_width-475, 7)
89            ready2.position = (screen_width-420, 7)
90            ready3.position = (screen_width-175, 7)
91            ready4.position = (screen_width-120, 7)
92            actions_scroll_area.position = (280, 5)
93            actions_width = screen_width - 465
94        # and finally add an actions box
95        self.hud.findChild(name="actionsBox").min_size = (actions_width, 0)
96        actions_scroll_area.min_size = (actions_width, 55)
97        actions_scroll_area.max_size = (actions_width, 55)
98        # now it should be OK to display it all
99        self.hud.show()
100
101    def refreshActionsBox(self):
102        """Refresh the actions box so that it displays the contents of
103           self.actionsText
104           @return: None"""
105        self.actionsBox.items = self.actionsText
106
107    def addAction(self, action):
108        """Add an action to the actions box.
109           @type action: ???
110           @param action: ???
111           @return: None"""
112        self.actionsText.insert(0, action)
113        self.refreshActionsBox()
114
115    def showHUD(self):
116        """Show the HUD.
117           @return: None"""
118        self.hud.show()
119
120    def hideHUD(self):
121        """Hide the HUD.
122           @return: None"""
123        self.hud.hide()
124       
125    def initializeMainMenu(self):
126        """Initalize the main menu.
127           @return: None"""
128        self.main_menu = pychan.loadXML("gui/hud_main_menu.xml")
129        self.menu_events = {"resumeButton":self.hideMenu, 
130                            "optionsButton":self.displayOptions,
131                            "helpButton":self.displayHelp}
132        self.main_menu.mapEvents(self.menu_events)
133
134    def displayMenu(self):
135        """Displays the main in-game menu.
136           @return: None"""
137        if (self.menu_displayed == False):
138            self.main_menu.show()
139            self.menu_displayed = True
140        elif (self.menu_displayed == True):
141            self.hideMenu()
142
143    def hideMenu(self):
144        """Hides the main in-game menu.
145           @return: None"""
146        self.main_menu.hide()
147        self.menu_displayed = False
148
149    def initializeHelpMenu(self):
150        """Initialize the help menu
151           @return: None"""
152        self.help_dialog = pychan.loadXML("gui/help.xml")
153        help_events = {"closeButton":self.help_dialog.hide}
154        self.help_dialog.mapEvents(help_events)
155        main_help_text = "Put help text here"
156        k_text = " A : Add a test action to the actions display"
157        k_text+="[br] I : Toggle the inventory screen"
158        k_text+="[br]F5 : Take a screenshot"
159        k_text+="[br]     (saves to <parpg>/screenshots/)"
160        k_text+="[br] M : Toggle music on/off"
161        k_text+="[br] Q : Quit the game"
162        self.help_dialog.distributeInitialData({
163                "MainHelpText":main_help_text,
164                "KeybindText":k_text
165                })
166
167    def displayHelp(self):
168        """Display the help screen.
169           @return: None"""
170        self.help_dialog.show()
171
172    def initializeOptionsMenu(self):
173        """Initalize the options menu.
174           @return: None"""
175        self.options_menu = pychan.loadXML("gui/hud_options.xml")
176        self.options_events = {"applyButton":self.applyOptions,
177                               "closeButton":self.options_menu.hide,
178                               "defaultsButton":self.setToDefaults,
179                               "InitialVolumeSlider":self.updateVolumeText}
180
181        self.Resolutions = ['640x480', '800x600',
182                            '1024x768', '1280x1024', '1440x900']
183        self.RenderBackends = ['OpenGL', 'SDL']
184        self.renderNumber = 0
185        if (str(self.settings.readSetting('RenderBackend')) == "SDL"):
186            self.renderNumber = 1
187        initialVolume = float(self.settings.readSetting('InitialVolume'))
188        initialVolumeText = str('Initial Volume: %.0f%s' %
189                                (int(initialVolume*10), "%"))
190        self.options_menu.distributeInitialData({
191                'ResolutionBox': self.Resolutions,
192                'RenderBox': self.RenderBackends,
193                'InitialVolumeLabel' : initialVolumeText
194                })
195
196        sFullscreen = self.settings.readSetting(name="FullScreen")
197        sSounds = self.settings.readSetting(name="PlaySounds")
198        sRender = self.renderNumber
199        sVolume = initialVolume
200
201        screen_width = self.settings.readSetting(name="ScreenWidth")
202        screen_height = self.settings.readSetting(name="ScreenHeight")
203        indexRes = str(screen_width + 'x' + screen_height)
204        try:
205            sResolution = self.Resolutions.index(indexRes)
206            resolutionInList = True
207        except:
208            resolutionInList = False
209
210        dataToDistribute = {
211                'FullscreenBox':int(sFullscreen), 
212                'SoundsBox':int(sSounds),
213                'RenderBox': sRender,
214                'InitialVolumeSlider':sVolume
215                }
216
217        if (resolutionInList == True):
218            dataToDistribute['ResolutionBox'] = sResolution
219
220        self.options_menu.distributeData(dataToDistribute)
221
222        self.options_menu.mapEvents(self.options_events)
223
224    def updateVolumeText(self):
225        """
226        Update the initial volume label to reflect the value of the slider
227        """
228        volume = float(self.options_menu.collectData("InitialVolumeSlider"))
229        volume_label = self.options_menu.findChild(name="InitialVolumeLabel")
230        volume_label.text = unicode("Initial Volume: %.0f%s" %
231                                    (int(volume*10), "%"))
232
233    def requireRestartDialog(self):
234        """Show a dialog asking the user to restart PARPG in order for their
235           changes to take effect.
236           @return: None"""
237        require_restart_dialog = pychan.loadXML('gui/hud_require_restart.xml')
238        require_restart_dialog.mapEvents({'okButton':require_restart_dialog.hide})
239        require_restart_dialog.show()
240
241    def applyOptions(self):
242        """Apply the current options.
243           @return: None"""
244        # At first no restart is required
245        self.requireRestart = False
246
247        # get the current values of each setting from the options menu
248        enable_fullscreen = self.options_menu.collectData('FullscreenBox')
249        enable_sound = self.options_menu.collectData('SoundsBox')
250        screen_resolution = self.options_menu.collectData('ResolutionBox')
251        partition = self.Resolutions[screen_resolution].partition('x')
252        screen_width = partition[0]
253        screen_height = partition[2]
254        render_backend = self.options_menu.collectData('RenderBox')
255        initial_volume = self.options_menu.collectData('InitialVolumeSlider')
256        initial_volume = "%.1f" % initial_volume
257
258        # get the options that are being used right now from settings.xml
259        sFullscreen = self.settings.readSetting('FullScreen')
260        sSound = self.settings.readSetting('PlaySounds')
261        sRender = self.settings.readSetting('RenderBackend')
262        sVolume = self.settings.readSetting('InitialVolume')
263
264        sScreenHeight = self.settings.readSetting('ScreenHeight')
265        sScreenWidth = self.settings.readSetting('ScreenWidth')
266        sResolution = sScreenWidth + 'x' + sScreenHeight
267
268        # On each:
269        # - Check to see whether the option within the xml matches the
270        #   option within the options menu
271        # - If they do not match, set the option within the xml to
272        #   to be what is within the options menu
273        # - Require a restart
274
275        if (int(enable_fullscreen) != int(sFullscreen)):
276            self.setOption('FullScreen', int(enable_fullscreen))
277            self.requireRestart = True
278           
279        if (int(enable_sound) != int(sSound)):
280            self.setOption('PlaySounds', int(enable_sound))
281            self.requireRestart = True
282
283        if (screen_resolution != sResolution):
284            self.setOption('ScreenWidth', int(screen_width))
285            self.setOption('ScreenHeight', int(screen_height))
286            self.requireRestart = True
287
288        # Convert the number from the list of render backends to
289        # the string that FIFE wants for its settings.xml
290        if (render_backend == 0):
291            render_backend = 'OpenGL'
292        else:
293            render_backend = 'SDL'
294
295        if (render_backend != str(sRender)):
296            self.setOption('RenderBackend', render_backend)
297            self.requireRestart = True
298
299        if (initial_volume != float(sVolume)):
300            self.setOption('InitialVolume', initial_volume)
301            self.requireRestart = True
302       
303        # Write all the settings to settings.xml
304        self.settings.tree.write('settings.xml')
305       
306        # If the changes require a restart, popup the dialog telling
307        # the user to do so
308        if (self.requireRestart):
309            self.requireRestartDialog()
310        # Once we are done, we close the options menu
311        self.options_menu.hide()
312
313    def setOption(self, name, value):
314        """Set an option within the xml.
315           @type name: string
316           @param name: The name of the option within the xml
317           @type value: any
318           @param value: The value that the option 'name' should be set to
319           @return: None"""
320        element = self.settings.root_element.find(name)
321        if(element != None):
322            if(value != element.text):
323                element.text = str(value)
324        else:
325            print 'Setting,', name, 'does not exist!'
326
327    def setToDefaults(self):
328        """Reset all the options to the options in settings-dist.xml.
329           @return: None"""
330        shutil.copyfile('settings-dist.xml', 'settings.xml')
331        self.requireRestartDialog()
332        self.options_menu.hide()
333
334    def displayOptions(self):
335        """Display the options menu.
336           @return: None"""
337        self.options_menu.show()
338   
339    def toggleInventory(self):
340        """Manually toggles the inventory button.
341           @return: None"""
342        button = self.hud.findChild(name="inventoryButton")
343        if(button.toggled == 0):
344            button.toggled = 1
345        else:
346            button.toggled = 0
347
Note: See TracBrowser for help on using the repository browser.