source: trunk/game/scripts/gui/dialoguegui.py @ 680

Revision 680, 6.5 KB checked in by technomage, 9 years ago (diff)

Patch by Technomage

  • Updated/wrote code documentation for the core dialogue subsystem modules dialogue.py, dialogueengine.py, dialogueactions.py, and dialogueparsers.py.
  • Updated/created flowcharts and UML diagrams explaining the new DialogueEngine? and how it functions.
  • Made a few minor changes to the dialoguegui.py module to make the class logger less visible.
  • Removed the "this is a sample dialogue file" crud from the old_man.yaml test dialogue file.
  • 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/>.
17import logging
18
19from fife import fife
20from fife.extensions import pychan
21from fife.extensions.pychan import widgets
22
23from scripts.dialogueengine import DialogueEngine
24
25def setup_logging():
26    """Set various logging parameters for this module."""
27    module_logger = logging.getLogger('dialoguegui')
28    if (__debug__):
29        module_logger.setLevel(logging.DEBUG)
30setup_logging()
31
32class DialogueGUI(object):
33    """Window that handles the dialogues."""
34    _logger = logging.getLogger('dialoguegui.DialogueGUI')
35   
36    def __init__(self, controller, npc, quest_engine, player_character):
37        self.active = False
38        self.controller = controller
39        self.dialogue_gui = pychan.loadXML("gui/dialogue.xml")
40        self.npc = npc
41        # TODO Technomage 2010-11-10: the QuestEngine should probably be
42        #     a singleton-like object, which would avoid all of this instance
43        #     handling.
44        self.quest_engine = quest_engine
45        self.player_character = player_character
46   
47    def initiateDialogue(self):
48        """Callback for starting a quest"""
49        self.active = True
50        stats_label = self.dialogue_gui.findChild(name='stats_label')
51        stats_label.text = u'Name: John Doe\nAn unnamed one'
52        events = {
53            'end_button': self.handleEnd
54        }
55        self.dialogue_gui.mapEvents(events)
56        self.dialogue_gui.show()
57        self.setNpcName(self.npc.name)
58        self.setAvatarImage(self.npc.dialogue.avatar_path)
59       
60        game_state = {'npc': self.npc, 'pc': self.player_character,
61                      'quest': self.quest_engine}
62        DialogueEngine.initiateDialogue(self.npc.dialogue, game_state)
63        self.continueDialogue()
64   
65    def setDialogueText(self, text):
66        """Set the displayed dialogue text.
67           @param text: text to display."""
68        text = unicode(text)
69        speech = self.dialogue_gui.findChild(name='speech')
70        # to append text to npc speech box, uncomment the following line
71        #speech.text = speech.text + "\n-----\n" + unicode(say)
72        speech.text = text
73        self._logger.debug('set dialogue text to "{0}"'.format(text))
74   
75    def continueDialogue(self):
76        """Display the dialogue text and responses for the current
77           L{DialogueSection}."""
78        dialogue_text = DialogueEngine.getCurrentDialogueSection().text
79        self.setDialogueText(dialogue_text)
80        self.responses = DialogueEngine.continueDialogue()
81        self.setResponses(self.responses)
82   
83    def handleEntered(self, *args):
84        """Callback for when user hovers over response label."""
85        pass
86   
87    def handleExited(self, *args):
88        """Callback for when user hovers out of response label."""
89        pass
90   
91    def handleClicked(self, *args):
92        """Handle a response being clicked."""
93        response_n = int(args[0].name.replace('response', ''))
94        response = self.responses[response_n]
95        DialogueEngine.reply(response)
96        if (not DialogueEngine.in_dialogue):
97            self.handleEnd()
98        else:
99            self.continueDialogue()
100   
101    def handleEnd(self):
102        """Handle the end of the conversation being reached, either from the
103           GUI or from within the conversation itself."""
104        self.dialogue_gui.hide()
105        self.responses = []
106        self.npc.behaviour.state = 1
107        self.npc.behaviour.idle()
108        self.active = False
109   
110    def setNpcName(self, name):
111        """Set the NPC name to display on the dialogue GUI.
112           @param name: name of the NPC to set
113           @type name: basestring"""
114        name = unicode(name)
115        stats_label = self.dialogue_gui.findChild(name='stats_label')
116        try:
117            (first_name, desc) = name.split(" ", 1)
118            stats_label.text = u'Name: ' + first_name + "\n" + desc
119        except ValueError:
120            stats_label.text = u'Name: ' + name
121       
122        self.dialogue_gui.title = name
123        self._logger.debug('set NPC name to "{0}"'.format(name))
124   
125    def setAvatarImage(self, image_path):
126        """Set the NPC avatar image to display on the dialogue GUI
127           @param image_path: filepath to the avatar image
128           @type image_path: basestring"""
129        avatar_image = self.dialogue_gui.findChild(name='npc_avatar')
130        avatar_image.image = image_path
131   
132    def setResponses(self, dialogue_responses):
133        """Creates the list of clickable response labels and sets their
134           respective on-click callbacks.
135           @param responses: list of L{DialogueResponses} from the
136               L{DialogueEngine}
137           @type responses: list of L{DialogueResponses}"""
138        choices_list = self.dialogue_gui.findChild(name='choices_list')
139        choices_list.removeAllChildren()
140        for index, response in enumerate(dialogue_responses):
141            button = widgets.Label(
142                name="response{0}".format(index),
143                text=unicode(response.text),
144                hexpand="1",
145                min_size=(100,16),
146                max_size=(490,48),
147                position_technique='center:center'
148            )
149            button.margins = (5, 5)
150            button.background_color = fife.Color(0, 0, 0)
151            button.color = fife.Color(0, 255, 0)
152            button.border_size = 0
153            button.wrap_text = 1
154            button.capture(lambda button=button: self.handleEntered(button),
155                           event_name='mouseEntered')
156            button.capture(lambda button=button: self.handleExited(button),
157                           event_name='mouseExited')
158            button.capture(lambda button=button: self.handleClicked(button),
159                           event_name='mouseClicked')
160            choices_list.addChild(button)
161            self.dialogue_gui.adaptLayout(True)
162            self._logger.debug(
163                'added {0} to response choice list'.format(response)
164            )
Note: See TracBrowser for help on using the repository browser.