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

Revision 346, 22.0 KB checked in by b0rland_parpg, 10 years ago (diff)

Ticket #107: patch by b0rland

  • Wrote initial version of the inventory storage class
  • Added some useful utility functions into container class and its derivatives
  • Created several combined classes for carryable containers
  • Extended tests and of course made new ones
  • Renamed old Inventory class to be InventoryGUI

Note: InventoryGUI still works the old way and doesn't use 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.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 accoriding 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 initializeOptionsMenu(self):
218        """Initalize the options menu.
219           @return: None"""
220        self.options_menu = pychan.loadXML("gui/hud_options.xml")
221        self.options_events = {"applyButton":self.applyOptions,
222                               "closeButton":self.options_menu.hide,
223                               "defaultsButton":self.setToDefaults,
224                               "InitialVolumeSlider":self.updateVolumeText}
225       
226        settings = self.engine.getSettings()
227        current_fullscreen = settings.isFullScreen()
228        settings.setFullScreen(True)
229        available_resolutions = settings.getPossibleResolutions()
230
231        # Filter too small resolutions
232        self.resolutions=[]
233        for x in available_resolutions:
234            if x[0]>=1024 and x[1]>=768:
235                self.resolutions.append(str(x[0])+'x'+str(x[1]))
236
237        settings.setFullScreen(current_fullscreen)
238        self.render_backends = ['OpenGL', 'SDL']
239        self.render_number = 0
240        if (str(self.settings.readSetting('RenderBackend')) == "SDL"):
241            self.render_number = 1
242        initial_volume = float(self.settings.readSetting('InitialVolume'))
243        initial_volume_text = str('Initial Volume: %.0f%s' %
244                                (int(initial_volume*10), "%"))
245        self.options_menu.distributeInitialData({
246                'ResolutionBox': self.resolutions,
247                'RenderBox': self.render_backends,
248                'InitialVolumeLabel' : initial_volume_text
249                })
250
251        s_fullscreen = self.settings.readSetting(name="FullScreen")
252        s_sounds = self.settings.readSetting(name="PlaySounds")
253        s_render = self.render_number
254        s_volume = initial_volume
255
256        screen_width = self.settings.readSetting(name="ScreenWidth")
257        screen_height = self.settings.readSetting(name="ScreenHeight")
258        index_res = str(screen_width + 'x' + screen_height)
259        try:
260            s_resolution = self.resolutions.index(index_res)
261            resolution_in_list = True
262        except:
263            resolution_in_list = False
264
265        data_to_distribute = {
266                'FullscreenBox':int(s_fullscreen), 
267                'SoundsBox':int(s_sounds),
268                'RenderBox': s_render,
269                'InitialVolumeSlider':s_volume
270                }
271
272        if (resolution_in_list == True):
273            data_to_distribute['ResolutionBox'] = s_resolution
274
275        self.options_menu.distributeData(data_to_distribute)
276
277        self.options_menu.mapEvents(self.options_events)
278
279    def saveGame(self):
280        """ Called when the user wants to save the game.
281            @return: None"""
282        save_browser = FileBrowser(self.engine,
283                                   self.save_game_callback,
284                                   save_file=True,
285                                   gui_xml_path="gui/savebrowser.xml",
286                                   extensions = ('.dat'))
287        save_browser.showBrowser()
288           
289    def newGame(self):
290        """Called when user request to start a new game.
291           @return: None"""
292        print 'new game'
293
294    def loadGame(self):
295        """ Called when the user wants to load a game.
296            @return: None"""
297        load_browser = FileBrowser(self.engine,
298                                   self.load_game_callback,
299                                   save_file=False,
300                                   gui_xml_path='gui/loadbrowser.xml',
301                                   extensions=('.dat'))
302        load_browser.showBrowser()
303   
304    def initializeQuitDialog(self):
305        """Creates the quit confirmation dialog
306           @return: None"""
307        self.quit_window = pychan.widgets.Window(title=unicode("Quit?"), \
308                                                 min_size=(200,0))
309
310        hbox = pychan.widgets.HBox()
311        are_you_sure = "Are you sure you want to quit?"
312        label = pychan.widgets.Label(text=unicode(are_you_sure))
313        yes_button = pychan.widgets.Button(name="yes_button", 
314                                           text=unicode("Yes"),
315                                           min_size=(90,20),
316                                           max_size=(90,20))
317        no_button = pychan.widgets.Button(name="no_button",
318                                          text=unicode("No"),
319                                          min_size=(90,20),
320                                          max_size=(90,20))
321
322        self.quit_window.addChild(label)
323        hbox.addChild(yes_button)
324        hbox.addChild(no_button)
325        self.quit_window.addChild(hbox)
326
327        events_to_map = { "yes_button": self.quit_callback,
328                          "no_button":  self.quit_window.hide }
329       
330        self.quit_window.mapEvents(events_to_map)
331
332
333    def quitGame(self):
334        """Called when user requests to quit game.
335           @return: None"""
336
337        self.quit_window.show()
338
339    def toggleInventoryButton(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
348    def toggleInventory(self, toggleImage=True):
349        """Display's the inventory screen
350           @return: None"""
351
352        self.inventory.toggleInventory(toggleImage)
353
354    def refreshReadyImages(self):
355        """Make the Ready slot images on the HUD be the same as those
356           on the inventory
357           @return: None"""
358        self.setImages(self.hud.findChild(name="hudReady1"),
359                       self.inventory.getImage("Ready1").up_image)
360
361        self.setImages(self.hud.findChild(name="hudReady2"),
362                       self.inventory.getImage("Ready2").up_image)
363
364        self.setImages(self.hud.findChild(name="hudReady3"),
365                       self.inventory.getImage("Ready3").up_image)
366
367        self.setImages(self.hud.findChild(name="hudReady4"),
368                       self.inventory.getImage("Ready4").up_image)
369
370    def setImages(self, widget, image):
371        """Set the up, down, and hover images of an Imagebutton.
372           @type widget: pychan.widget
373           @param widget: widget to set
374           @type image: string
375           @param image: image to use
376           @return: None"""
377        widget.up_image = image
378        widget.down_image = image
379        widget.hover_image = image
380
381    def initializeEvents(self):
382        """Intialize Hud events
383           @return: None"""
384        events_to_map = {}
385
386        # when we click the toggle button don't change the image
387        events_to_map["inventoryButton"] = cbwa(self.toggleInventory, False)
388        events_to_map["saveButton"] = self.saveGame
389        events_to_map["loadButton"] = self.loadGame
390
391        hud_ready_buttons = ["hudReady1", "hudReady2", \
392                             "hudReady3", "hudReady4"]
393
394        for item in hud_ready_buttons:
395            events_to_map[item] = cbwa(self.readyAction, item)
396
397        self.hud.mapEvents(events_to_map)
398
399        menu_events = {}
400        menu_events["newButton"] = self.newGame
401        menu_events["quitButton"] = self.quitGame
402        menu_events["saveButton"] = self.saveGame
403        menu_events["loadButton"] = self.loadGame
404        self.main_menu.mapEvents(menu_events)
405
406    def updateVolumeText(self):
407        """
408        Update the initial volume label to reflect the value of the slider
409        """
410        volume = float(self.options_menu.collectData("InitialVolumeSlider"))
411        volume_label = self.options_menu.findChild(name="InitialVolumeLabel")
412        volume_label.text = unicode("Initial Volume: %.0f%s" %
413                                    (int(volume*10), "%"))
414
415    def requireRestartDialog(self):
416        """Show a dialog asking the user to restart PARPG in order for their
417           changes to take effect.
418           @return: None"""
419        require_restart_dialog = pychan.loadXML('gui/hud_require_restart.xml')
420        require_restart_dialog.mapEvents(\
421                                {'okButton':require_restart_dialog.hide})
422        require_restart_dialog.show()
423
424    def applyOptions(self):
425        """Apply the current options.
426           @return: None"""
427        # At first no restart is required
428        self.require_restart = False
429
430        # get the current values of each setting from the options menu
431        enable_fullscreen = self.options_menu.collectData('FullscreenBox')
432        enable_sound = self.options_menu.collectData('SoundsBox')
433        screen_resolution = self.options_menu.collectData('ResolutionBox')
434        partition = self.resolutions[screen_resolution].partition('x')
435        screen_width = partition[0]
436        screen_height = partition[2]
437        render_backend = self.options_menu.collectData('RenderBox')
438        initial_volume = self.options_menu.collectData('InitialVolumeSlider')
439        initial_volume = "%.1f" % initial_volume
440
441        # get the options that are being used right now from settings.xml
442        s_fullscreen = self.settings.readSetting('FullScreen')
443        s_sounds = self.settings.readSetting('PlaySounds')
444        s_render = self.settings.readSetting('RenderBackend')
445        s_volume = self.settings.readSetting('InitialVolume')
446
447        s_screen_height = self.settings.readSetting('ScreenHeight')
448        s_screen_width = self.settings.readSetting('ScreenWidth')
449        s_resolution = s_screen_width + 'x' + s_screen_height
450
451        # On each:
452        # - Check to see whether the option within the xml matches the
453        #   option within the options menu
454        # - If they do not match, set the option within the xml to
455        #   to be what is within the options menu
456        # - Require a restart
457
458        if (int(enable_fullscreen) != int(s_fullscreen)):
459            self.setOption('FullScreen', int(enable_fullscreen))
460            self.require_restart = True
461           
462        if (int(enable_sound) != int(s_sounds)):
463            self.setOption('PlaySounds', int(enable_sound))
464            self.require_restart = True
465
466        if (screen_resolution != s_resolution):
467            self.setOption('ScreenWidth', int(screen_width))
468            self.setOption('ScreenHeight', int(screen_height))
469            self.require_restart = True
470
471        # Convert the number from the list of render backends to
472        # the string that FIFE wants for its settings.xml
473        if (render_backend == 0):
474            render_backend = 'OpenGL'
475        else:
476            render_backend = 'SDL'
477
478        if (render_backend != str(s_render)):
479            self.setOption('RenderBackend', render_backend)
480            self.require_restart = True
481
482        if (initial_volume != float(s_volume)):
483            self.setOption('InitialVolume', initial_volume)
484            self.require_restart = True
485       
486        # Write all the settings to settings.xml
487        self.settings.tree.write('settings.xml')
488       
489        # If the changes require a restart, popup the dialog telling
490        # the user to do so
491        if (self.require_restart):
492            self.requireRestartDialog()
493        # Once we are done, we close the options menu
494        self.options_menu.hide()
495
496    def setOption(self, name, value):
497        """Set an option within the xml.
498           @type name: string
499           @param name: The name of the option within the xml
500           @type value: any
501           @param value: The value that the option 'name' should be set to
502           @return: None"""
503        element = self.settings.root_element.find(name)
504        if(element != None):
505            if(value != element.text):
506                element.text = str(value)
507        else:
508            print 'Setting,', name, 'does not exist!'
509
510    def setToDefaults(self):
511        """Reset all the options to the options in settings-dist.xml.
512           @return: None"""
513        shutil.copyfile('settings-dist.xml', 'settings.xml')
514        self.requireRestartDialog()
515        self.options_menu.hide()
516
517    def displayOptions(self):
518        """Display the options menu.
519           @return: None"""
520        self.options_menu.show()
521   
522    def readyAction(self, ready_button):
523        """ Called when the user selects a ready button from the HUD """
524        text = "Used the item from %s" % ready_button
525        self.addAction(text)
526       
527    def createBoxGUI(self, title):
528        """Creates a window to display the contents of a box
529           @type title: string
530           @param title: The title for the window
531           @return: None"""
532        if self.box_container:
533            # if it has already been created, just show it
534            self.box_container.showContainer()
535        else:
536            # otherwise create it then show it
537            data = ["dagger01", "empty", "empty", "empty", "empty",
538                    "empty", "empty", "empty", "empty"]
539            self.box_container = ContainerGUI(self.engine, \
540                                              unicode(title), data)
541            def closeAndDelete():
542                self.hideContainer()
543            events = {'takeAllButton':closeAndDelete,
544                      'closeButton':closeAndDelete}
545            self.box_container.container_gui.mapEvents(events)
546            self.box_container.showContainer()
547
548    def hideContainer(self):
549        """Hide the container box
550           @return: None"""
551        if self.box_container:
552            self.box_container.hideContainer()
553
554    def createExamineBox(self, title, desc):
555        """Create an examine box. It displays some textual description of an
556           object
557           @type title: string
558           @param title: The title of the examine box
559           @type desc: string
560           @param desc: The main body of the examine box
561           @return: None"""
562
563        if self.examine_box is not None:
564            self.examine_box.closePopUp()
565        self.examine_box = ExaminePopup(self.engine, title, desc)
566        self.examine_box.showPopUp()
567
568    def showDialogue(self, npc):
569        """Show the NPC dialogue window
570           @type npc: ???
571           @param npc: the npc that we are having a dialogue with"""
572        dialogue = DialogueGUI(npc)
573        dialogue.initiateDialogue()
Note: See TracBrowser for help on using the repository browser.