source: branches/active/character_customization/game/parpg/gui/dialoguegui.py @ 774

Revision 774, 6.8 KB checked in by aspidites, 9 years ago (diff)

Patch by Aspidites

  • removed shebang from all python files except launcher scripts
  • added shebang to pychan_designer
  • Property svn:eol-style set to native
Line 
1#   This file is part of PARPG.
2
3#   PARPG is free software: you can redistribute it and/or modify
4#   it under the terms of the GNU General Public License as published by
5#   the Free Software Foundation, either version 3 of the License, or
6#   (at your option) any later version.
7
8#   PARPG is distributed in the hope that it will be useful,
9#   but WITHOUT ANY WARRANTY; without even the implied warranty of
10#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11#   GNU General Public License for more details.
12
13#   You should have received a copy of the GNU General Public License
14#   along with PARPG.  If not, see <http://www.gnu.org/licenses/>.
15import logging
16
17from fife import fife
18from fife.extensions import pychan
19from fife.extensions.pychan import widgets
20
21from parpg.dialogueprocessor import DialogueProcessor
22
23def setupLogging():
24    """Set various logging parameters for this module."""
25    module_logger = logging.getLogger('dialoguegui')
26    if (__debug__):
27        module_logger.setLevel(logging.DEBUG)
28setupLogging()
29
30class DialogueGUI(object):
31    """Window that handles the dialogues."""
32    _logger = logging.getLogger('dialoguegui.DialogueGUI')
33   
34    def __init__(self, controller, npc, quest_engine, player_character):
35        self.active = False
36        self.controller = controller
37        self.dialogue_gui = pychan.loadXML("gui/dialogue.xml")
38        self.npc = npc
39        # TODO Technomage 2010-11-10: the QuestEngine should probably be
40        #     a singleton-like object, which would avoid all of this instance
41        #     handling.
42        self.quest_engine = quest_engine
43        self.player_character = player_character
44   
45    def initiateDialogue(self):
46        """Callback for starting a quest"""
47        self.active = True
48        stats_label = self.dialogue_gui.findChild(name='stats_label')
49        stats_label.text = u'Name: John Doe\nAn unnamed one'
50        events = {
51            'end_button': self.handleEnd
52        }
53        self.dialogue_gui.mapEvents(events)
54        self.dialogue_gui.show()
55        self.setNpcName(self.npc.name)
56        self.setAvatarImage(self.npc.dialogue.avatar_path)
57       
58        game_state = {'npc': self.npc, 'pc': self.player_character,
59                      'quest': self.quest_engine}
60        try:
61            self.dialogue_processor = DialogueProcessor(self.npc.dialogue,
62                                                        game_state)
63            self.dialogue_processor.initiateDialogue()
64        except (TypeError) as error:
65            self._logger.error(str(error))
66        else:
67            self.continueDialogue()
68   
69    def setDialogueText(self, text):
70        """Set the displayed dialogue text.
71           @param text: text to display."""
72        text = unicode(text)
73        speech = self.dialogue_gui.findChild(name='speech')
74        # to append text to npc speech box, uncomment the following line
75        #speech.text = speech.text + "\n-----\n" + unicode(say)
76        speech.text = text
77        self._logger.debug('set dialogue text to "{0}"'.format(text))
78   
79    def continueDialogue(self):
80        """Display the dialogue text and responses for the current
81           L{DialogueSection}."""
82        dialogue_processor = self.dialogue_processor
83        dialogue_text = dialogue_processor.getCurrentDialogueSection().text
84        self.setDialogueText(dialogue_text)
85        self.responses = dialogue_processor.continueDialogue()
86        self.setResponses(self.responses)
87   
88    def handleEntered(self, *args):
89        """Callback for when user hovers over response label."""
90        pass
91   
92    def handleExited(self, *args):
93        """Callback for when user hovers out of response label."""
94        pass
95   
96    def handleClicked(self, *args):
97        """Handle a response being clicked."""
98        response_n = int(args[0].name.replace('response', ''))
99        response = self.responses[response_n]
100        dialogue_processor = self.dialogue_processor
101        dialogue_processor.reply(response)
102        if (not dialogue_processor.in_dialogue):
103            self.handleEnd()
104        else:
105            self.continueDialogue()
106   
107    def handleEnd(self):
108        """Handle the end of the conversation being reached, either from the
109           GUI or from within the conversation itself."""
110        self.dialogue_gui.hide()
111        self.responses = []
112        self.npc.behaviour.state = 1
113        self.npc.behaviour.idle()
114        self.active = False
115   
116    def setNpcName(self, name):
117        """Set the NPC name to display on the dialogue GUI.
118           @param name: name of the NPC to set
119           @type name: basestring"""
120        name = unicode(name)
121        stats_label = self.dialogue_gui.findChild(name='stats_label')
122        try:
123            (first_name, desc) = name.split(" ", 1)
124            stats_label.text = u'Name: ' + first_name + "\n" + desc
125        except ValueError:
126            stats_label.text = u'Name: ' + name
127       
128        self.dialogue_gui.title = name
129        self._logger.debug('set NPC name to "{0}"'.format(name))
130   
131    def setAvatarImage(self, image_path):
132        """Set the NPC avatar image to display on the dialogue GUI
133           @param image_path: filepath to the avatar image
134           @type image_path: basestring"""
135        avatar_image = self.dialogue_gui.findChild(name='npc_avatar')
136        avatar_image.image = image_path
137   
138    def setResponses(self, dialogue_responses):
139        """Creates the list of clickable response labels and sets their
140           respective on-click callbacks.
141           @param responses: list of L{DialogueResponses} from the
142               L{DialogueProcessor}
143           @type responses: list of L{DialogueResponses}"""
144        choices_list = self.dialogue_gui.findChild(name='choices_list')
145        choices_list.removeAllChildren()
146        for index, response in enumerate(dialogue_responses):
147            button = widgets.Label(
148                name="response{0}".format(index),
149                text=unicode(response.text),
150                hexpand="1",
151                min_size=(100,16),
152                max_size=(490,48),
153                position_technique='center:center'
154            )
155            button.margins = (5, 5)
156            button.background_color = fife.Color(0, 0, 0)
157            button.color = fife.Color(0, 255, 0)
158            button.border_size = 0
159            button.wrap_text = 1
160            button.capture(lambda button=button: self.handleEntered(button),
161                           event_name='mouseEntered')
162            button.capture(lambda button=button: self.handleExited(button),
163                           event_name='mouseExited')
164            button.capture(lambda button=button: self.handleClicked(button),
165                           event_name='mouseClicked')
166            choices_list.addChild(button)
167            self.dialogue_gui.adaptLayout(True)
168            self._logger.debug(
169                'added {0} to response choice list'.format(response)
170            )
Note: See TracBrowser for help on using the repository browser.