04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

464 CHAPTER 24 ■ PROJECT 5: A VIRTUAL TEA PARTY<br />

possibly with the session itself as an added argument (so do_say would know who did the<br />

talking). Here is a simple implementation, with an added method to express that a command<br />

is unknown:<br />

class CommandHandler:<br />

"""<br />

Simple command handler similar to cmd.Cmd from the standard<br />

library.<br />

"""<br />

def unknown(self, session, cmd):<br />

session.push('Unknown command: %s\r\n' % cmd)<br />

def handle(self, session, line):<br />

if not line.strip(): return<br />

parts = line.split(' ', 1)<br />

cmd = parts[0]<br />

try: line = parts[1].strip()<br />

except IndexError: line = ''<br />

meth = getattr(self, 'do_'+cmd, None)<br />

if callable(meth):<br />

meth(session, line)<br />

else:<br />

self.unknown(session, cmd)<br />

The use of getattr in this class is similar to that in Chapter 20.<br />

With the basic command handling out of the way, you need to define some actual<br />

commands—and which commands are available (and what they do) should depend on the<br />

current state of the session. How do you represent that state?<br />

Rooms<br />

Each state can be represented by a custom command handler. This is easily combined with the<br />

standard notion of chat rooms (or locations in a MUD). Each room is a CommandHandler with its<br />

own specialized commands. In addition, it should keep track of which users (sessions) are<br />

currently inside it. Here is a generic superclass for all your rooms:<br />

class EndSession(Exception): pass<br />

class Room(CommandHandler):<br />

"""<br />

A generic environment which may contain one or more users<br />

(sessions). It takes care of basic command handling and<br />

broadcasting.<br />

"""

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!