source: trunk/game/scripts/gui/hud.py @ 444

Revision 444, 24.8 KB checked in by b0rland_parpg, 10 years ago (diff)

Ticket #107: patch by b0rland
Ready slots in hud are now updated in sync with inventory

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