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

Revision 584, 16.7 KB checked in by beliar, 10 years ago (diff)

Removed pylint command to ignore missing docstring at the beginning of a file, it interfered with the shebang

  • Property svn:eol-style set to native
Line 
1#!/usr/bin/env 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
18from fife.extensions import pychan
19from fife.extensions.pychan.tools import callbackWithArguments as cbwa
20
21from scripts.gui.filebrowser import FileBrowser
22from scripts.gui.context_menu import ContextMenu
23from scripts.gui import inventorygui
24from scripts.gui.popups import ExaminePopup
25from scripts.gui.containergui import ContainerGUI
26from scripts.gui.dialoguegui import DialogueGUI
27
28class Hud(object):
29    """Main Hud class"""
30    def __init__(self, controller, settings, callbacks):
31        """Initialise the instance.
32           @type controller: Class derived from ControllerBase
33           @param controller: The current controller
34           @type settings: settings.Setting
35           @param settings: The settings
36           @type inv_model: dict
37           @type callbacks: dict
38           @param callbacks: a dict of callbacks
39               saveGame: called when the user clicks on Save
40               loadGame: called when the user clicks on Load
41               quitGame: called when the user clicks on Quit
42           @return: None"""
43        pychan.init(controller.engine, debug = True)
44
45        # TODO: perhaps this should not be hard-coded here
46        self.hud = pychan.loadXML("gui/hud.xml")
47        self.controller = controller
48        self.engine = controller.engine
49        self.model = controller.model
50        self.settings = settings
51        self.inventory = None
52
53        self.save_game_callback = callbacks['saveGame']
54        self.load_game_callback = callbacks['loadGame']
55        self.quit_callback      = callbacks['quitGame']
56
57        self.box_container = None
58        self.examine_box = None
59        self.context_menu = None
60        self.help_dialog = None
61        self.events_to_map = None
62        self.main_menu = None
63        self.menu_events = None
64        self.quit_window = None
65       
66        self.actions_box = self.hud.findChild(name="actionsBox")
67        #self.actions_text = ""
68        self.menu_displayed = False
69        self.inventory_storage = None
70        self.initializeHud()
71        self.initializeMainMenu()
72        self.initializeContextMenu()
73        self.initializeHelpMenu()
74        self.initializeEvents()
75        self.initializeQuitDialog()
76
77    def initializeHud(self):
78        """Initialize and show the main HUD
79           @return: None"""
80        self.events_to_map = {"menuButton":self.displayMenu, }
81        self.hud.mapEvents(self.events_to_map) 
82        # set HUD size according to screen size
83        screen_width = self.engine.getSettings().getScreenWidth()
84        self.hud.findChild(name="mainHudWindow").size = (screen_width, 65)
85        self.hud.findChild(name="inventoryButton").position = \
86                                                    (screen_width-59, 7)
87        # add ready slots
88        ready1 = self.hud.findChild(name='hudReady1')
89        ready2 = self.hud.findChild(name='hudReady2')
90        ready3 = self.hud.findChild(name='hudReady3')
91        ready4 = self.hud.findChild(name='hudReady4')
92        actions_scroll_area = self.hud.findChild(name='actionsScrollArea')
93
94        if (screen_width <=800) :
95            gap = 0
96        else :
97            gap = 40
98        ready1.position = (160+gap, 7)
99        ready2.position = (220+gap, 7)
100        ready3.position = (screen_width-180-gap, 7)
101        ready4.position = (screen_width-120-gap, 7)
102        actions_scroll_area.position = (280+gap, 5)
103        actions_width = screen_width - 470 - 2*gap
104
105        self.actions_box.min_width = actions_width
106        self.actions_box.max_width = actions_width
107       
108        # and finally add an actions box
109        actions_scroll_area.min_size = (actions_width, 55)
110        actions_scroll_area.max_size = (actions_width, 55)
111        # now it should be OK to display it all
112        self.hud.show()
113
114    def refreshActionsBox(self):
115        """Refresh the actions box so that it displays the contents of
116           self.actions_text
117           @return: None"""
118        self.actions_box.adaptLayout()
119        self.actions_box.parent.adaptLayout()
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        action_label = pychan.widgets.Label(text = action, wrap_text = True)
127        action_label.max_width = self.actions_box.width
128        self.actions_box.insertChild(action_label, 0)
129        self.refreshActionsBox()
130
131    def showHUD(self):
132        """Show the HUD.
133           @return: None"""
134        self.hud.show()
135
136    def hideHUD(self):
137        """Hide the HUD.
138           @return: None"""
139        self.hud.hide()
140
141    def initializeInventory(self):
142        """Initialize the inventory"""
143        inv_callbacks = {
144            'refreshReadyImages': self.refreshReadyImages,
145            'toggleInventoryButton': self.toggleInventoryButton,
146        }
147        self.inventory_storage = self.model.game_state.player_character.inventory
148        if self.inventory == None:
149            self.inventory = inventorygui.InventoryGUI(self.controller,
150                                                       self.inventory_storage,
151                                                       inv_callbacks)
152        else:
153            self.inventory.inventory_storage = self.inventory_storage
154        self.refreshReadyImages()
155
156    def initializeContextMenu(self):
157        """Initialize the Context Menu
158           @return: None"""
159        self.context_menu = ContextMenu (self.engine, [], (0, 0))
160        self.context_menu.hide()
161
162    def showContextMenu(self, data, pos):
163        """Display the Context Menu with model at pos
164           @type model: list
165           @param model: model to pass to context menu
166           @type pos: tuple
167           @param pos: tuple of x and y coordinates
168           @return: None"""
169        self.context_menu = ContextMenu(self.engine, data, pos)
170
171    def hideContextMenu(self):
172        """Hides the context menu
173           @return: None"""
174        self.context_menu.hide()
175
176    def initializeMainMenu(self):
177        """Initalize the main menu.
178           @return: None"""
179        self.main_menu = pychan.loadXML("gui/hud_main_menu.xml")
180        self.menu_events = {"resumeButton":self.hideMenu, 
181                            "optionsButton":self.settings.onOptionsPress,
182                            "helpButton":self.displayHelp}
183        self.main_menu.mapEvents(self.menu_events)
184
185    def displayMenu(self):
186        """Displays the main in-game menu.
187           @return: None"""
188        if (self.menu_displayed == False):
189            self.main_menu.show()
190            self.menu_displayed = True
191        elif (self.menu_displayed == True):
192            self.hideMenu()
193
194    def hideMenu(self):
195        """Hides the main in-game menu.
196           @return: None"""
197        self.main_menu.hide()
198        self.menu_displayed = False
199
200
201    def initializeHelpMenu(self):
202        """Initialize the help menu
203           @return: None"""
204        self.help_dialog = pychan.loadXML("gui/help.xml")
205        help_events = {"closeButton":self.help_dialog.hide}
206        self.help_dialog.mapEvents(help_events)
207        main_help_text = u"Welcome to Post-Apocalyptic RPG or PARPG![br][br]"\
208        "This game is still in development, so please expect for there to be "\
209        "bugs and[br]feel free to tell us about them at "\
210        "http://www.forums.parpg.net.[br]This game uses a "\
211        "\"Point 'N' Click\" interface, which means that to move around,[br]"\
212        "just click where you would like to go and your character will move "\
213        "there.[br]PARPG also utilizes a context menu. To access this, just "\
214        "right click anywhere[br]on the screen and a menu will come up. This "\
215        "menu will change depending on[br]what you have clicked on, hence "\
216        "it's name \"context menu\".[br][br]"
217       
218        k_text = u" Keybindings" 
219        k_text += "[br] A : Add a test action to the actions display"
220        k_text += "[br] I : Toggle the inventory screen"
221        k_text += "[br] F5 : Take a screenshot"
222        k_text += "[br]      (saves to <parpg>/screenshots/)"
223        k_text += "[br] F10 : Toggle console"
224        k_text += "[br] PAUSE : (Un)Pause the game"
225        k_text += "[br] Q : Quit the game"
226        self.help_dialog.distributeInitialData({
227                "MainHelpText":main_help_text,
228                "KeybindText":k_text
229                })
230
231    def displayHelp(self):
232        """Display the help screen.
233           @return: None"""
234        self.help_dialog.show()
235
236    def saveGame(self):
237        """ Called when the user wants to save the game.
238            @return: None"""
239        save_browser = FileBrowser(self.engine,
240                                   self.save_game_callback,
241                                   save_file=True,
242                                   gui_xml_path="gui/savebrowser.xml",
243                                   extensions = ('.dat'))
244        save_browser.showBrowser()
245           
246    def newGame(self):
247        """Called when user request to start a new game.
248           @return: None"""
249        print 'new game'
250
251    def loadGame(self):
252        """ Called when the user wants to load a game.
253            @return: None"""
254        load_browser = FileBrowser(self.engine,
255                                   self.load_game_callback,
256                                   save_file=False,
257                                   gui_xml_path='gui/loadbrowser.xml',
258                                   extensions=('.dat'))
259        load_browser.showBrowser()
260   
261    def initializeQuitDialog(self):
262        """Creates the quit confirmation dialog
263           @return: None"""
264        self.quit_window = pychan.widgets.Window(title=unicode("Quit?"), \
265                                                 min_size=(200,0))
266
267        hbox = pychan.widgets.HBox()
268        are_you_sure = "Are you sure you want to quit?"
269        label = pychan.widgets.Label(text=unicode(are_you_sure))
270        yes_button = pychan.widgets.Button(name="yes_button", 
271                                           text=unicode("Yes"),
272                                           min_size=(90,20),
273                                           max_size=(90,20))
274        no_button = pychan.widgets.Button(name="no_button",
275                                          text=unicode("No"),
276                                          min_size=(90,20),
277                                          max_size=(90,20))
278
279        self.quit_window.addChild(label)
280        hbox.addChild(yes_button)
281        hbox.addChild(no_button)
282        self.quit_window.addChild(hbox)
283
284        events_to_map = { "yes_button": self.quit_callback,
285                          "no_button":  self.quit_window.hide }
286       
287        self.quit_window.mapEvents(events_to_map)
288
289
290    def quitGame(self):
291        """Called when user requests to quit game.
292           @return: None"""
293
294        self.quit_window.show()
295
296    def toggleInventoryButton(self):
297        """Manually toggles the inventory button.
298           @return: None"""
299        button = self.hud.findChild(name="inventoryButton")
300        if button.toggled == 0:
301            button.toggled = 1
302        else:
303            button.toggled = 0
304
305    def toggleInventory(self, toggle_image=True):
306        """Displays the inventory screen
307           @return: None"""
308        if self.inventory == None:
309            self.initializeInventory()
310        self.inventory.toggleInventory(toggle_image)
311
312    def refreshReadyImages(self):
313        """Make the Ready slot images on the HUD be the same as those
314           on the inventory
315           @return: None"""
316        for ready in range(1, 5):
317            button = self.hud.findChild(name=("hudReady%d" % ready))
318            if self.inventory_storage == None :
319                origin = None
320            else:
321                origin = self.inventory_storage.getItemsInSlot('ready', ready-1)
322            if origin == None:
323                self.setImages(button, 
324                               self.inventory.slot_empty_images['ready'])
325            else:
326                self.setImages(button, origin.getInventoryThumbnail())
327
328    def setImages(self, widget, image):
329        """Set the up, down, and hover images of an Imagebutton.
330           @type widget: pychan.widget
331           @param widget: widget to set
332           @type image: string
333           @param image: image to use
334           @return: None"""
335        widget.up_image = image
336        widget.down_image = image
337        widget.hover_image = image
338
339    def initializeEvents(self):
340        """Intialize Hud events
341           @return: None"""
342        events_to_map = {}
343
344        # when we click the toggle button don't change the image
345        events_to_map["inventoryButton"] = cbwa(self.toggleInventory, False)
346        events_to_map["saveButton"] = self.saveGame
347        events_to_map["loadButton"] = self.loadGame
348
349        hud_ready_buttons = ["hudReady1", "hudReady2", \
350                             "hudReady3", "hudReady4"]
351
352        for item in hud_ready_buttons:
353            events_to_map[item] = cbwa(self.readyAction, item)
354
355        self.hud.mapEvents(events_to_map)
356
357        menu_events = {}
358        menu_events["newButton"] = self.newGame
359        menu_events["quitButton"] = self.quitGame
360        menu_events["saveButton"] = self.saveGame
361        menu_events["loadButton"] = self.loadGame
362        self.main_menu.mapEvents(menu_events)
363
364    def setOption(self, name, value):
365        """Set an option within the xml.
366           @type name: string
367           @param name: The name of the option within the xml
368           @type value: any
369           @param value: The value that the option 'name' should be set to
370           @return: None"""
371        element = self.settings.root_element.find(name)
372        if(element != None):
373            if(value != element.text):
374                element.text = str(value)
375        else:
376            print 'Setting,', name, 'does not exist!'
377   
378    def readyAction(self, ready_button):
379        """ Called when the user selects a ready button from the HUD """
380        text = "Used the item from %s" % ready_button       
381        self.addAction(text)
382       
383    def createBoxGUI(self, title, container):
384        """Creates a window to display the contents of a box
385           @type title: string
386           @param title: The title for the window
387           @param items: The box to display
388           @return: A new ContainerGui"""
389        events = {'takeAllButton':self.hideContainer,
390                  'closeButton':self.hideContainer}
391        #hide previous container if any, to avoid orphaned dialogs
392        self.hideContainer()
393
394        self.box_container = ContainerGUI(self.controller,
395                                              unicode(title), container)
396        self.box_container.gui.mapEvents(events)
397        self.box_container.showContainer()
398        return self.box_container
399
400    def hideContainer(self):
401        """Hide the container box
402           @return: None"""
403        if self.box_container:
404            self.box_container.hideContainer()
405            #TODO: Move the close() call into OpenBoxAction(). This can be done
406            # after createBoxGUI becomes a blocking call or it's otherwise
407            # possible to wait till the box GUI is closed.
408            self.box_container.container.close()
409            self.box_container = None
410
411    def createExamineBox(self, title, desc):
412        """Create an examine box. It displays some textual description of an
413           object
414           @type title: string
415           @param title: The title of the examine box
416           @type desc: string
417           @param desc: The main body of the examine box
418           @return: None"""
419        if self.examine_box is not None:
420            self.examine_box.closePopUp()
421        self.examine_box = ExaminePopup(self.engine, title, desc)
422        self.examine_box.showPopUp()
423
424    def showDialogue(self, npc):
425        """Show the NPC dialogue window
426           @type npc: actors.NonPlayerCharacter
427           @param npc: the npc that we are having a dialogue with
428           @return: None"""
429        dialogue = DialogueGUI(
430                    self.controller,
431                    npc,
432                    self.model.game_state.quest_engine,
433                    self.model.game_state.player_character)
434        dialogue.initiateDialogue()
Note: See TracBrowser for help on using the repository browser.