Thursday, June 14, 2012

Bite-sized Twisted: A simple, working program

There's an asynchronous, single-player Bomberman clone at the end of this post.

Quick overview

Very quickly, these are the components of the game:

  1. players (the things running around dropping bombs)
  2. bombs
  3. fire (from the bombs)
  4. the game board
This post will build them in the reverse order: the board, fire, bombs then players. I'm going to skim through the normal Python, only emphasizing the points where the Twisted library does something neat.

Coordinates throughout the program are x,y tuples (e.g. (3,2)).

Big fat disclaimer

I'm not a game programmer. I've previously written simple games like Tetris. I know there are cool optimizations that game makers use (for dealing with lag and minimizing network traffic and such). I'm not going to prematurely optimize. I will accept good patches though :)

Da board

The game board will be divided into layers. At the bottom is the bottom layer... which, for now, consists of identical background tiles. One layer up is the layer of destructable and indestructable tiles. We'll call these the foreground tiles. Here's how we'll implement the foreground tiles and a method to generate a basic board:

EMPTY = 0
HARD = 1
SOFT = 2

class Board:

def __init__(self):
self.fg_tiles = {}

def generate(self, width, height):
for x in xrange(width):
for y in xrange(height):
coord = (x,y)
if (x % 2) and (y % 2):
self.fg_tiles[coord] = HARD
else:
self.fg_tiles[coord] = SOFT
board1.py

EMPTY means there's no foreground tile, SOFT tiles are destructable and HARD tiles are indestructable. A basic 5 x 5 board looks like this:

+-----+
|:::::|
|:#:#:|
|:::::|
|:#:#:|
|:::::|
+-----+

: = SOFT
# = HARD

The keys for fg_tiles are coordinate tuples (e.g. (4,5)). There's nothing asynchronous or Twisted-y about that code. Let's move along.

Start the fire!

Generally, an exploding bomb will make fire appear on the board. Once a bomb makes the fire, however, the bomb has nothing more to do with it. Let's implement the post-bomb portion of the fire.

We'll keep track of fires in a dictionary on Board. The keys into the fires dictionary are x,y coordinate tuples:

    def __init__(self):
self.fg_tiles = {}
self.fires = {}
fire1.py

Fires have an asynchronous component: they ignite, burn for some amount of time, then die. We'll use reactor.callLater to do the "burn for some amount time" bit and use a Deferred to signal to the fire-starter when the fire is extinguished:

from twisted.internet import reactor
from twisted.internet.defer import Deferred

...

def startFire(self, coord, burntime):
defer = Deferred()

# Put the fire out after a bit.
reactor.callLater(burntime, self.stopFire, coord)

# Record that there's a fire on the board.
self.fires[coord] = defer

# Destroy whatever tile is here
self.fg_tiles[coord] = EMPTY
return defer


def stopFire(self, coord):
defer = self.fires[coord]

# Remove the fire from the board
del self.fires[coord]

# notify people who care that the fire is out
defer.callback(None)
fire2.py

The Deferred is created, stored in the fires dictionary, then returned to the caller (they can add callbacks to it if they want). Also, the tile at that coordinate is "destroyed" (made EMPTY).

The callLater calls stopFire, which remove the entry in the fires dictionary and calls back the stored Deferred. That the Deferred is called back with None simply means that any attached callbacks will be passed None as the first argument.

Let's talk about threading. If you've done threaded programming, you may be cringing over the blatant disregard with which global variables are accessed (self.fires and self.fg_tiles) without proper locking mechanisms to guarantee atomicity. This code, though, isn't threaded. startFire will run from beginning to end, sequentially, without any other code executing. Breathe well! This is Twisted!

Restart the fire!

It's possible that an exploding bomb will ignite a tile that is already burning. With fire2.py, that scenario is a problem because the second fire will overwrite the first fire's entry in the fires dict. Then the first fire's stopFire call will delete the entry from fires dict so that when the second fire's stopFire happens, a KeyError is raised. From the players' perspective, the second fire will be prematurely extinguished.

