Código Python:
Ver original# -*- coding: utf-8 -*-
class Answer(object):
def __init__(self, text):
self.text = text
def __hash__(self):
return hash(self.text)
def __eq__(self, other):
return self.text == other
def __unicode__(self):
return u'%s' % (self.text,)
class Question(object):
def __init__(self, text, possible_answers):
self.text = text
self.possible_answers = possible_answers
def get_next_question(self, answer):
if self.possible_answers:
return self.possible_answers.get(answer)
def __unicode__(self):
s = u'{0}\n'.format(self.text)
if self.possible_answers:
s += u'\n'.join(u' ' + unicode(i) for i in self.possible_answers.keys())
return s
dialog = Question(u'¿Eres hombre o mujer?',
{
Answer('hombre'): Question(u'¿Te llamas Ramón?',
{
Answer('si'): Question(u'Hola Ramón', None),
Answer('no'): Question(u'Deberías de llarte Ramón', None),
Answer('no se'): Question(u'¿Como no puedes saber?', None)
}),
Answer('mujer'): Question(u'¿Te llamas Maria?',
{
Answer('si'): Question(u'Hola Maria :D', None),
Answer('no'): Question(u'Deberías llamarte Maria', None),
Answer('no se'): Question('¿Como no puedes saber tu nombre?', None),
})
}
)
question = dialog
while question:
print unicode(question)
if question.possible_answers is None:
break
answer = Answer(raw_input('> '))
question = question.get_next_question(answer)
La verdad es sorprendentemente fácil de modelar con diccionarios.