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

Revision 348, 24.7 KB checked in by eliedebrauwer, 10 years ago (diff)

Ticket #97. Fix by eliedebrauwer, extended options menu with he possibility to have a windowed-resolution list and a fullscreen-resolution list and to switch between both using the dialogue checkbox. fixes[s:trac, t:97]

  • 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
19import fife
20import pychan
21import pychan.widgets as widgets
22from pychan.tools import callbackWithArguments as cbwa
23from scripts.filebrowser import FileBrowser
24from scripts.context_menu import ContextMenu
25from scripts import inventorygui
26from scripts.popups import ExaminePopup, ContainerGUI
27from scripts.dialoguegui import DialogueGUI
28
29class Hud(object):
30    """Main Hud class"""
31    def __init__(self, engine, settings, inv_model, callbacks):
32        """Initialise the instance.
33           @type engine: fife.Engine
34           @param engine: An instance of the fife engine
35           @type settings: settings.Setting
36           @param settings: The settings data
37           @type inv_model: dict
38           @type callbacks: dict
39           @param callbacks: a dict of callbacks
40               saveGame: called when the user clicks on Save
41               loadGame: called when the user clicks on Load
42               quitGame: called when the user clicks on Quit
43           @return: None"""
44        pychan.init(engine, debug = True)
45
46        # TODO: perhaps this should not be hard-coded here
47        self.hud = pychan.loadXML("gui/hud.xml")
48        self.engine = engine
49        self.settings = settings
50
51        inv_callbacks = {
52            'refreshReadyImages': self.refreshReadyImages,
53            'toggleInventoryButton': self.toggleInventoryButton,
54        }
55
56
57        self.inventory = inventorygui.InventoryGUI(self.engine, \
58                                                   inv_model, inv_callbacks)
59
60        self.refreshReadyImages()
61
62        self.save_game_callback = callbacks['saveGame']
63        self.load_game_callback = callbacks['loadGame']
64        self.quit_callback      = callbacks['quitGame']
65
66        self.box_container = None
67        self.examine_box = None
68
69        self.actions_box = self.hud.findChild(name="actionsBox")
70        self.actions_text = []
71        self.menu_displayed = False
72        self.initializeHud()
73        self.initializeMainMenu()
74        self.initializeContextMenu()
75        self.initializeOptionsMenu()
76        self.initializeHelpMenu()
77        self.initializeEvents()
78        self.initializeQuitDialog()
79
80    def initializeHud(self):
81        """Initialize and show the main HUD
82           @return: None"""
83        self.events_to_map = {"menuButton":self.displayMenu,}
84        self.hud.mapEvents(self.events_to_map) 
85        # set HUD size according to screen size
86        screen_width = int(self.settings.readSetting('ScreenWidth'))
87        self.hud.findChild(name="mainHudWindow").size = (screen_width, 65)
88        self.hud.findChild(name="inventoryButton").position = \
89                                                    (screen_width-59, 7)
90        # add ready slots
91        ready1 = self.hud.findChild(name='hudReady1')
92        ready2 = self.hud.findChild(name='hudReady2')
93        ready3 = self.hud.findChild(name='hudReady3')
94        ready4 = self.hud.findChild(name='hudReady4')
95        actions_scroll_area = self.hud.findChild(name='actionsScrollArea')
96        if (screen_width <=800) :
97            gap = 0
98        else :
99            gap = 40
100        # annoying code that is both essential and boring to enter
101        ready1.position = (160+gap, 7)
102        ready2.position = (220+gap, 7)
103        ready3.position = (screen_width-180-gap, 7)
104        ready4.position = (screen_width-120-gap, 7)
105        actions_scroll_area.position = (280+gap, 5)
106        actions_width = screen_width - 470 - 2*gap
107
108        # and finally add an actions box
109        self.hud.findChild(name="actionsBox").min_size = (actions_width, 0)
110        actions_scroll_area.min_size = (actions_width, 55)
111        actions_scroll_area.max_size = (actions_width, 55)
112        # now it should be OK to display it all
113        self.hud.show()
114
115    def refreshActionsBox(self):
116        """Refresh the actions box so that it displays the contents of
117           self.actions_text
118           @return: None"""
119        self.actions_box.items = self.actions_text
120
121    def addAction(self, action):
122        """Add an action to the actions box.
123           @type action: string
124           @param action: The text that you want to display in the actions box
125           @return: None"""
126        self.actions_text.insert(0, action)
127        self.refreshActionsBox()
128
129    def showHUD(self):
130        """Show the HUD.
131           @return: None"""
132        self.hud.show()
133
134    def hideHUD(self):
135        """Hide the HUD.
136           @return: None"""
137        self.hud.hide()
138
139    def initializeContextMenu(self):
140        """Initialize the Context Menu
141           @return: None"""
142        self.context_menu = ContextMenu (self.engine, [], (0,0))
143        self.context_menu.hide()
144
145    def showContextMenu(self, data, pos):
146        """Display the Context Menu with data at pos
147           @type data: list
148           @param data: data to pass to context menu
149           @type pos: tuple
150           @param pos: tuple of x and y coordinates
151           @return: None"""
152        self.context_menu = ContextMenu(self.engine, data, pos)
153
154    def hideContextMenu(self):
155        """Hides the context menu
156           @return: None"""
157        self.context_menu.hide()
158
159    def initializeMainMenu(self):
160        """Initalize the main menu.
161           @return: None"""
162        self.main_menu = pychan.loadXML("gui/hud_main_menu.xml")
163        self.menu_events = {"resumeButton":self.hideMenu, 
164                            "optionsButton":self.displayOptions,
165                            "helpButton":self.displayHelp}
166        self.main_menu.mapEvents(self.menu_events)
167
168    def displayMenu(self):
169        """Displays the main in-game menu.
170           @return: None"""
171        if (self.menu_displayed == False):
172            self.main_menu.show()
173            self.menu_displayed = True
174        elif (self.menu_displayed == True):
175            self.hideMenu()
176
177    def hideMenu(self):
178        """Hides the main in-game menu.
179           @return: None"""
180        self.main_menu.hide()
181        self.menu_displayed = False
182
183
184    def initializeHelpMenu(self):
185        """Initialize the help menu
186           @return: None"""
187        self.help_dialog = pychan.loadXML("gui/help.xml")
188        help_events = {"closeButton":self.help_dialog.hide}
189        self.help_dialog.mapEvents(help_events)
190        main_help_text = u"Welcome to Post-Apocalyptic RPG or PARPG![br][br]"\
191        "This game is still in development, so please expect for there to be "\
192        "bugs and[br]feel free to tell us about them at "\
193        "http://www.forums.parpg.net.[br]This game uses a "\
194        "\"Point 'N' Click\" interface, which means that to move around,[br]"\
195        "just click where you would like to go and your character will move "\
196        "there.[br]PARPG also utilizes a context menu. To access this, just "\
197        "right click anywhere[br]on the screen and a menu will come up. This "\
198        "menu will change depending on[br]what you have clicked on, hence "\
199        "it's name \"context menu\".[br][br]"
200       
201        k_text = u" Keybindings" 
202        k_text += "[br] A : Add a test action to the actions display"
203        k_text += "[br] I : Toggle the inventory screen"
204        k_text += "[br] F5 : Take a screenshot"
205        k_text += "[br]      (saves to <parpg>/screenshots/)"
206        k_text += "[br] Q : Quit the game"
207        self.help_dialog.distributeInitialData({
208                "MainHelpText":main_help_text,
209                "KeybindText":k_text
210                })
211
212    def displayHelp(self):
213        """Display the help screen.
214           @return: None"""
215        self.help_dialog.show()
216
217    def switchResolutions(self):
218        """ Sync the contents of the resolution box (windowed or fullscreen
219            resolutions to the selection made in the Fullscreen checkbox.
220            @return: None"""
221           
222        if self.options_menu.collectData('FullscreenBox'):
223            self.options_menu.distributeInitialData({
224                                'ResolutionBox' : self.resolutions_fullscreen
225                                                     })
226        else:
227            self.options_menu.distributeInitialData({
228                                'ResolutionBox' : self.resolutions_windowed
229                                                     })
230       
231    def initializeOptionsMenu(self):
232        """Initialize the options menu, this will generate a list of fullscreen
233           resolutions and a list of windowed resolutions. Next to this the
234           current active settings are read and also selected in the matching
235           widgets.
236           @return: None"""
237           
238        self.options_menu = pychan.loadXML("gui/hud_options.xml")
239        self.options_events = {"applyButton":self.applyOptions,
240                               "closeButton":self.options_menu.hide,
241                               "defaultsButton":self.setToDefaults,
242                               "FullscreenBox": self.switchResolutions,
243                               "InitialVolumeSlider":self.updateVolumeText}
244       
245        settings = self.engine.getSettings()
246        # The settings need to be set to fullscreen for the call to
247        # getPossibleResolutions() to function.
248        current_fullscreen = settings.isFullScreen()
249        settings.setFullScreen(True)
250       
251        available_fullscreen_resolutions = settings.getPossibleResolutions()
252        available_windowed_resolutions = ((1920, 1200), (1920, 1080), \
253                                          (1856, 1392), (1792, 1344), \
254                                          (1680, 1050), (1600, 1200), \
255                                          (1600, 1024), (1440,  900), \
256                                          (1400, 1050), (1360,  768), \
257                                          (1280, 1024), (1280,  960), \
258                                          (1152,  864), (1024,  768))
259        # Filter too small resolutions from the fullscreen resolutions
260        self.resolutions_fullscreen = []
261        for x in available_fullscreen_resolutions:
262            if x[0] >= 1024 and x[1] >= 768:
263                self.resolutions_fullscreen.append(str(x[0]) + 'x' + str(x[1]))
264
265        # Filter too large resolution from the windowed resolutions
266        self.resolutions_windowed = []
267        for x in available_windowed_resolutions:
268            if x[0] <= available_fullscreen_resolutions[0][0] and \
269            x[1] <= available_fullscreen_resolutions[0][1]:
270                self.resolutions_windowed.append(str(x[0]) + 'x' + str(x[1]))       
271       
272        settings.setFullScreen(current_fullscreen)
273        self.render_backends = ['OpenGL', 'SDL']
274        self.render_number = 0
275        if (str(self.settings.readSetting('RenderBackend')) == "SDL"):
276            self.render_number = 1
277        initial_volume = float(self.settings.readSetting('InitialVolume'))
278        initial_volume_text = str('Initial Volume: %.0f%s' %
279                                (int(initial_volume*10), "%"))
280        initial_data_to_distribute = {   
281                'RenderBox'          : self.render_backends,
282                'InitialVolumeLabel' : initial_volume_text
283                }
284
285        s_fullscreen = self.settings.readSetting(name="FullScreen")
286        s_sounds = self.settings.readSetting(name="PlaySounds")
287        s_render = self.render_number
288        s_volume = initial_volume
289
290        # Find the current active resolution so we can select it
291        screen_width = self.settings.readSetting(name="ScreenWidth")
292        screen_height = self.settings.readSetting(name="ScreenHeight")
293        index_res = str(screen_width + 'x' + screen_height)
294        try:
295            if int(s_fullscreen) == 0:
296                s_resolution = self.resolutions_windowed.index(index_res)
297            else:
298                s_resolution = self.resolutions_fullscreen.index(index_res)
299            resolution_in_list = True
300        except:
301            resolution_in_list = False
302           
303        data_to_distribute = {
304                'FullscreenBox'      : int(s_fullscreen), 
305                'SoundsBox'          : int(s_sounds),
306                'RenderBox'          : s_render,
307                'InitialVolumeSlider': s_volume
308                }
309
310        if int(s_fullscreen) == 0:
311            initial_data_to_distribute['ResolutionBox'] = self.resolutions_windowed
312        else:
313            initial_data_to_distribute['ResolutionBox'] = self.resolutions_fullscreen
314           
315        if (resolution_in_list == True):
316            data_to_distribute['ResolutionBox'] = s_resolution
317
318        self.options_menu.distributeInitialData(initial_data_to_distribute)
319        self.options_menu.distributeData(data_to_distribute)
320        self.options_menu.mapEvents(self.options_events)
321
322    def saveGame(self):
323        """ Called when the user wants to save the game.
324            @return: None"""
325        save_browser = FileBrowser(self.engine,
326                                   self.save_game_callback,
327                                   save_file=True,
328                                   gui_xml_path="gui/savebrowser.xml",
329                                   extensions = ('.dat'))
330        save_browser.showBrowser()
331           
332    def newGame(self):
333        """Called when user request to start a new game.
334           @return: None"""
335        print 'new game'
336
337    def loadGame(self):
338        """ Called when the user wants to load a game.
339            @return: None"""
340        load_browser = FileBrowser(self.engine,
341                                   self.load_game_callback,
342                                   save_file=False,
343                                   gui_xml_path='gui/loadbrowser.xml',
344                                   extensions=('.dat'))
345        load_browser.showBrowser()
346   
347    def initializeQuitDialog(self):
348        """Creates the quit confirmation dialog
349           @return: None"""
350        self.quit_window = pychan.widgets.Window(title=unicode("Quit?"), \
351                                                 min_size=(200,0))
352
353        hbox = pychan.widgets.HBox()
354        are_you_sure = "Are you sure you want to quit?"
355        label = pychan.widgets.Label(text=unicode(are_you_sure))
356        yes_button = pychan.widgets.Button(name="yes_button", 
357                                           text=unicode("Yes"),
358                                           min_size=(90,20),
359                                           max_size=(90,20))
360        no_button = pychan.widgets.Button(name="no_button",
361                                          text=unicode("No"),
362                                          min_size=(90,20),
363                                          max_size=(90,20))
364
365        self.quit_window.addChild(label)
366        hbox.addChild(yes_button)
367        hbox.addChild(no_button)
368        self.quit_window.addChild(hbox)
369
370        events_to_map = { "yes_button": self.quit_callback,
371                          "no_button":  self.quit_window.hide }
372       
373        self.quit_window.mapEvents(events_to_map)
374
375
376    def quitGame(self):
377        """Called when user requests to quit game.
378           @return: None"""
379
380        self.quit_window.show()
381
382    def toggleInventoryButton(self):
383        """Manually toggles the inventory button.
384           @return: None"""
385        button = self.hud.findChild(name="inventoryButton")
386        if button.toggled == 0:
387            button.toggled = 1
388        else:
389            button.toggled = 0
390
391    def toggleInventory(self, toggleImage=True):
392        """Display's the inventory screen
393           @return: None"""
394
395        self.inventory.toggleInventory(toggleImage)
396
397    def refreshReadyImages(self):
398        """Make the Ready slot images on the HUD be the same as those
399           on the inventory
400           @return: None"""
401        self.setImages(self.hud.findChild(name="hudReady1"),
402                       self.inventory.getImage("Ready1").up_image)
403
404        self.setImages(self.hud.findChild(name="hudReady2"),
405                       self.inventory.getImage("Ready2").up_image)
406
407        self.setImages(self.hud.findChild(name="hudReady3"),
408                       self.inventory.getImage("Ready3").up_image)
409
410        self.setImages(self.hud.findChild(name="hudReady4"),
411                       self.inventory.getImage("Ready4").up_image)
412
413    def setImages(self, widget, image):
414        """Set the up, down, and hover images of an Imagebutton.
415           @type widget: pychan.widget
416           @param widget: widget to set
417           @type image: string
418           @param image: image to use
419           @return: None"""
420        widget.up_image = image
421        widget.down_image = image
422        widget.hover_image = image
423
424    def initializeEvents(self):
425        """Intialize Hud events
426           @return: None"""
427        events_to_map = {}
428
429        # when we click the toggle button don't change the image
430        events_to_map["inventoryButton"] = cbwa(self.toggleInventory, False)
431        events_to_map["saveButton"] = self.saveGame
432        events_to_map["loadButton"] = self.loadGame
433
434        hud_ready_buttons = ["hudReady1", "hudReady2", \
435                             "hudReady3", "hudReady4"]
436
437        for item in hud_ready_buttons:
438            events_to_map[item] = cbwa(self.readyAction, item)
439
440        self.hud.mapEvents(events_to_map)
441
442        menu_events = {}
443        menu_events["newButton"] = self.newGame
444        menu_events["quitButton"] = self.quitGame
445        menu_events["saveButton"] = self.saveGame
446        menu_events["loadButton"] = self.loadGame
447        self.main_menu.mapEvents(menu_events)
448
449    def updateVolumeText(self):
450        """
451        Update the initial volume label to reflect the value of the slider
452        """
453        volume = float(self.options_menu.collectData("InitialVolumeSlider"))
454        volume_label = self.options_menu.findChild(name="InitialVolumeLabel")
455        volume_label.text = unicode("Initial Volume: %.0f%s" %
456                                    (int(volume*10), "%"))
457
458    def requireRestartDialog(self):
459        """Show a dialog asking the user to restart PARPG in order for their
460           changes to take effect.
461           @return: None"""
462        require_restart_dialog = pychan.loadXML('gui/hud_require_restart.xml')
463        require_restart_dialog.mapEvents(\
464                                {'okButton':require_restart_dialog.hide})
465        require_restart_dialog.show()
466
467    def applyOptions(self):
468        """Apply the current options.
469           @return: None"""
470        # At first no restart is required
471        self.require_restart = False
472
473        # get the current values of each setting from the options menu
474        enable_fullscreen = self.options_menu.collectData('FullscreenBox')
475        enable_sound = self.options_menu.collectData('SoundsBox')
476        screen_resolution = self.options_menu.collectData('ResolutionBox')
477        if enable_fullscreen:
478            partition = self.resolutions_fullscreen[screen_resolution].partition('x')
479        else:
480            partition = self.resolutions_windowed[screen_resolution].partition('x')
481        screen_width = partition[0]
482        screen_height = partition[2]
483        render_backend = self.options_menu.collectData('RenderBox')
484        initial_volume = self.options_menu.collectData('InitialVolumeSlider')
485        initial_volume = "%.1f" % initial_volume
486
487        # get the options that are being used right now from settings.xml
488        s_fullscreen = self.settings.readSetting('FullScreen')
489        s_sounds = self.settings.readSetting('PlaySounds')
490        s_render = self.settings.readSetting('RenderBackend')
491        s_volume = self.settings.readSetting('InitialVolume')
492
493        s_screen_height = self.settings.readSetting('ScreenHeight')
494        s_screen_width = self.settings.readSetting('ScreenWidth')
495        s_resolution = s_screen_width + 'x' + s_screen_height
496
497        # On each:
498        # - Check to see whether the option within the xml matches the
499        #   option within the options menu
500        # - If they do not match, set the option within the xml to
501        #   to be what is within the options menu
502        # - Require a restart
503
504        if (int(enable_fullscreen) != int(s_fullscreen)):
505            self.setOption('FullScreen', int(enable_fullscreen))
506            self.require_restart = True
507           
508        if (int(enable_sound) != int(s_sounds)):
509            self.setOption('PlaySounds', int(enable_sound))
510            self.require_restart = True
511
512        if (screen_resolution != s_resolution):
513            self.setOption('ScreenWidth', int(screen_width))
514            self.setOption('ScreenHeight', int(screen_height))
515            self.require_restart = True
516
517        # Convert the number from the list of render backends to
518        # the string that FIFE wants for its settings.xml
519        if (render_backend == 0):
520            render_backend = 'OpenGL'
521        else:
522            render_backend = 'SDL'
523
524        if (render_backend != str(s_render)):
525            self.setOption('RenderBackend', render_backend)
526            self.require_restart = True
527
528        if (initial_volume != float(s_volume)):
529            self.setOption('InitialVolume', initial_volume)
530            self.require_restart = True
531       
532        # Write all the settings to settings.xml
533        self.settings.tree.write('settings.xml')
534       
535        # If the changes require a restart, popup the dialog telling
536        # the user to do so
537        if (self.require_restart):
538            self.requireRestartDialog()
539        # Once we are done, we close the options menu
540        self.options_menu.hide()
541
542    def setOption(self, name, value):
543        """Set an option within the xml.
544           @type name: string
545           @param name: The name of the option within the xml
546           @type value: any
547           @param value: The value that the option 'name' should be set to
548           @return: None"""
549        element = self.settings.root_element.find(name)
550        if(element != None):
551            if(value != element.text):
552                element.text = str(value)
553        else:
554            print 'Setting,', name, 'does not exist!'
555
556    def setToDefaults(self):
557        """Reset all the options to the options in settings-dist.xml.
558           @return: None"""
559        shutil.copyfile('settings-dist.xml', 'settings.xml')
560        self.requireRestartDialog()
561        self.options_menu.hide()
562
563    def displayOptions(self):
564        """Display the options menu.
565           @return: None"""
566        self.options_menu.show()
567   
568    def readyAction(self, ready_button):
569        """ Called when the user selects a ready button from the HUD """
570        text = "Used the item from %s" % ready_button
571        self.addAction(text)
572       
573    def createBoxGUI(self, title):
574        """Creates a window to display the contents of a box
575           @type title: string
576           @param title: The title for the window
577           @return: None"""
578        if self.box_container:
579            # if it has already been created, just show it
580            self.box_container.showContainer()
581        else:
582            # otherwise create it then show it
583            data = ["dagger01", "empty", "empty", "empty", "empty",
584                    "empty", "empty", "empty", "empty"]
585            self.box_container = ContainerGUI(self.engine, \
586                                              unicode(title), data)
587            def closeAndDelete():
588                self.hideContainer()
589            events = {'takeAllButton':closeAndDelete,
590                      'closeButton':closeAndDelete}
591            self.box_container.container_gui.mapEvents(events)
592            self.box_container.showContainer()
593
594    def hideContainer(self):
595        """Hide the container box
596           @return: None"""
597        if self.box_container:
598            self.box_container.hideContainer()
599
600    def createExamineBox(self, title, desc):
601        """Create an examine box. It displays some textual description of an
602           object
603           @type title: string
604           @param title: The title of the examine box
605           @type desc: string
606           @param desc: The main body of the examine box
607           @return: None"""
608
609        if self.examine_box is not None:
610            self.examine_box.closePopUp()
611        self.examine_box = ExaminePopup(self.engine, title, desc)
612        self.examine_box.showPopUp()
613
614    def showDialogue(self, npc):
615        """Show the NPC dialogue window
616           @type npc: ???
617           @param npc: the npc that we are having a dialogue with"""
618        dialogue = DialogueGUI(npc)
619        dialogue.initiateDialogue()
Note: See TracBrowser for help on using the repository browser.