So instead of having two fires burning in the same tile, if a second fire ignites, let's extend the existing fire's time. We can do this with the reset method of the thing returned by callLater (it's called a DelayedCall and you can read the docs here):

    def startFire(self, coord, burntime):
# Is there already a fire on this tile?
if coord in self.fires:
defer, call = self.fires[coord]
# Stoke the fire
call.reset(burntime)
else:
defer = Deferred()
# Put the fire out after a bit.
call = reactor.callLater(burntime, self.stopFire, coord)

# Record that there's a fire on the board.
self.fires[coord] = (defer, call)

# Destroy whatever tile is here
self.fg_tiles[coord] = EMPTY
return defer


def stopFire(self, coord):
d, call = self.fires[coord]

# Remove the fire from the board
del self.fires[coord]

# notify people who care that the fire is out
d.callback(None)
fire3.py

Now a second call to start a fire on a tile will prolong the burning without glitches. Anyone waiting on the Deferred returned by the first call will just wait a little longer.

Bomb, bomb, bomb

Now that we can start fires at will, let's add bombs to the fray. We'll track bombs similarly to fires:

    def __init__(self):
self.fg_tiles = {}
self.bombs = {}
self.fires = {}
bomb1.py

And the code for dropping and detonating bombs is very similar to that for igniting and extinguishing fires (with some extra in detonateBomb to account for the different kinds of tiles and board boundaries, etc...):

    dft_burn = 1


def dropBomb(self, coord, fuse, size):
# Set the bomb up to explode later
defer = Deferred()
call = self._reactor.callLater(fuse, self.detonateBomb, coord)

# Place the bomb on the board
self.bombs[coord] = (defer, call, size)
return defer


def detonateBomb(self, coord):
defer, call, size = self.bombs[coord]

# Remove the bomb from the board
del self.bombs[coord]

# Let people who care know that the bomb has exploded
defer.callback(None)

# Start the fires up, down, left and right
self.startFire(coord, self.dft_burn)
directions = [
(0, -1),
(0, 1),
(-1, 0),
(1, 0),
]
for i in xrange(1, size+1):
for d in list(directions):
target = (coord[0]+(d[0]*i), coord[1]+(d[1]*i))
try:
tile = self.fg_tiles[target]
except KeyError:
continue
if tile == HARD:
directions.remove(d)
continue
if target in self.bombs:
directions.remove(d)
if tile == SOFT:
directions.remove(d)
self.startFire(target, self.dft_burn)
bomb2.py

In Bomberman, exploding bombs cause other bombs to explode. We can incorporate that by changing startFire (changed lines are highlighted):

    def startFire(self, coord, burntime):
# Is there already a fire on this tile?
if coord in self.fires:
defer, call = self.fires[coord]
# Stoke the fire
call.reset(burntime)
else:
defer = Deferred()
# Put the fire out after a bit.
call = reactor.callLater(burntime, self.stopFire, coord)

# Record that there's a fire on the board.
self.fires[coord] = (defer, call)

# Destroy whatever tile is here
self.fg_tiles[coord] = EMPTY

# Is there a bomb to detonate here?
if coord in self.bombs:
self.detonateBomb(coord)
return defer
bomb3.py

But now what happens when the bomb's original fuse expires? It will cause problems trying to re-explode an exploded bomb. So, let's cancel the original fuse using the cancel() method of the DelayedCall:

    def detonateBomb(self, coord):
defer, call, size = self.bombs[coord]

# Remove the bomb from the board
del self.bombs[coord]

# Let people who care know that the bomb has exploded
defer.callback(None)

# Premature explosion?
if call.active():
call.cancel()

# Start the fires up, down, left and right
self.startFire(coord, self.dft_burn)
...
bomb4.py

Now the fuse is canceled on prematurely ignited bombs.

Merely a pawn

I'm using the term pawn to represent the thing that moves around on the board. We'll keep track of Pawns in a set rather than a dictionary because multiple Pawns can be at the same location at once.

class Board:

def __init__(self):
self.fg_tiles = {}
self.bombs = {}
self.fires = {}
self.pawns = set()
pawn1.py

Pawns have various attributes, as shown:

class Pawn:

bombs = 1
flame_size = 1
fuse = 2.0
alive = True

def __init__(self, name=None):
self.name = name
pawn2.py

First things first: Pawns need to know how to die.

    def kill(self):
self.alive = False
pawn3.py

We need to be able to put Pawns on the Board:

class Board:
...
def insertPawn(self, coord, pawn):
# Let the Board and Pawn know about each other
pawn.board = self
pawn.loc = coord
self.pawns.add(pawn)

# Clear a space for the Pawn
self.fg_tiles[pawn.loc] = EMPTY
directions = [
(1,0),
(-1,0),
(0,1),
(0,-1),
]
for d in directions:
target = (pawn.loc[0]+d[0], pawn.loc[1]+d[1])
if target in self.fg_tiles:
self.fg_tiles[target] = EMPTY


class Pawn:
...
board = None
loc = None
pawn4.py

A fire + a Pawn = death for the Pawn:

    def startFire(self, coord, burntime):
# Is there already a fire on this tile?
if coord in self.fires:
defer, call = self.fires[coord]
# Stoke the fire
call.reset(burntime)
else:
defer = Deferred()
# Put the fire out after a bit.
call = reactor.callLater(burntime, self.stopFire, coord)

# Record that there's a fire on the board.
self.fires[coord] = (defer, call)

# Destroy whatever tile is here
self.fg_tiles[coord] = EMPTY

# Is there a bomb to detonate here?
if coord in self.bombs:
self.detonateBomb(coord)

# Any pawns that should diaf?
for pawn in [x for x in self.pawns if x.loc==coord]:
pawn.kill()
return defer
pawn5.py

Pawns can move (very quickly in this version). And when they move, the Board is notified:

class YoureDead(Exception): pass
class IllegalMove(Exception): pass


class Board:
...
def pawnMoved(self, pawn, new_loc):
pawn.loc = new_loc

# Did the Pawn unwittingly move into a fire?
if new_loc in self.fires:
pawn.kill()


class Pawn:
...
def move(self, direction):
if not self.alive:
raise YoureDead("Dead people can't move")

# Which way?
delta = {
'u': (0,-1),
'd': (0,1),
'l': (-1,0),
'r': (1,0),
}[direction]
target = (self.loc[0]+delta[0], self.loc[1]+delta[1])

# Is it okay to move there?
try:
tile = self.board.fg_tiles[target]
except KeyError:
raise IllegalMove("That would be off the board")
if tile != EMPTY:
raise IllegalMove("There's a brick there")
if target in self.board.bombs:
raise IllegalMove("There's a bomb there")

# Go ahead and move
self.board.pawnMoved(self, target)
pawn6.py

Merely an asynchronous pawn

Nothing in the above Pawn snippets makes use of Twisted. But the act of dropping a bomb on the board does:

class Pawn:
...
def dropBomb(self):
if not self.alive:
raise YoureDead("Dead people can't drop bombs")
if self.bombs <= 0:
raise IllegalMove("You're out of bombs")

# Use a bomb from the Pawn's stash
self.bombs -= 1
d = self.board.dropBomb(self.loc, self.fuse, self.flame_size)

# Get the bomb back after it explodes
def bombExploded(result, pawn):
pawn.bombs += 1
d.addCallback(bombExploded, self)
pawn7.py

To keep track of the bombs allotted to the Pawn, we subtract when it's put down, then add when the bomb's Deferred is called back.

Wanna play?

Do this:

git clone -b tx-single-player git://github.com/iffy/boom boom.git
cd boom.git
PYTHONPATH=. python run.py

Or if you don't have Git:

wget https://github.com/iffy/boom/tarball/tx-single-player
tar xf tx-single-player
cd iffy-boom-58c1582/
PYTHONPATH=. python run.py

The controls are W, A, S, D for up, left, down, right respectively. E lays a bomb. AND you have to press enter after each key press. I know, I know! "What a dumb game! Twisted is terrible!" I just haven't covered it yet. We'll get there. Remember, it's bite-sized Twisted.

All the code for this post is in the tx-single-player branch on GitHub. Unlike the snippets shown here, the code there is fully tested and has class and method documentation. Take a look at game.py

Next time

Next time, I'll likely highlight some asynchronous testing tools, then move on to making the game multiplayer and playable (not having to press enter every move).

Tuesday, June 12, 2012

Bite-sized Twisted: Deferred Errors

In this post, I'll talk about the Deferred callback chain, including error handling.

Exceptions

Boring, run-of-the-mill Exception:

def mouth(food):
raise Exception("Don't eat %s" % food)
mouth('cannon balls')
err1.py
Traceback (most recent call last):
File "err1.py", line 3, in <module>
mouth('cannon balls')
File "err1.py", line 2, in mouth
raise Exception("Don't eat %s" % food)
Exception: Don't eat cannon balls
python err1.py

Exception raised inside a callback:

from twisted.internet.defer import Deferred

def mouth(food):
raise Exception("Don't eat %s" % food)

d = Deferred()
d.addCallback(mouth)
d.callback('cannon balls')
err2.py
Unhandled error in Deferred:
Unhandled Error
Traceback (most recent call last):
File "err2.py", line 8, in <module>
d.callback('cannon balls')
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 361, in callback
self._startRunCallbacks(result)
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 455, in _startRunCallbacks
self._runCallbacks()
--- <exception caught here> ---
File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 542, in _runCallbacks
current.result = callback(current.result, *args, **kw)
File "err2.py", line 4, in mouth
raise Exception("Don't eat %s" % food)
exceptions.Exception: Don't eat cannon balls
python err2.py

It complains of an Unhandled error in Deferred. To handle it, an error callback (errback for short) is needed.

from twisted.internet.defer import Deferred

def mouth(food):
raise Exception("Don't eat %s" % food)

def badfood(food):
print "Bad food happened, but I'm okay"

d = Deferred()
d.addCallback(mouth)
d.addErrback(badfood)
d.callback('cannon balls')
err3.py
Bad food happened, but I'm okay
python err3.py

Errbacks are only called to handle errors. So, in this case, the errback is not called since there's no error:

from twisted.internet.defer import Deferred

def mouth(food):
print "I ate %s" % food

def badfood(food):
print "Bad food happened, but I'm okay"

d = Deferred()
d.addCallback(mouth)
d.addErrback(badfood)
d.callback('piano keys')
err4.py
I ate piano keys
python err4.py

Garden of forking paths

Callbacks will always result in either:

  1. a value or
  2. an error
If a value is returned, the next callback in line will get the value. If an error happens, the next errback in line will get the error.

Errbacks are the same -- they will always result in either a value or an error. And the result will be handled either by the next callback or the next errback. This snippet illustrates that:

from twisted.internet.defer import Deferred

def value(result, msg):
print 'value %s' % msg
return 'value'

def error(result, msg):
print 'error %s' % msg
raise Exception(msg)

d = Deferred()
d.addCallback(value, 'callback level 1')

d.addErrback(value, 'errback level 2')

d.addCallback(error, 'callback level 3')
d.addCallback(value, 'callback level 4')
d.addCallback(error, 'callback level 5')
d.addCallback(value, 'callback level 6')

d.addErrback(value, 'errback level 7')
d.addErrback(error, 'errback level 8')
d.addErrback(value, 'errback level 9')
d.addErrback(error, 'errback level 10')

d.addCallback(value, 'callback level 11')

d.callback('begin')
twopaths1.py
value callback level 1
error callback level 3
value errback level 7
value callback level 11
python twopaths1.py

What happened?

  1. The Deferred is called back with 'begin'.
  2. The first callback is called with 'begin' and returns 'value'.
  3. Since there is no error, the errback on level 2 is skipped and the next callback (level 3) is called.
  4. The callback on level 3 ends in error, so all the callbacks are skipped until the next errback (level 7) is found.
  5. The errback on level 7 returns 'value', so all the errbacks are skipped until the next callback (level 11) is found.
Here's a diagram of what happened. Blue squares are callbacks. Red squares are errbacks. Time flows to the right:

1 2 3 4 5 6 7 8 9 10 11

Trapping specific exceptions

Error handlers can be made to only deal with specific exceptions using the trap() method of the passed-in error (the first argument). If the actual error doesn't match the kind being trapped, the next errback in line will be called with the error.

from twisted.internet.defer import Deferred

def add3(result):
return 3 + result

def catchAttributeError(error):
error.trap(AttributeError)
print 'AttributeError happened'
return 'Bad attribute'

def catchTypeError(error):
error.trap(TypeError)
print 'TypeError happened'
return 'Bad type of value'

def printResult(result):
print 'Result: %s' % result

d = Deferred()
d.addCallback(add3)
d.addErrback(catchAttributeError)
d.addErrback(catchTypeError)
d.addCallback(printResult)
d.callback('foo')
trap1.py
TypeError happened
Result: Bad type of value
python trap1.py

Without the .trap() calls in trap1.py, catchAttributeError would have handled the error instead of catchTypeError. Also, notice that catchAttributeError is called first, but since it's only trapping AttributeErrors, the error is passed to the next errback, catchTypeError.

Why can you call .trap() on the thing passed to errbacks? Short answer: it's a Failure object. Long answer: see the "Read more" section below.

Read more

Believe it or not, there's still more you can do with Deferreds. As features are needed for the Bomberman clone, I'll introduce them. In the meantime, read the very thorough, official Deferred Reference if you're interested.

Next time: Bombs away!

Using the things I've posted about so far, I plan for the next Bite-sized Twisted post to include the code for a playable version of boom. Lest you expect more than I'm planning: it will be single player, may or may not display a textual representation of the board, and will require pressing enter after every move. Future posts will improve the game further.

Friday, June 8, 2012

Bite-sized Twisted: Deferreds

In this post, we'll examine the Deferred.

The check's in the mail

A Deferred is kind of like an IOU. It's a promise. It's a forecast of things to come. A forerunner of sorts. A title bearer or trumpeteer.

Enough analogies: it's a class you can instantiate. Like this:

>>> from twisted.internet.defer import Deferred
>>> iou = Deferred()

If you are given a Deferred, use addCallback to register a function to handle the value when it arrives.

>>> def spend(value):
... print value + ' spent!'
...
>>> iou.addCallback(spend)
<Deferred at 0xb764bcccL>

If you are the one giving out the Deferred and are responsible for fulfilling the promise, use callback to send the value to the registered callback functions:

>>> iou.callback('$20.00')
$20.00 spent!

Callbacks can be chained

Multiple callbacks can be added to a Deferred. Each callback is not called with the original value. Each callback is called with the return value of the prior callback. For example:

from twisted.internet.defer import Deferred

def mouth(what):
print 'I am the mouth, I got ' + what
return 'chewed up ' + what

def stomach(what):
print 'I am the stomach, I got ' + what

d = Deferred()
d.addCallback(mouth)
d.addCallback(stomach)
d.callback('jelly beans')
deferred1.py
I am the mouth, I got jelly beans
I am the stomach, I got chewed up jelly beans
python deferred1.py

Extra arguments

If you want to pass additional arguments to a callback, add them in addCallback:

from twisted.internet.defer import Deferred

def callback(value, arg, keyword_arg='foo'):
print 'value: %r' % value
print 'arg: %r' % arg
print 'keyword_arg: %r' % keyword_arg

d = Deferred()
d.addCallback(callback, 'apple', keyword_arg='banana')
d.callback('gorilla')
deferred2.py
value: 'gorilla'
arg: 'apple'
keyword_arg: 'banana'
python deferred2.py

Read the source

A Deferred works approximately like this PoorMansDeferred:

class PoorMansDeferred:

def __init__(self):
self.callbacks = []

def addCallback(self, function):
self.callbacks.append(function)

def callback(self, value):
for callback in self.callbacks:
value = callback(value)


def government(value):
portion = value / 2
print 'Government got %s' % portion
return value - portion

def vinny(value):
portion = value / 2
print 'Vinny got %s' % portion
return value - portion

def me(value):
print 'I got %s' % value

d = PoorMansDeferred()
d.addCallback(government)
d.addCallback(vinny)
d.addCallback(me)
d.callback(30)
not_a_great_deferred.py
Government got 15
Vinny got 7
I got 8
python not_a_great_deferred.py

Vinny should study up on integer division. You should probably study up on self defense.

The real Deferred implementation is not that long and worth reading. It includes error handling, chaining, extra arguments, canceling, etc... Read the source here.

There's no reactor

Please notice a few things about the above examples:

  1. The reactor was not involved
  2. There was no reactor.run() call
  3. reactor wasn't used
  4. A Deferred does not need the reactor

In short, a Deferred does not depend on the reactor. It is made more useful by the reactor but it works independently from it.

Many of Twisted's APIs either return or work with Deferreds. It is time well-spent learning how they work.

Defer explosions!

Though a Deferred does not require the reactor, it can be used with it. Let's add an ignite method to our Bomb that returns a Deferred:

from twisted.internet import reactor
from twisted.internet.defer import Deferred

class Bomb:

def __init__(self, fuse, size):
self.fuse = fuse
self.size = size

def ignite(self):
d = Deferred()
reactor.callLater(self.fuse, d.callback, self)
return d
boom/game.py

Then we can modify the Protocol we wrote a few posts ago to use the Deferred code:

from twisted.internet.protocol import Protocol
from twisted.internet import reactor, stdio

from boom.game import Bomb

def explode(bomb):
print 'BOOM! (magnitude %s)' % bomb.size

class BombProtocol(Protocol):

def dataReceived(self, data):
fuse = int(data)
bomb = Bomb(fuse, fuse)
bomb.ignite().addCallback(explode)

stdio.StandardIO(BombProtocol())
reactor.run()
async_input3.py
10
3
5
4
2
5
1
BOOM! (magnitude 3)
BOOM! (magnitude 1)
BOOM! (magnitude 2)
BOOM! (magnitude 4)
BOOM! (magnitude 5)
BOOM! (magnitude 5)
BOOM! (magnitude 10)
python async_input3.py

Errors next time

Error handling deserves a post of its own. In fact, that's probably what the next post will be about. Until then, chew on this:

from twisted.internet.defer import Deferred

def toInfinity(value):
return value / 0

def errorHandler(error):
print 'There was an error: %s' % error.value

d = Deferred()
d.addCallback(toInfinity)
d.addErrback(errorHandler)
d.callback(293)

print "The error didn't kill the program"
errback1.py
There was an error: integer division or modulo by zero
The error didn't kill the program
python errback1.py

Also consider reading Twisted's official, very thorough guide.

Tuesday, June 5, 2012

Bite-sized Twisted: Testing

In this post, we'll explore a few of the neat testing features Twisted has to offer. And we'll starting testing the Bomberman clone. I think we'll name the program boom.

Write tests the same way

You can write tests using unittest from the Python standard library. Read more about that here.

Let's make some bomb tests. I'm going to lay out the directory structure like this:

boom/
boom/__init__.py
boom/test
boom/test/__init__.py
boom/test/test_game.py

We'll make a really simple test for creating a Bomb:

from unittest import TestCase

from boom.game import Bomb

class BombTest(TestCase):

def test_init(self):
bomb = Bomb(3, 4)
self.assertEqual(bomb.fuse, 3)
self.assertEqual(bomb.size, 4)
boom/test/test_game.py

Trial

Twisted comes with an executable for running tests named trial. You can tell it to run tests found in files:

trial boom/test/test_game.py

Or tests found in modules/packages.

trial boom.test.test_game

Running either of the above will result in something like this:

boom
test
test_game ... [ERROR]

===============================================================================
[ERROR]
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/twisted/trial/runner.py", line 677, in loadByNames
things.append(self.findByName(name))
File "/usr/local/lib/python2.7/dist-packages/twisted/trial/runner.py", line 487, in findByName
return reflect.namedAny(name)
File "/usr/local/lib/python2.7/dist-packages/twisted/python/reflect.py", line 464, in namedAny
topLevelPackage = _importAndCheckStack(trialname)
File "/home/matt/iffycan.git/tx-bite-3-testing/boom/test/test_game.py", line 3, in <module>
from boom.game import Bomb
exceptions.ImportError: No module named game

boom.test.test_game
-------------------------------------------------------------------------------
Ran 1 tests in 0.071s

FAILED (errors=1)

Let's fix the test. This post isn't about testing as much as the tools Twisted provides, so I'm going to skip the iterations I went through to arrive at this file:

class Bomb:

def __init__(self, fuse, size):
self.fuse = fuse
self.size = size
boom/game.py

And now the tests pass. Yay!

boom.test.test_game
BombTest
test_init ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.056s

PASSED (successes=1)
trial boom.test.test_game

Trial finds tests

As our program grows, it will be tedious to test if we have to type out the filename or module name for each of our test files. trial alleviates this by searching for things that look like tests. Generally, files with the word "test" in them are considered tests. We can run all of the boom tests just by specifying the root package (e.g trial boom):

boom.test.test_game
BombTest
test_init ... [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.058s

PASSED (successes=1)
trial boom

Temporary files are easy

Twisted includes a subclass of unittest.TestCase which provides some very nice features. For instance, making temporary files and directories is easy using self.mktemp().

from twisted.trial.unittest import TestCase

class MkTempTest(TestCase):

def test_writeable(self):
filename = self.mktemp()
open(filename, 'w').write('foo')
test_mktemp.py

You can skip irrelevant tests

Sometimes you only want to run certain tests under certain conditions. Perhaps your code has optional features, or perhaps some tests only apply to certain operating systems. Twisted provides ways of skipping tests.

Skip entire TestCases by setting a skip attribute:

from twisted.trial.unittest import TestCase

class SkipTest1(TestCase):

skip = "Don't run these tests. They don't do anything"

def test_nothing(self):
pass
test_skip1.py
test_skip1
SkipTest1
test_nothing ... [SKIPPED]

===============================================================================
[SKIPPED]
Don't run these tests. They don't do anything

test_skip1.SkipTest1.test_nothing
-------------------------------------------------------------------------------
Ran 1 tests in 0.002s

PASSED (skips=1)
trial test_skip1.py

Skip individual tests by raising twisted.trial.unittest.SkipTest:

from twisted.trial.unittest import TestCase, SkipTest

class SkipTest2(TestCase):

def test_nothing(self):
raise SkipTest("Waste of time")
test_skip2.py
test_skip2
SkipTest2
test_nothing ... [SKIPPED]

===============================================================================
[SKIPPED]
Waste of time

test_skip2.SkipTest2.test_nothing
-------------------------------------------------------------------------------
Ran 1 tests in 0.028s

PASSED (skips=1)
trial test_skip2.py

Test runs are logged and saved

When you run trial, it creates or recreates a special directory named _trial_temp. Inside, you'll find test.log (a log of the test run). And you can inspect any files created with self.mktemp().

For instance, here's the test.log from running trial test_mktemp.py:

2012-06-02 17:20:27-0600 [-] Log opened.
2012-06-02 17:20:27-0600 [-] --> test_mktemp.MkTempTest.test_writeable <--
2012-06-02 17:20:27-0600 [-] using set_wakeup_fd

And there's a temporary file with foo in it, created by the test:

$ cat _trial_temp/test_mktemp/MkTempTest/test_writeable/d31a0y/temp 
foo

On this run, the file happened to end up in a directory named d31a0y/. This will vary from run to run and won't be the same when you run it.

Keep reading

I've highlighted just a few of my favorite trial features. All of the features described here do not involve the reactor and are a perfectly useable for testing synchronous code. A future post will discuss asynchronous testing features provided by Twisted. Read more about trial here.

I've created a GitHub repo for this Bomberman clone. The files used in this post are in the tx-testing-1 branch.

Saturday, June 2, 2012

Bite-sized Twisted: Bytes and Standard IO

In the last Bite-sized Twisted post I introduced reactor and reactor.callLater, and we made some bombs. In this post, we'll accept user input for lighting bombs.

Input/Output == Bytes

For our game to work, we're going to need to accept user input. By the word input, I actually mean bytes. The user could be using a keyboard or joystick attached to the computer on which the program is running. They might use a browser to play our game. Or they could be tethered to an orbiting satellite, texting with their cellphone. Unless they have no space suit. Regardless, our program will get bytes.

Synchronously, we can get bytes from the keyboard using raw_input as in this example:

import time
fuse = raw_input()
time.sleep(int(fuse))
print 'BOOM!'
raw_input1.py
3
BOOM!

When I typed 3 and pressed enter, the program received bytes for the ASCII string '3' and according to raw_input1.py,

input bytes are converted to an integer, the program waits that number of seconds then writes bytes for the ASCII string 'BOOM!' to stdout.
This is raw_input1.py's protocol.

Let's break out the protocol into a reusable function named dataReceived:

import time

def dataReceived(data):
fuse = int(data)
time.sleep(fuse)
print 'BOOM!'

input_bytes = raw_input()
dataReceived(input_bytes)
raw_input2.py

This program behaves identically to raw_input1.py. Having split the protocol into a self-contained function, however, we can use it on bytes that come from raw_input, a file or some other source.

Asynchronous Input/Output == Bytes

The program in raw_input2.py is limited to one lit bomb at a time. Bomberman with only one bomb shared among all players wouldn't be fun. By using Twisted, we can accept input asynchronously:

from twisted.internet.protocol import Protocol
from twisted.internet import reactor, stdio
import time

class BombProtocol(Protocol):

def dataReceived(self, data):
fuse = int(data)
time.sleep(fuse)
print 'BOOM!'

stdio.StandardIO(BombProtocol())
reactor.run()
async_input1.py

The original dataReceived function was made into a method in a Protocol class. The Protocol class has methods that other Twisted components expect a protocol to have. One such method is dataReceived. Because it implements an expected API, we can use it with other Twisted components. In this case, stdio.StandardIO calls the BombProtocol() instance's dataReceived method with bytes from stdin.

When you run async_input1.py you may notice that there's still only one bomb lit at a time. See it by spamming 3 (alternating with enter) as fast as you can. Each BOOM! happens 3 seconds after the previous one.

3
3
3
BOOM!
BOOM!
BOOM!

The problem is the use of synchronous time.sleep instead of asynchronous reactor.callLater.

This is important: Even though Twisted provides an asynchronous interface, synchronous code will still take all the time it needs, blocking other things from happening. Twisted is single-threaded. A more asynchronous version looks like this:

from twisted.internet.protocol import Protocol
from twisted.internet import reactor, stdio

def explode():
print 'BOOM!'

class BombProtocol(Protocol):

def dataReceived(self, data):
fuse = int(data)
reactor.callLater(fuse, explode)

stdio.StandardIO(BombProtocol())
reactor.run()
async_input2.py

This code lets you start as many bombs as you want, whenever you want. And bomb fuses are lit immediately after you press enter, instead of waiting for the previous bomb to blow up.

Notice that an instance of BombProtocol is passed in to stdio.StandardIO, rather than the class. This will become more important when there is more than one source of input. Each source of input (keyboard, mouse, joystick, orbiting texter) will interact with our code by going through their own instance of a Protocol.

Next time: Testing?

Stay tuned for the next post, which will likely be about how Twisted makes testing easier (unless something else seems more appropriate).

Friday, June 1, 2012

Bite-sized Twisted: Introduction and the Reactor

Why I'm writing this

Twisted has enabled me to do some amazing things -- things I hadn't thought possible. Others haven't had the same delightful experience. Their descriptions of Twisted include less glowing adjectives. My intent with this and related posts is to ameliorate some of those adjectives.

I'm borrowing conceptually from JP Calderone's excellent Twisted Web in 60 Seconds series by keeping these posts relatively short. Also, there's KRONDO blog's Twisted Introduction, another great series for learning Twisted (and general Asynchronous Programming).

Bomberman

Bomberman is great! So, let's make it. By the end (or maybe somewhere in the middle) of these Bite-sized Twisted posts, I'm hoping that some semblance of a Bomberman clone emerges. That's the goal, at least.

Also, am I the only one who thought Super Smash Bros should have included Bomberman? And MegaMan?

The Reactor

The reactor is central to Twisted. You may not always interact with it directly, but it'll almost always be there, reacting away. To start the reactor, call its run method:

from twisted.internet import reactor
reactor.run()
snippet1.py

Run this code and you'll see it hang:


Nothing != Something

You might be tempted to say, "nothing happened." Don't say that. Something happened; in fact it's still happening, and will continue to happen until you stop it (press Control-C). The something happening is the reactor running. To prove it, run this code:

from twisted.internet import reactor
print 'Hello,'
reactor.run()
print 'world!'
snippet2.py

You should see the Hello, but won't see the world! until you stop the reactor:

Hello,
^Cworld!

(The ^C is what my terminal prints when I press Control-C)

What does the reactor do?

The reactor reacts to events. One kind of event it can react to is the passage of time (scheduled events):

from twisted.internet import reactor
reactor.callLater(2, reactor.stop)
reactor.run()
snippet3.py

snippet3.py tells the reactor to call reactor.stop after 2 seconds, then it starts the reactor with reactor.run(). After 2 seconds, reactor.stop is called, stopping the reactor, and the process exits.

The first argument to reactor.callLater is the number of seconds to wait before calling the function. The second argument is the function to call. It's important that it's reactor.stop, not reactor.stop(). reactor.callLater expects the reference to the function, not the result of the function. Passing function references is a common idiom in the Twisted API.

Also, you can read the callLater docs for yourself. (See twisted.internet.interfaces.IReactorTime.callLater as it says)

Make a bomb

If we're going to make Bomberman, we'll need bombs. Bombs have fuses. Let's light some fuses:

from twisted.internet import reactor

def explode(message):
print 'BOOM! ' + message

reactor.callLater(1, explode, 'shakalaka')
reactor.callLater(2, explode, 'I say')
reactor.callLater(3, reactor.stop)
reactor.run()
bomb.py

Run it. After 1 second, the first bomb explodes. After 1 more second, the second explodes. After 1 more, the process exits:

BOOM! shakalaka
BOOM! I say

In bomb.py, note two things:

First, when scheduling explode we also pass a string ('shakalaka') as an extra argument to reactor.callLater. This argument is eventually passed to explode as it's first argument. callLater takes any number of arguments and keyword arguments, which it will use to call the scheduled method.

Second, do the explosions happen when you expect them to? Consider this synchronous code, which has the same timed output as bomb.py:

import time

def explode(message):
print 'BOOM! ' + message

time.sleep(1)
explode('shakalaka')
time.sleep(1)
explode('I say')
time.sleep(1)
synchronous.py

In the synchronous code, since commands happen sequentially, you specify the timing offset from one command to the other. In the asynchronous code, scheduled commands are independent of each other: you specify the timing offset from the time that you schedule the command.

The Twisted code does the same thing as the synchronous code... so why should I use Twisted?

Though synchronous.py has the same output as bomb.py, it does not do the same thing. This will become more apparent when we start adding input/output to programs. Until then, consider how you would do this synchronously:

from twisted.internet import reactor

def explode(message):
print 'BOOM! ' + message

def funkyBomb(message):
reactor.callLater(0.25, explode, message + ' 1')
reactor.callLater(0.5, explode, message + ' 2')
reactor.callLater(0.9, explode, message + ' 3')
reactor.callLater(1.5, explode, message + ' 4')

reactor.callLater(1, funkyBomb, 'shakalaka')
reactor.callLater(1.5, funkyBomb, 'booyah')
reactor.callLater(2, funkyBomb, 'I say')
reactor.callLater(4, reactor.stop)
reactor.run()
bomb2.py
BOOM! shakalaka 1
BOOM! shakalaka 2
BOOM! booyah 1
BOOM! shakalaka 3
BOOM! booyah 2
BOOM! I say 1
BOOM! booyah 3
BOOM! I say 2
BOOM! shakalaka 4
BOOM! I say 3
BOOM! booyah 4
BOOM! I say 4

What do you think of that?!