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

Revision 149, 12.5 KB checked in by bretzel_parpg, 10 years ago (diff)

Added a slider in the options menu for the initial volume setting

  • 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                              "loadButton":self.loadGame}
48        self.hud.mapEvents(self.events_to_map) 
49        # set HUD size accoriding to screen size
50        screen_width = int(self.settings.readSetting('ScreenWidth'))
51        self.hud.findChild(name="mainHudWindow").size = (screen_width, 65)
52        self.hud.findChild(name="inventoryButton").position = (screen_width-59, 7)
53        # add ready slots
54        ready1 = self.hud.findChild(name='hudReady1')
55        ready2 = self.hud.findChild(name='hudReady2')
56        ready3 = self.hud.findChild(name='hudReady3')
57        ready4 = self.hud.findChild(name='hudReady4')
58        actions_scroll_area = self.hud.findChild(name='actionsScrollArea')
59        # annoying code that is both essential and boring to enter
60        if (screen_width == 1440):
61            ready1.position = (screen_width-1235, 7)
62            ready2.position = (screen_width-1175, 7)
63            ready3.position = (screen_width-215, 7)
64            ready4.position = (screen_width-155, 7)
65            actions_scroll_area.position = (325, 5)
66            actions_width = screen_width - 550
67        elif (screen_width == 1280):
68            ready1.position = (screen_width-1075, 7)
69            ready2.position = (screen_width-1015, 7)
70            ready3.position = (screen_width-215, 7)
71            ready4.position = (screen_width-155, 7)
72            actions_scroll_area.position = (325, 5)
73            actions_width = screen_width - 550
74        elif (screen_width == 1024):
75            ready1.position = (screen_width-820, 7)
76            ready2.position = (screen_width-760, 7)
77            ready3.position = (screen_width-215, 7)
78            ready4.position = (screen_width-155, 7)
79            actions_scroll_area.position = (325, 5)
80            actions_width = screen_width - 550
81        elif (screen_width == 800):
82            ready1.position = (screen_width-640, 7)
83            ready2.position = (screen_width-580, 7)
84            ready3.position = (screen_width-185, 7)
85            ready4.position = (screen_width-125, 7)
86            actions_scroll_area.position = (280, 5)
87            actions_width = screen_width - 475
88        else:
89            ready1.position = (screen_width-475, 7)
90            ready2.position = (screen_width-420, 7)
91            ready3.position = (screen_width-175, 7)
92            ready4.position = (screen_width-120, 7)
93            actions_scroll_area.position = (280, 5)
94            actions_width = screen_width - 465
95        # and finally add an actions box
96        self.hud.findChild(name="actionsBox").min_size = (actions_width, 0)
97        actions_scroll_area.min_size = (actions_width, 55)
98        actions_scroll_area.max_size = (actions_width, 55)
99        # now it should be OK to display it all
100        self.hud.show()
101
102    def refreshActionsBox(self):
103        """Refresh the actions box so that it displays the contents of
104           self.actionsText
105           @return: None"""
106        self.actionsBox.items = self.actionsText
107
108    def addAction(self, action):
109        """Add an action to the actions box.
110           @type action: ???
111           @param action: ???
112           @return: None"""
113        self.actionsText.insert(0, action)
114        self.refreshActionsBox()
115
116    def showHUD(self):
117        """Show the HUD.
118           @return: None"""
119        self.hud.show()
120
121    def hideHUD(self):
122        """Hide the HUD.
123           @return: None"""
124        self.hud.hide()
125       
126    def initializeMainMenu(self):
127        """Initalize the main menu.
128           @return: None"""
129        self.main_menu = pychan.loadXML("gui/hud_main_menu.xml")
130        self.menu_events = {"resumeButton":self.hideMenu,
131                            "loadButton":self.loadGame, 
132                            "optionsButton":self.displayOptions,
133                            "helpButton":self.displayHelp}
134        self.main_menu.mapEvents(self.menu_events)
135
136    def displayMenu(self):
137        """Displays the main in-game menu.
138           @return: None"""
139        if (self.menu_displayed == False):
140            self.main_menu.show()
141            self.menu_displayed = True
142        elif (self.menu_displayed == True):
143            self.hideMenu()
144
145    def hideMenu(self):
146        """Hides the main in-game menu.
147           @return: None"""
148        self.main_menu.hide()
149        self.menu_displayed = False
150
151    def initializeHelpMenu(self):
152        """Initialize the help menu
153           @return: None"""
154        self.help_dialog = pychan.loadXML("gui/help.xml")
155        help_events = {"closeButton":self.help_dialog.hide}
156        self.help_dialog.mapEvents(help_events)
157        main_help_text = "Put help text here"
158        k_text = " A : Add a test action to the actions display"
159        k_text+="[br] I : Toggle the inventory screen"
160        k_text+="[br]F5 : Take a screenshot"
161        k_text+="[br]     (saves to <parpg>/screenshots/)"
162        k_text+="[br] M : Toggle music on/off"
163        k_text+="[br] Q : Quit the game"
164        self.help_dialog.distributeInitialData({
165                "MainHelpText":main_help_text,
166                "KeybindText":k_text
167                })
168
169    def displayHelp(self):
170        """Display the help screen.
171           @return: None"""
172        self.help_dialog.show()
173
174    def initializeOptionsMenu(self):
175        """Initalize the options menu.
176           @return: None"""
177        self.options_menu = pychan.loadXML("gui/hud_options.xml")
178        self.options_events = {"applyButton":self.applyOptions,
179                               "closeButton":self.options_menu.hide,
180                               "defaultsButton":self.setToDefaults,
181                               "InitialVolumeSlider":self.updateVolumeText}
182        self.Resolutions = ['640x480', '800x600',
183                            '1024x768', '1280x1024', '1440x900']
184        self.RenderBackends = ['OpenGL', 'SDL']
185        self.renderNumber = 0
186        if (str(self.settings.readSetting('RenderBackend')) == "SDL"):
187            self.renderNumber = 1
188        initialVolume = float(self.settings.readSetting('InitialVolume'))
189        initialVolumeText = str('Initial Volume: %.0f%s' %
190                                (int(initialVolume*10), "%"))
191        self.options_menu.distributeInitialData({
192                'ResolutionBox': self.Resolutions,
193                'RenderBox': self.RenderBackends,
194                'InitialVolumeLabel' : initialVolumeText
195                })
196        # TODO: fix bad line length here
197        self.options_menu.distributeData({
198                'FullscreenBox':int(self.settings.readSetting(name="FullScreen")), 
199                'SoundsBox':int(self.settings.readSetting(name="PlaySounds")),
200                'ResolutionBox':self.Resolutions.index(str(self.settings.readSetting("ScreenWidth")) + 'x' + str(self.settings.readSetting("ScreenHeight"))),
201                'RenderBox': self.renderNumber,
202                'InitialVolumeSlider':initialVolume
203                })
204        self.options_menu.mapEvents(self.options_events)
205
206    def updateVolumeText(self):
207        """
208        Update the initial volume label to reflect the value of the slider
209        """
210        volume = float(self.options_menu.collectData("InitialVolumeSlider"))
211        volume_label = self.options_menu.findChild(name="InitialVolumeLabel")
212        volume_label.text = unicode("Initial Volume: %.0f%s" %
213                                    (int(volume*10), "%"))
214
215    def requireRestartDialog(self):
216        """Show a dialog asking the user to restart PARPG in order for their
217           changes to take effect.
218           @return: None"""
219        require_restart_dialog = pychan.loadXML('gui/hud_require_restart.xml')
220        require_restart_dialog.mapEvents({'okButton':require_restart_dialog.hide})
221        require_restart_dialog.show()
222
223    def applyOptions(self):
224        """Apply the current options.
225           @return: None"""
226        # TODO: line lengths here are horrible
227        # TODO: add comments
228        self.requireRestart = False
229        enable_fullscreen, enable_sound, screen_resolution, render_backend, initial_volume = self.options_menu.collectData('FullscreenBox', 'SoundsBox', 'ResolutionBox', 'RenderBox', 'InitialVolumeSlider')
230        initial_volume = "%.1f" % initial_volume
231
232        if (int(enable_fullscreen) != int(self.settings.readSetting('FullScreen'))):
233            self.setOption('FullScreen', int(enable_fullscreen))
234            self.requireRestart = True
235           
236        if (int(enable_sound) != int(self.settings.readSetting('PlaySounds'))):
237            self.setOption('PlaySounds', int(enable_sound))
238            self.requireRestart = True
239
240        if (screen_resolution != self.Resolutions.index(str(self.settings.readSetting("ScreenWidth")) + 'x' + str(self.settings.readSetting("ScreenHeight")))):
241            self.setOption('ScreenWidth', int(self.Resolutions[screen_resolution].partition('x')[0]))
242            self.setOption('ScreenHeight', int(self.Resolutions[screen_resolution].partition('x')[2]))
243            self.requireRestart = True
244       
245        if (render_backend == 0):
246            render_backend = 'OpenGL'
247        else:
248            render_backend = 'SDL'
249
250        if (render_backend != str(self.settings.readSetting("RenderBackend"))):
251            self.setOption('RenderBackend', render_backend)
252            self.requireRestart = True
253
254        if (initial_volume != float(self.settings.readSetting("InitialVolume"))):
255            self.setOption('InitialVolume', initial_volume)
256            self.requireRestart = True
257
258        self.settings.tree.write('settings.xml')
259        if (self.requireRestart):
260            self.requireRestartDialog()
261        self.options_menu.hide()
262
263    def setOption(self, name, value):
264        """Set an option within the xml.
265           @type name: ???
266           @param name: The name?
267           @type value: ???
268           @param value: The value?
269           @return: None"""
270        element = self.settings.root_element.find(name)
271        if(element != None):
272            if(value != element.text):
273                element.text = str(value)
274        else:
275            print 'Setting,', name, 'does not exist!'
276
277    def setToDefaults(self):
278        """Reset all the options to the options in settings-dist.xml.
279           @return: None"""
280        shutil.copyfile('settings-dist.xml', 'settings.xml')
281        self.requireRestartDialog()
282        self.options_menu.hide()
283
284    def displayOptions(self):
285        """Display the options menu.
286           @return: None"""
287        self.options_menu.show()
288   
289    def saveGame(self):
290        """Open the save game dialog.
291           @return: None"""
292        print "Save not yet enabled"
293
294    def loadGame(self):
295        """Open the load game dialog.
296           @return: None"""
297        print "Load not yet enabled"
298       
299    def toggleInventory(self):
300        """Manually toggles the inventory button.
301           @return: None"""
302        button = self.hud.findChild(name="inventoryButton")
303        if(button.toggled == 0):
304            button.toggled = 1
305        else:
306            button.toggled = 0
307
Note: See TracBrowser for help on using the repository browser.