source: trunk/game/scripts/hud.py @ 268

Revision 268, 18.2 KB checked in by b0rland_parpg, 10 years ago (diff)

Ticket #77:

  • Hud class now gets the list of supported fullscreen resolutions from SDL
  • Hud elements placement is made more or less universal
  • 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
20from scripts.parpgfilebrowser import PARPGFileBrowser
21from scripts.context_menu import ContextMenu
22import weakref
23
24class Hud(object):
25    """Main Hud class"""
26    def __init__(self, engine, world, settings):
27        """Initialise the instance.
28           @type engine: fife.Engine
29           @param engine: An instance of the fife engine
30           @type settings: settings.Setting
31           @param settings: The settings data
32           @return: None"""
33        pychan.init(engine, debug = True)
34
35        # TODO: perhaps this should not be hard-coded here
36        self.hud = pychan.loadXML("gui/hud.xml")
37        self.engine = engine
38        self.settings = settings
39        self.world = weakref.proxy(world)
40        self.actionsBox = self.hud.findChild(name="actionsBox")
41        self.actionsText = []
42        self.menu_displayed = False
43        self.initializeHud()
44        self.initializeMainMenu()
45        self.initializeContextMenu()
46        self.initializeOptionsMenu()
47        self.initializeHelpMenu()
48        self.initializeEvents()
49
50    def initializeHud(self):
51        """Initialize and show the main HUD
52           @return: None"""
53        self.events_to_map = {"menuButton":self.displayMenu,}
54        self.hud.mapEvents(self.events_to_map) 
55        # set HUD size accoriding to screen size
56        screen_width = int(self.settings.readSetting('ScreenWidth'))
57        self.hud.findChild(name="mainHudWindow").size = (screen_width, 65)
58        self.hud.findChild(name="inventoryButton").position = (screen_width-59, 7)
59        # add ready slots
60        ready1 = self.hud.findChild(name='hudReady1')
61        ready2 = self.hud.findChild(name='hudReady2')
62        ready3 = self.hud.findChild(name='hudReady3')
63        ready4 = self.hud.findChild(name='hudReady4')
64        actions_scroll_area = self.hud.findChild(name='actionsScrollArea')
65        if (screen_width <=800) :
66            gap = 0
67        else :
68            gap = 40
69        # annoying code that is both essential and boring to enter
70        ready1.position = (160+gap, 7)
71        ready2.position = (220+gap, 7)
72        ready3.position = (screen_width-180-gap, 7)
73        ready4.position = (screen_width-120-gap, 7)
74        actions_scroll_area.position = (280+gap, 5)
75        actions_width = screen_width - 470 - 2*gap
76
77        # and finally add an actions box
78        self.hud.findChild(name="actionsBox").min_size = (actions_width, 0)
79        actions_scroll_area.min_size = (actions_width, 55)
80        actions_scroll_area.max_size = (actions_width, 55)
81        # now it should be OK to display it all
82        self.hud.show()
83
84    def refreshActionsBox(self):
85        """Refresh the actions box so that it displays the contents of
86           self.actionsText
87           @return: None"""
88        self.actionsBox.items = self.actionsText
89
90    def addAction(self, action):
91        """Add an action to the actions box.
92           @type action: string
93           @param action: The text that you want to display in the actions box
94           @return: None"""
95        self.actionsText.insert(0, action)
96        self.refreshActionsBox()
97
98    def showHUD(self):
99        """Show the HUD.
100           @return: None"""
101        self.hud.show()
102
103    def hideHUD(self):
104        """Hide the HUD.
105           @return: None"""
106        self.hud.hide()
107
108    def initializeContextMenu(self):
109        """Initialize the Context Menu
110           @return: None"""
111        self.context_menu = ContextMenu (self.engine, [], (0,0))
112        self.context_menu.hide()
113
114    def showContextMenu(self, data, pos):
115        """Display the Context Menu with data at pos
116           @type data: list
117           @param data: data to pass to context menu
118           @type pos: tuple
119           @param pos: tuple of x and y coordinates
120           @return: None"""
121        self.context_menu = ContextMenu(self.engine, data, pos)
122
123    def initializeMainMenu(self):
124        """Initalize the main menu.
125           @return: None"""
126        self.main_menu = pychan.loadXML("gui/hud_main_menu.xml")
127        self.menu_events = {"resumeButton":self.hideMenu, 
128                            "optionsButton":self.displayOptions,
129                            "helpButton":self.displayHelp}
130        self.main_menu.mapEvents(self.menu_events)
131
132    def displayMenu(self):
133        """Displays the main in-game menu.
134           @return: None"""
135        if (self.menu_displayed == False):
136            self.main_menu.show()
137            self.menu_displayed = True
138        elif (self.menu_displayed == True):
139            self.hideMenu()
140
141    def hideMenu(self):
142        """Hides the main in-game menu.
143           @return: None"""
144        self.main_menu.hide()
145        self.menu_displayed = False
146
147    def initializeHelpMenu(self):
148        """Initialize the help menu
149           @return: None"""
150        self.help_dialog = pychan.loadXML("gui/help.xml")
151        help_events = {"closeButton":self.help_dialog.hide}
152        self.help_dialog.mapEvents(help_events)
153        main_help_text = u"Welcome to Post-Apocalyptic RPG or PARPG![br][br]"\
154        "This game is still in development, so please expect for there to be bugs"\
155        " and[br]feel free to tell us about them at http://www.forums.parpg.net.[br]"\
156        "This game uses a \"Point 'N' Click\" interface, which means that to move around,[br]"\
157        "just click where you would like to go and your character will move there.[br]"\
158        "PARPG also utilizes a context menu. To access this, just right click "\
159        "anywhere[br]on the screen and a menu will come up. This menu will change"\
160        " depending on[br]what you have clicked on, hence it's name \"context menu\".[br][br]"
161       
162        k_text = u" Keybindings" 
163        k_text+="[br] A : Add a test action to the actions display"
164        k_text+="[br] I : Toggle the inventory screen"
165        k_text+="[br] F5 : Take a screenshot"
166        k_text+="[br]      (saves to <parpg>/screenshots/)"
167        k_text+="[br] Q : Quit the game"
168        self.help_dialog.distributeInitialData({
169                "MainHelpText":main_help_text,
170                "KeybindText":k_text
171                })
172
173    def displayHelp(self):
174        """Display the help screen.
175           @return: None"""
176        self.help_dialog.show()
177
178    def initializeOptionsMenu(self):
179        """Initalize the options menu.
180           @return: None"""
181        self.options_menu = pychan.loadXML("gui/hud_options.xml")
182        self.options_events = {"applyButton":self.applyOptions,
183                               "closeButton":self.options_menu.hide,
184                               "defaultsButton":self.setToDefaults,
185                               "InitialVolumeSlider":self.updateVolumeText}
186       
187        settings = self.engine.getSettings()
188        current_fullscreen = settings.isFullScreen()
189        settings.setFullScreen(True)
190        availableResolutions = settings.getPossibleResolutions()
191        self.Resolutions = [str(x[0])+'x'+str(x[1]) for x in availableResolutions];
192        settings.setFullScreen(current_fullscreen)
193        self.RenderBackends = ['OpenGL', 'SDL']
194        self.renderNumber = 0
195        if (str(self.settings.readSetting('RenderBackend')) == "SDL"):
196            self.renderNumber = 1
197        initialVolume = float(self.settings.readSetting('InitialVolume'))
198        initialVolumeText = str('Initial Volume: %.0f%s' %
199                                (int(initialVolume*10), "%"))
200        self.options_menu.distributeInitialData({
201                'ResolutionBox': self.Resolutions,
202                'RenderBox': self.RenderBackends,
203                'InitialVolumeLabel' : initialVolumeText
204                })
205
206        sFullscreen = self.settings.readSetting(name="FullScreen")
207        sSounds = self.settings.readSetting(name="PlaySounds")
208        sRender = self.renderNumber
209        sVolume = initialVolume
210
211        screen_width = self.settings.readSetting(name="ScreenWidth")
212        screen_height = self.settings.readSetting(name="ScreenHeight")
213        indexRes = str(screen_width + 'x' + screen_height)
214        try:
215            sResolution = self.Resolutions.index(indexRes)
216            resolutionInList = True
217        except:
218            resolutionInList = False
219
220        dataToDistribute = {
221                'FullscreenBox':int(sFullscreen), 
222                'SoundsBox':int(sSounds),
223                'RenderBox': sRender,
224                'InitialVolumeSlider':sVolume
225                }
226
227        if (resolutionInList == True):
228            dataToDistribute['ResolutionBox'] = sResolution
229
230        self.options_menu.distributeData(dataToDistribute)
231
232        self.options_menu.mapEvents(self.options_events)
233
234    def saveGame(self):
235        """ Called when the user wants to save the game.
236            @return: None"""
237        save_browser = PARPGFileBrowser(self.engine,
238                                   self.world.saveFunction,
239                                   savefile=True,
240                                   guixmlpath="gui/savebrowser.xml",
241                                   extensions = ('.dat'))
242        save_browser.showBrowser()
243           
244    def newGame(self):
245        """Called when user request to start a new game.
246           @return: None"""
247        print 'new game'
248
249    def loadGame(self):
250        """ Called when the user wants to load a game.
251            @return: None"""
252        load_browser = PARPGFileBrowser(self.engine,
253                                   self.world.loadFunction,
254                                   savefile=False,
255                                   guixmlpath='gui/loadbrowser.xml',
256                                   extensions=('.dat'))
257        load_browser.showBrowser()
258
259    def quitGame(self):
260        """Called when user requests to quit game.
261           @return: None"""
262
263        window = pychan.widgets.Window(title=unicode("Quit?"))
264
265        hbox = pychan.widgets.HBox()
266        are_you_sure = "Are you sure you want to quit?"
267        label = pychan.widgets.Label(text=unicode(are_you_sure))
268        yes_button = pychan.widgets.Button(name="yes_button", 
269                                           text=unicode("Yes"))
270        no_button = pychan.widgets.Button(name="no_button",
271                                          text=unicode("No"))
272
273        window.addChild(label)
274        hbox.addChild(yes_button)
275        hbox.addChild(no_button)
276        window.addChild(hbox)
277
278        events_to_map = {"yes_button":self.world.quitFunction,
279                         "no_button":window.hide}
280       
281        window.mapEvents(events_to_map)
282        window.show()
283
284    def toggleInventoryButton(self):
285        """Manually toggles the inventory button.
286           @return: None"""
287        button = self.hud.findChild(name="inventoryButton")
288        if(button.toggled == 0):
289            button.toggled = 1
290        else:
291            button.toggled = 0
292
293    def displayInventory(self, *args, **kwargs):
294        """Display's the inventory screen
295           @return: None"""
296        self.world.inventory.displayInventory(*args, **kwargs)
297
298    def refreshReadyImages(self):
299        """Make the Ready slot images on the HUD be the same as those
300           on the inventory
301           @return: None"""
302        self.setImages(self.hud.findChild(name="hudReady1"),
303                       self.world.inventory.inventory.findChild(name="Ready1").up_image)
304        self.setImages(self.hud.findChild(name="hudReady2"),
305                       self.world.inventory.inventory.findChild(name="Ready2").up_image)
306        self.setImages(self.hud.findChild(name="hudReady3"),
307                       self.world.inventory.inventory.findChild(name="Ready3").up_image)
308        self.setImages(self.hud.findChild(name="hudReady4"),
309                       self.world.inventory.inventory.findChild(name="Ready4").up_image)
310
311    def setImages(self, widget, image):
312        """Set the up, down, and hover images of an Imagebutton.
313           @type widget: pychan.widget
314           @param widget: widget to set
315           @type image: string
316           @param image: image to use
317           @return: None"""
318        widget.up_image = image
319        widget.down_image = image
320        widget.hover_image = image
321
322    def initializeEvents(self):
323        """Intialize Hud events
324           @return: None"""
325        events_to_map = {}
326        events_to_map["inventoryButton"] = cbwa(self.displayInventory, True)
327        events_to_map["saveButton"] = self.saveGame
328        events_to_map["loadButton"] = self.loadGame
329
330        hud_ready_buttons = ["hudReady1", "hudReady2", "hudReady3", "hudReady4"]
331
332        for item in hud_ready_buttons:
333            events_to_map[item] = cbwa(self.readyAction, item)
334
335        self.hud.mapEvents(events_to_map)
336
337        menu_events = {}
338        menu_events["newButton"] = self.newGame
339        menu_events["quitButton"] = self.quitGame
340        menu_events["saveButton"] = self.saveGame
341        menu_events["loadButton"] = self.loadGame
342        self.main_menu.mapEvents(menu_events)
343
344    def updateVolumeText(self):
345        """
346        Update the initial volume label to reflect the value of the slider
347        """
348        volume = float(self.options_menu.collectData("InitialVolumeSlider"))
349        volume_label = self.options_menu.findChild(name="InitialVolumeLabel")
350        volume_label.text = unicode("Initial Volume: %.0f%s" %
351                                    (int(volume*10), "%"))
352
353    def requireRestartDialog(self):
354        """Show a dialog asking the user to restart PARPG in order for their
355           changes to take effect.
356           @return: None"""
357        require_restart_dialog = pychan.loadXML('gui/hud_require_restart.xml')
358        require_restart_dialog.mapEvents({'okButton':require_restart_dialog.hide})
359        require_restart_dialog.show()
360
361    def applyOptions(self):
362        """Apply the current options.
363           @return: None"""
364        # At first no restart is required
365        self.requireRestart = False
366
367        # get the current values of each setting from the options menu
368        enable_fullscreen = self.options_menu.collectData('FullscreenBox')
369        enable_sound = self.options_menu.collectData('SoundsBox')
370        screen_resolution = self.options_menu.collectData('ResolutionBox')
371        partition = self.Resolutions[screen_resolution].partition('x')
372        screen_width = partition[0]
373        screen_height = partition[2]
374        render_backend = self.options_menu.collectData('RenderBox')
375        initial_volume = self.options_menu.collectData('InitialVolumeSlider')
376        initial_volume = "%.1f" % initial_volume
377
378        # get the options that are being used right now from settings.xml
379        sFullscreen = self.settings.readSetting('FullScreen')
380        sSound = self.settings.readSetting('PlaySounds')
381        sRender = self.settings.readSetting('RenderBackend')
382        sVolume = self.settings.readSetting('InitialVolume')
383
384        sScreenHeight = self.settings.readSetting('ScreenHeight')
385        sScreenWidth = self.settings.readSetting('ScreenWidth')
386        sResolution = sScreenWidth + 'x' + sScreenHeight
387
388        # On each:
389        # - Check to see whether the option within the xml matches the
390        #   option within the options menu
391        # - If they do not match, set the option within the xml to
392        #   to be what is within the options menu
393        # - Require a restart
394
395        if (int(enable_fullscreen) != int(sFullscreen)):
396            self.setOption('FullScreen', int(enable_fullscreen))
397            self.requireRestart = True
398           
399        if (int(enable_sound) != int(sSound)):
400            self.setOption('PlaySounds', int(enable_sound))
401            self.requireRestart = True
402
403        if (screen_resolution != sResolution):
404            self.setOption('ScreenWidth', int(screen_width))
405            self.setOption('ScreenHeight', int(screen_height))
406            self.requireRestart = True
407
408        # Convert the number from the list of render backends to
409        # the string that FIFE wants for its settings.xml
410        if (render_backend == 0):
411            render_backend = 'OpenGL'
412        else:
413            render_backend = 'SDL'
414
415        if (render_backend != str(sRender)):
416            self.setOption('RenderBackend', render_backend)
417            self.requireRestart = True
418
419        if (initial_volume != float(sVolume)):
420            self.setOption('InitialVolume', initial_volume)
421            self.requireRestart = True
422       
423        # Write all the settings to settings.xml
424        self.settings.tree.write('settings.xml')
425       
426        # If the changes require a restart, popup the dialog telling
427        # the user to do so
428        if (self.requireRestart):
429            self.requireRestartDialog()
430        # Once we are done, we close the options menu
431        self.options_menu.hide()
432
433    def setOption(self, name, value):
434        """Set an option within the xml.
435           @type name: string
436           @param name: The name of the option within the xml
437           @type value: any
438           @param value: The value that the option 'name' should be set to
439           @return: None"""
440        element = self.settings.root_element.find(name)
441        if(element != None):
442            if(value != element.text):
443                element.text = str(value)
444        else:
445            print 'Setting,', name, 'does not exist!'
446
447    def setToDefaults(self):
448        """Reset all the options to the options in settings-dist.xml.
449           @return: None"""
450        shutil.copyfile('settings-dist.xml', 'settings.xml')
451        self.requireRestartDialog()
452        self.options_menu.hide()
453
454    def displayOptions(self):
455        """Display the options menu.
456           @return: None"""
457        self.options_menu.show()
458   
459    def readyAction(self, ready_button):
460        """ Called when the user selects a ready button from the HUD """
461        text = "Used the item from %s" % ready_button
462        self.addAction(text)
463       
Note: See TracBrowser for help on using the repository browser.