| 1 |
# -*- coding: utf-8 -*- |
| 2 |
# CFDialog.py - Dialog helper class |
| 3 |
# |
| 4 |
# Copyright (C) 2007 Yann Chachkoff |
| 5 |
# |
| 6 |
# This program is free software; you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation; either version 2 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program; if not, write to the Free Software |
| 18 |
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. |
| 19 |
# |
| 20 |
# The author can be reached via e-mail at [email protected] |
| 21 |
|
| 22 |
# What is CFDialog? |
| 23 |
# ================= |
| 24 |
# |
| 25 |
# This is a small set of utility classes, to help you create complex dialogs. |
| 26 |
# It is made for those who do not want to bother about complex programming, |
| 27 |
# but just want to make a few dialogs that are better than the @match system |
| 28 |
# used in the server. |
| 29 |
# You will not normally use this directly, but will instead want to call |
| 30 |
# dialog/npc_dialog.py which will handle most common uses for dialogs. |
| 31 |
# |
| 32 |
# How to use CFDialog |
| 33 |
# =================== |
| 34 |
# |
| 35 |
# First, create a script that imports the DialogRule and Dialog classes. Add |
| 36 |
# the following line at the beginning of your script: |
| 37 |
# |
| 38 |
# from CFDialog import DialogRule, Dialog |
| 39 |
# |
| 40 |
# Next, build the dialog by creating a sequence of several rules made up of |
| 41 |
# keywords, answers, preconditions, and postconditions. |
| 42 |
# |
| 43 |
# - Keywords are what the rule answers to. For example, if you want a rule to |
| 44 |
# trigger when the player says "hi", then "hi" must appear in the keyword |
| 45 |
# list. One or more keywords are specified in a string list in the form |
| 46 |
# ["keyword1", "keyword2" ...]. A "*" character is a special keyword that |
| 47 |
# means: "match everything", and is useful to create rules that provide |
| 48 |
# generic answers no matter what the player character says. |
| 49 |
# |
| 50 |
# NOTE: Like the @match system, CFDialog converts both keywords and the |
| 51 |
# things the player says to lowercase before checking for a match, |
| 52 |
# so it is never necessary to include multiple keywords that only |
| 53 |
# differ in case. |
| 54 |
# |
| 55 |
# - Answers are what the rule will respond, or say, to the player when it is |
| 56 |
# triggered. This is what the NPC replies to the player. Answers are stored |
| 57 |
# in a list of one or more strings in the form ["Answer1", "Answer2" ...]. |
| 58 |
# When there is more than one answer in that list, each time the rule is |
| 59 |
# triggered, a single random reply will be selected from the list. |
| 60 |
# |
| 61 |
# NOTE: Answers may contain line breaks. To insert one, use "\n". |
| 62 |
# |
| 63 |
# - Preconditions are checks that must pass in order for a rule to be |
| 64 |
# triggered. The checks that can be used are to be found in dialog/pre/*.py |
| 65 |
# Each file describes how to use the check in question. |
| 66 |
# |
| 67 |
# - Postconditions are changes that should be made to the player and/or the |
| 68 |
# game world after the rule triggers. The effects that are available are to |
| 69 |
# be found in dialog/post/*.py Each file describes how to use the effect in |
| 70 |
# question. |
| 71 |
# |
| 72 |
# - Replies are what the player will be informed of possible replies. |
| 73 |
# Each should be an array in the form [word, text, type], with |
| 74 |
# 'word' the actual word the player should say, 'text' the text the player |
| 75 |
# will actually say if she says the word, 'type' an optional integer |
| 76 |
# to specify if the text is a regular sentence (0), a reply (1) or a question |
| 77 |
# to ask (2). |
| 78 |
# |
| 79 |
# |
| 80 |
# Once the rules are all defined, assemble them into a dialog. Each dialog |
| 81 |
# involves somebody who triggers it, somebody who answers, and also a unique |
| 82 |
# name so it cannot be confused with other dialogs. Typically, the "one who |
| 83 |
# triggers" will be the player, and the "one who answers" is an NPC the player |
| 84 |
# was taking to. You are free to choose whatever you want for the dialog name, |
| 85 |
# as long as it contains no whitespace or special characters, and as long as |
| 86 |
# it is not used by another dialog. You can then add the rules you created to |
| 87 |
# the dialog. Rules are parsed in a given order, so you must add the most |
| 88 |
# generic answer last. |
| 89 |
# |
| 90 |
# http://wiki.metalforge.net/doku.php/cfdialog?s=cfdialog#a_simple_example |
| 91 |
# |
| 92 |
# A more complex example |
| 93 |
# ====================== |
| 94 |
# |
| 95 |
# A ./misc/npc_dialog.py script has been written that uses CFDialog, but |
| 96 |
# allows the dialog data to be written in JSON format. |
| 97 |
# This also permits the inclusion of additional files to take in more rules |
| 98 |
# (this is mostly useful when you have a character who has some specific lines |
| 99 |
# of dialog but also some other lines that are shared with other characters |
| 100 |
# - the character can reference their specific lines of dialog directly and |
| 101 |
# include the general ones. |
| 102 |
# |
| 103 |
# ../scorn/kar/gork.msg is an example that uses multiple keywords and multiple |
| 104 |
# precondition values. Whereas the above example has a linear and predicable |
| 105 |
# conversation paths, note how a conversation with Gork can fork, merge, and |
| 106 |
# loop back on itself. The example also illustrates how CFDialog can allow |
| 107 |
# dialogs to affect how other NPCs react to a player. ../scorn/kar/mork.msg |
| 108 |
# is a completely different dialog, but it is part of a quest that requires |
| 109 |
# the player to interact with both NPCs in a specific way before the quest |
| 110 |
# prize can be obtained. With the old @match system, once the player knew |
| 111 |
# the key words, he could short-circuit the conversation the map designer |
| 112 |
# intended to occur. CFDialog constrains the player to follow the proper |
| 113 |
# conversation thread to qualify to receive the quest reward. |
| 114 |
# |
| 115 |
# Debugging |
| 116 |
# ========= |
| 117 |
# |
| 118 |
# When debugging, if changes are made to this file, the Crossfire Server must |
| 119 |
# be restarted for it to register the changes. |
| 120 |
|
| 121 |
import Crossfire |
| 122 |
import string |
| 123 |
import random |
| 124 |
import sys |
| 125 |
import os |
| 126 |
import CFItemBroker |
| 127 |
|
| 128 |
class DialogRule: |
| 129 |
def __init__(self, keywords, presemaphores, messages, postsemaphores, suggested_response = None): |
| 130 |
self.__keywords = keywords |
| 131 |
self.__presems = presemaphores |
| 132 |
self.__messages = messages |
| 133 |
self.__postsems = postsemaphores |
| 134 |
self.__suggestions = suggested_response |
| 135 |
self.__prefunction = None |
| 136 |
|
| 137 |
# The keyword is a string. Multiple keywords may be defined in the string |
| 138 |
# by delimiting them with vertical bar (|) characters. "*" is a special |
| 139 |
# keyword that matches anything. |
| 140 |
def getKeyword(self): |
| 141 |
return self.__keywords |
| 142 |
|
| 143 |
# Messages are stored in a list of strings. One or more messages may be |
| 144 |
# defined in the list. If more than one message is present, a random |
| 145 |
# string is returned. |
| 146 |
def getMessage(self): |
| 147 |
msg = self.__messages |
| 148 |
l = len(msg) |
| 149 |
r = random.randint(0, l - 1) |
| 150 |
return msg[r] |
| 151 |
|
| 152 |
# Return the preconditions of a rule. They are a list of one or more lists |
| 153 |
# that specify a flag name to check, and one or more acceptable values it |
| 154 |
# may have in order to allow the rule to be triggered. |
| 155 |
def getPreconditions(self): |
| 156 |
return self.__presems |
| 157 |
|
| 158 |
# Return the postconditions for a rule. They are a list of one or more |
| 159 |
# lists that specify a flag to be set in the player file and what value it |
| 160 |
# should be set to. |
| 161 |
def getPostconditions(self): |
| 162 |
return self.__postsems |
| 163 |
|
| 164 |
# Return the possible responses to this rule |
| 165 |
# This is when a message is sent. |
| 166 |
def getSuggests(self): |
| 167 |
return self.__suggestions |
| 168 |
|
| 169 |
# Return a possible pre function, that will be called to ensure the rule matches. |
| 170 |
def getPreFunction(self): |
| 171 |
return self.__prefunction |
| 172 |
|
| 173 |
# Define a prefunction that will be called to match the rule. |
| 174 |
def setPreFunction(self, function): |
| 175 |
self.__prefunction = function |
| 176 |
|
| 177 |
# This is a subclass of the generic dialog rule that we use for determining whether to |
| 178 |
# 'include' additional rules. |
| 179 |
class IncludeRule(DialogRule): |
| 180 |
def __init__(self, presemaphores): |
| 181 |
DialogRule.__init__(self, None, presemaphores, None, None, None ) |
| 182 |
|
| 183 |
class Dialog: |
| 184 |
# A character is the source that supplies keywords that drive the dialog. |
| 185 |
# The speaker is the NPC that responds to the keywords. A location is an |
| 186 |
# unique identifier that is used to distinguish dialogs from each other. |
| 187 |
def __init__(self, character, speaker, location): |
| 188 |
self.__character = character |
| 189 |
self.__location = location |
| 190 |
self.__speaker = speaker |
| 191 |
self.__rules = [] |
| 192 |
|
| 193 |
# Create rules of the DialogRule class that define dialog flow. An index |
| 194 |
# defines the order in which rules are processed. FIXME: addRule could |
| 195 |
# very easily create the index. It is unclear why this mundane activity |
| 196 |
# is left for the dialog maker. |
| 197 |
def addRule(self, rule, index): |
| 198 |
self.__rules.insert(index, rule) |
| 199 |
|
| 200 |
# A function to call when saying something to an NPC to elicit a response |
| 201 |
# based on defined rules. It iterates through the rules and determines if |
| 202 |
# the spoken text matches a keyword. If so, the rule preconditions and/or |
| 203 |
# prefunctions are checked. If all conditions they define are met, then |
| 204 |
# the NPC responds, and postconditions, if any, are set. Postfunctions |
| 205 |
# also execute if present. |
| 206 |
# some variable substitution is done on the message here, $me and $you |
| 207 |
# are replaced by the names of the npc and the player respectively |
| 208 |
def speak(self, msg): |
| 209 |
# query the animation system in case the NPC is playing an animation |
| 210 |
if self.__speaker.Event(self.__speaker, self.__speaker, "query_object_is_animated", 1): |
| 211 |
return 0 |
| 212 |
|
| 213 |
key = self.uniqueKey() |
| 214 |
replies = None |
| 215 |
if key in Crossfire.GetPrivateDictionary(): |
| 216 |
replies = Crossfire.GetPrivateDictionary()[key] |
| 217 |
Crossfire.GetPrivateDictionary()[key] = None |
| 218 |
|
| 219 |
for rule in self.__rules: |
| 220 |
if self.isAnswer(msg, rule.getKeyword()) == 1: |
| 221 |
if self.matchConditions(rule) == 1: |
| 222 |
message = rule.getMessage() |
| 223 |
message = message.replace('$me', self.__speaker.QueryName()) |
| 224 |
message = message.replace('$you', self.__character.QueryName()) |
| 225 |
|
| 226 |
Crossfire.NPCSay(self.__speaker, message) |
| 227 |
if rule.getSuggests() != None: |
| 228 |
for reply in rule.getSuggests(): |
| 229 |
Crossfire.AddReply(reply[0], reply[1]) |
| 230 |
Crossfire.GetPrivateDictionary()[key] = rule.getSuggests() |
| 231 |
self.setConditions(rule) |
| 232 |
|
| 233 |
# change the player's text if found |
| 234 |
if replies != None: |
| 235 |
for reply in replies: |
| 236 |
if reply[0] == msg: |
| 237 |
type = Crossfire.ReplyType.SAY |
| 238 |
if len(reply) > 2: |
| 239 |
type = int(reply[2]) |
| 240 |
Crossfire.SetPlayerMessage(reply[1], type) |
| 241 |
break |
| 242 |
|
| 243 |
return 0 |
| 244 |
return 1 |
| 245 |
|
| 246 |
def uniqueKey(self): |
| 247 |
return self.__location + '_' + self.__character.QueryName() |
| 248 |
|
| 249 |
# Determine if the message sent to an NPC matches a string in the keyword |
| 250 |
# list. The match check is case-insensitive, and succeeds if a keyword |
| 251 |
# string is found in the message. This means that the keyword string(s) |
| 252 |
# only need to be a substring of the message in order to trigger a reply. |
| 253 |
def isAnswer(self, msg, keywords): |
| 254 |
for ckey in keywords: |
| 255 |
if ckey == "*" or msg.lower().find(ckey.lower()) != -1: |
| 256 |
return 1 |
| 257 |
return 0 |
| 258 |
|
| 259 |
# Check the preconditions specified in rule have been met. Preconditions |
| 260 |
# are lists of one or more conditions to check. Each condition specifies |
| 261 |
# a check to perform and the options it should act on. |
| 262 |
# separate files are used for each type of check. |
| 263 |
def matchConditions(self, rule): |
| 264 |
character = self.__character |
| 265 |
location = self.__location |
| 266 |
speaker = self.__speaker |
| 267 |
verdict = True |
| 268 |
for condition in rule.getPreconditions(): |
| 269 |
action = condition[0] |
| 270 |
args = condition[1:] |
| 271 |
script_args = {'args': args, 'character': character, 'location': location, 'action': action, 'self': self, 'verdict': verdict} |
| 272 |
path = os.path.join(Crossfire.DataDirectory(), Crossfire.MapDirectory(), 'python/dialog/pre/', action + '.py') |
| 273 |
if os.path.isfile(path): |
| 274 |
try: |
| 275 |
exec(open(path).read(), {}, script_args) |
| 276 |
verdict = script_args['verdict'] |
| 277 |
except Exception as ex: |
| 278 |
Crossfire.Log(Crossfire.LogError, "CFDialog: Failed to evaluate condition %s: %s." % (condition, str(ex))) |
| 279 |
verdict = False |
| 280 |
if verdict == False: |
| 281 |
return 0 |
| 282 |
else: |
| 283 |
Crossfire.Log(Crossfire.LogError, "CFDialog: Pre Block called with unknown action %s." % action) |
| 284 |
return 0 |
| 285 |
|
| 286 |
if rule.getPreFunction() != None: |
| 287 |
if rule.getPreFunction()(self.__character, rule) != True: |
| 288 |
return 0 |
| 289 |
return 1 |
| 290 |
|
| 291 |
|
| 292 |
# If a rule triggers, this function goes through each condition and runs the file that handles it. |
| 293 |
def setConditions(self, rule): |
| 294 |
character = self.__character |
| 295 |
location = self.__location |
| 296 |
speaker = self.__speaker |
| 297 |
|
| 298 |
for condition in rule.getPostconditions(): |
| 299 |
Crossfire.Log(Crossfire.LogDebug, "CFDialog: Trying to apply %s." % condition) |
| 300 |
action = condition[0] |
| 301 |
args = condition[1:] |
| 302 |
path = os.path.join(Crossfire.DataDirectory(), Crossfire.MapDirectory(), 'python/dialog/post/', action + '.py') |
| 303 |
if os.path.isfile(path): |
| 304 |
try: |
| 305 |
exec(open(path).read()) |
| 306 |
except: |
| 307 |
Crossfire.Log(Crossfire.LogError, "CFDialog: Failed to set post-condition %s." %condition) |
| 308 |
else: |
| 309 |
Crossfire.Log(Crossfire.LogError, "CFDialog: Post Block called with unknown action %s." % action) |
| 310 |
|
| 311 |
|
| 312 |
# Search the player file for a particular flag, and if it exists, return |
| 313 |
# its value. Flag names are combined with the unique dialog "location" |
| 314 |
# identifier, and are therefore are not required to be unique. This also |
| 315 |
# prevents flags from conflicting with other non-dialog-related contents |
| 316 |
# in the player file. |
| 317 |
def getStatus(self, key): |
| 318 |
character_status=self.__character.ReadKey("dialog_"+self.__location) |
| 319 |
if character_status == "": |
| 320 |
return "0" |
| 321 |
pairs=character_status.split(";") |
| 322 |
for i in pairs: |
| 323 |
subpair=i.split(":") |
| 324 |
if subpair[0] == key: |
| 325 |
return subpair[1] |
| 326 |
return "0" |
| 327 |
|
| 328 |
# Store a flag in the player file and set it to the specified value. Flag |
| 329 |
# names are combined with the unique dialog "location" identifier, and are |
| 330 |
# therefore are not required to be unique. This also prevents flags from |
| 331 |
# conflicting with other non-dialog-related contents in the player file. |
| 332 |
def setStatus(self, key, value): |
| 333 |
if value == "*": |
| 334 |
return |
| 335 |
ishere = 0 |
| 336 |
finished = "" |
| 337 |
character_status = self.__character.ReadKey("dialog_"+self.__location) |
| 338 |
if character_status != "": |
| 339 |
pairs = character_status.split(";") |
| 340 |
for i in pairs: |
| 341 |
subpair = i.split(":") |
| 342 |
if subpair[0] == key: |
| 343 |
subpair[1] = value |
| 344 |
ishere = 1 |
| 345 |
if finished != "": |
| 346 |
finished = finished+";" |
| 347 |
finished = finished + subpair[0] + ":" + subpair[1] |
| 348 |
if ishere == 0: |
| 349 |
if finished != "": |
| 350 |
finished = finished + ";" |
| 351 |
finished = finished + key + ":" + value |
| 352 |
self.__character.WriteKey("dialog_" + self.__location, finished, 1) |
| 353 |
|
| 354 |
# Search the NPC for a particular flag, and if it exists, return |
| 355 |
# its value. Flag names are combined with the unique dialog "location" |
| 356 |
# identifier and the player's name, and are therefore are not required |
| 357 |
# to be unique. This also prevents flags from conflicting with other |
| 358 |
# non-dialog-related contents in the NPC. |
| 359 |
def getNPCStatus(self, key): |
| 360 |
npc_status=self.__speaker.ReadKey("dialog_"+self.__location + "_" + self.__character.Name) |
| 361 |
if npc_status == "": |
| 362 |
return "0" |
| 363 |
pairs=npc_status.split(";") |
| 364 |
for i in pairs: |
| 365 |
subpair=i.split(":") |
| 366 |
if subpair[0] == key: |
| 367 |
return subpair[1] |
| 368 |
return "0" |
| 369 |
|
| 370 |
# Store a flag in the NPC and set it to the specified value. Flag |
| 371 |
# names are combined with the unique dialog "location" identifier |
| 372 |
# and the player's name, and are therefore are not required to be unique. |
| 373 |
# This also prevents flags from conflicting with other non-dialog-related |
| 374 |
# contents in the player file. |
| 375 |
def setNPCStatus(self, key, value): |
| 376 |
if value == "*": |
| 377 |
return |
| 378 |
ishere = 0 |
| 379 |
finished = "" |
| 380 |
npc_status = self.__speaker.ReadKey("dialog_"+self.__location + "_" + self.__character.Name) |
| 381 |
if npc_status != "": |
| 382 |
pairs = npc_status.split(";") |
| 383 |
for i in pairs: |
| 384 |
subpair = i.split(":") |
| 385 |
if subpair[0] == key: |
| 386 |
subpair[1] = value |
| 387 |
ishere = 1 |
| 388 |
if finished != "": |
| 389 |
finished = finished+";" |
| 390 |
finished = finished + subpair[0] + ":" + subpair[1] |
| 391 |
if ishere == 0: |
| 392 |
if finished != "": |
| 393 |
finished = finished + ";" |
| 394 |
finished = finished + key + ":" + value |
| 395 |
self.__speaker.WriteKey("dialog_" + self.__location + "_" + self.__character.Name, finished, 1) |