Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

2008-11-25

Python MUD Game Example

I've found a small MUD-like single player game that I did with Python several years ago. Thought it would be nice to share the source. So here it is.

First of all, a live demo (type help. gone if my internet connection or home server is down.)

server down


And a "screenshot" (sorry for my bad sense of humor):


> help
welcome to mud. available commands are:
go, move, help, exit, look, say, take, drop, inventory, use
>
Unknown Command
> look
spajus sees deep green woods. There also seems to be: flower, bird
> touch bird
looks like a rainbow
> use bird
you do not have bird
> take bird
spajus puts bird in his inventory
> use bird
cuckarekoo! motherfucka!?!
> drop bird
bird was dropped..
> kill bird
Unknown Command
> look north
spajus sees shallow river. There also seems to be: object
> go north
spajus moves to shallow river
> look object
spajus sees a stinky one
> touch object
ewww...
> take object
spajus puts shit in his inventory
> use shit
you are sick, you know that?


Now, the engine.py

class MudObject:
def __init__(self, name, sight, collide = 'nothing happens', usability = 'unusable'):
self.name = name
self.sight = sight
self.collide = collide
self.usability = usability
def view(self):
return self.sight
def touch(self):
return self.collide
def use(self):
return self.usability
class MudPlayer:
def __init__(self, name):
self.inventory = {}
self.name = name
self.health = 100
def move(self, area):
return self.name + ' moves to ' + area.sight
def take(self, obj):
self.inventory[obj.name] = obj
return self.name + ' puts ' + obj.name + ' in his inventory'
def drop(self, name):
if self.inventory.has_key(name):
return self.inventory.pop(name)
def say(self, what):
return self.name + ' says: ' + what
def use(self, what):
if self.inventory.has_key(what):
return self.inventory[what].use()
else:
return 'you do not have ' + what

class MudArea:
def __init__(self, sight):
self.objects = {}
self.panorama = {}
self.sight = sight
self.inverted_directions = {'north':'south', 'south':'north', 'east':'west', 'west':'east'}
def addArea(self, direction, area):
area.panorama[self.inverted_directions[direction]] = self
self.panorama[direction] = area

def relocate(self, args):
try:
return self.panorama[args]
except KeyError:
return None
def addObject(self, name, obj):
if obj != None:
self.objects[name] = obj
return name + ' was dropped..'
def getObject(self, name):
if self.objects.has_key(name):
return self.objects.pop(name)
else:
return 'there is no ' + name + ' arround!'
def touchObject(self, name):
if self.objects.has_key(name):
return self.objects[name].touch()
else:
return 'there is no ' + name + ' arround!'
def view(self, args = 'arround'):
if (args != '' and args != 'arround'):
try:
return self.panorama[args].view()
except KeyError:
try:
return self.objects[args].view()
except KeyError:
return 'nothing.'
else:
objects = ', '.join([k for k, v in self.objects.items()])
if (objects != ''):
obsight = '. There also seems to be: ' + objects
else:
obsight = ''
return self.sight + obsight
import sys

class MudCommand:
""" welcome to mud. available commands are:
go, move, help, exit, look, touch, say, take, drop, inventory, use """
def __init__(self, char, area):
self.char = char
self.area = area

def go(self, args):
""" alias of move """
return self.move(args)

def use(self, args):
""" uses item from inventory """
return self.char.use(args)

def inventory(self, args):
""" displays inventory """
return self.char.name + ' has: ' + ', '.join(self.char.inventory)

def help(self, args):
""" gives you help on a topic"""
if args == '':
return self.__doc__
else:
try:
return getattr(self, args).__doc__
except AttributeError:
return 'help topic not found'

def exit(self, args):
""" exits game """
print 'bye bye!'
sys.exit()

def look(self, args):
""" lets you look arround """
return self.char.name + ' sees ' + self.area.view(args)

def take(self, args):
""" takes item from the ground """
try:
return self.char.take(self.area.getObject(args))
except AttributeError:
return 'you cannot take ' + args

def touch(self, args):
""" touches item from the ground """
return self.area.touchObject(args)

def drop(self, args):
""" drops item from inventory to current area """
return self.area.addObject(args, self.char.drop(args))

def move(self, args):
""" moves arround """
area = self.area.relocate(args)
if area != None:
self.area = area
return self.char.move(self.area)
else:
return 'There seems to be nothing that way.'

def say(self, args):
""" makes character talk """
return self.char.say(args)
class MudGame:
def __init__(self, char, area):
self.cmd = MudCommand(char, area)

def run(self):
while True:
command = raw_input('> ');
self.parse(command)

def parse(self, command):
comm = command.lower().split(' ')
try:
cmd = comm[0]
except IndexError:
cmd = 'help'
try:
args = comm[1:]
except IndexError:
args = []
try:
result = getattr(self.cmd, cmd)(' '.join(args).strip())
except AttributeError:
result = 'Unknown Command'
print result


And the main game script - mud.py:

from engine import *

#objects (name, description, on touch, on use)
rose = MudObject('rose', 'a red blossom with spikes', 'bites fingers!', 'wanna eat it or what?')
shit = MudObject('shit', 'a stinky one', 'ewww...', 'you are sick, you know that?')
gaidys = MudObject('bird', 'oh, a cock!', 'looks like a rainbow', 'cuckarekoo! motherfucka!?!')

#areas
woods = MudArea('deep green woods')
river = MudArea('shallow river')
hills = MudArea('orc hills')
house = MudArea('house of all gay')
meadow = MudArea('a green smelly meadow')

#attaching interactive stuff to areas
river.addObject('object', shit)
woods.addObject('flower', rose)
woods.addObject('bird', gaidys)
meadow.addObject('animal', gaidys)

#link all areas with bidirectional references
river.addArea('south', hills)
woods.addArea('north', river)
woods.addArea('west', house)
hills.addArea('east', meadow)
meadow.addArea('north', woods)

#create a player
char = MudPlayer('spajus')

#create a game with player and starting area
game = MudGame(char, woods)

#lets go!
game.run()


OK, and of course, unit tests:

import unittest
from engine import *

class TestMudObject(unittest.TestCase):
def setUp(self):
self.o = MudObject('object1', 'sight1', 'collision1', 'usage1')
self.o2 = MudObject('object2', 'sight2')

def test_view(self):
self.assertEqual(self.o.view(), 'sight1')
self.assertEqual(self.o2.view(), 'sight2')
self.assertNotEqual(self.o.view(), 'c')
self.assertNotEqual(self.o.view(), self.o2.view())

def test_touch(self):
self.assertEqual(self.o.touch(), 'collision1')
self.assertEqual(self.o2.touch(), 'nothing happens')
self.assertNotEqual(self.o.touch(), 'sight1')
self.assertNotEqual(self.o.touch(), self.o2.touch())

def test_use(self):
self.assertEqual(self.o.use(), 'usage1')
self.assertEqual(self.o2.use(), 'unusable')
self.assertNotEqual(self.o.use(), 'unsuable')
self.assertNotEqual(self.o.use(), self.o2.use())

class TestMudPlayer(unittest.TestCase):
def setUp(self):
self.p1 = MudPlayer('player1')
self.p2 = MudPlayer('player2')
self.area1 = MudArea('area1')
self.area2 = MudArea('area2')
self.o = MudObject('object1', 'sight1', 'collision1', 'usage1')
self.o2 = MudObject('object2', 'sight2')

def test_move(self):
f1 = self.p1.move
f2 = self.p2.move
a1 = self.area1
a2 = self.area2
self.assertEqual(f1(a1), 'player1 moves to area1')
self.assertEqual(f2(a1), 'player2 moves to area1')
self.assertEqual(f1(a2), 'player1 moves to area2')
self.assertEqual(f2(a2), 'player2 moves to area2')
self.assertNotEqual(f1(a1), 'player1 moves to area2')

def test_take_drop(self):
take = self.p1.take
use = self.p1.use
drop = self.p1.drop
inven = self.p1.inventory

o1 = self.o
o2 = self.o2

self.assertEqual(inven, {})
self.assertEqual(take(o1), 'player1 puts object1 in his inventory')
self.assertEqual(inven, {'object1':o1})
self.assertEqual(take(o2), 'player1 puts object2 in his inventory')
self.assertEqual(inven, {'object1':o1, 'object2':o2})

self.assertEqual(drop('object1'), o1)
#neesamo objekto dropint neina
self.assertRaises(TypeError, drop('object1'))
self.assertEqual(inven, {'object2':o2})
self.assertEqual(drop('object2'), o2)
self.assertEqual(inven, {})

def test_use(self):
p1 = self.p1
o1 = self.o
self.assertNotEqual(p1.use('object1'), 'usage1')
self.assertEqual(p1.use('object1'), 'you do not have object1')
p1.take(o1)
self.assertEqual(p1.use('object1'), 'usage1')

class TestMudArea(unittest.TestCase):
def setUp(self):
self.a1 = MudArea('area1')
self.a2 = MudArea('area2')
self.o1 = MudObject('obj1', 'sight1', 'collide1', 'use1')
self.o2 = MudObject('obj2', 'sight2')

def test_addArea(self):
#assignmentas turi buti veidrodinis
self.a1.addArea('north', self.a2)
self.assertEqual(self.a1.panorama, {'north':self.a2})
self.assertEqual(self.a2.panorama, {'south':self.a1})

def test_relocate(self):
self.a1.addArea('north', self.a2)
self.assertEqual(self.a1.relocate('north'), self.a2)
self.assertEqual(self.a2.relocate('north'), None)
self.assertEqual(self.a2.relocate('south'), self.a1)

def test_addObject(self):
self.assertEqual(self.a1.objects, {})
#dropped returninama todel, kad paprastai objectas zaidimo metu addinamas tada, kai playeris dropina ji.
#kreivai biski, bet ka padarysi :)
self.assertEqual(self.a1.addObject('something', self.o1), 'something was dropped..')
self.assertEqual(self.a1.objects, {'something':self.o1})
self.a1.addObject('other', self.o2)
self.assertEqual(self.a1.objects, {'something':self.o1, 'other':self.o2})
self.assertEqual(self.a1.addObject('something_clone', self.o1), 'something_clone was dropped..')
self.assertEqual(self.a1.objects, {'something':self.o1, 'other':self.o2, 'something_clone':self.o1})

def test_getObject(self):
self.assertEqual(self.a1.objects, {})
self.a1.addObject('something', self.o1)
self.a1.addObject('other', self.o2)
self.assertEqual(self.a1.getObject('something'), self.o1)
self.assertEqual(self.a1.objects, {'other':self.o2})
self.assertEqual(self.a1.getObject('something'), 'there is no something arround!')

def test_touchObject(self):
self.assertEqual(self.a1.objects, {})
self.a1.addObject('something', self.o1)
self.a1.addObject('other', self.o2)
self.assertEqual(self.a1.touchObject('something'), self.o1.touch())
self.assertNotEqual(self.a1.touchObject('obj2'), self.o2.touch())
self.assertEqual(self.a1.touchObject('ass'), 'there is no ass arround!')

def test_view(self):
view = self.a1.view
self.assertEqual(view(), 'area1')
#unindentified object/panorama
self.assertEqual(view('my brain'), 'nothing.')

self.a1.addObject('my brain', self.o1)
self.assertEqual(view('my brain'), self.o1.view())
#padarom dar idomiau. kadangi pridejom my brain, reikia parodyti ir tai..
self.assertNotEqual(view(), 'area1')
self.assertEqual(view(), 'area1. There also seems to be: my brain')
self.a1.addObject('duck', self.o2)
self.assertEqual(view(), 'area1. There also seems to be: my brain, duck') #', '.join(self.a1.objects)

self.assertEqual(view('north'), 'nothing.')
self.a1.addArea('north', self.a2)
self.assertEqual(view('north'), 'area2')
#kadangi priskyrem area2, turejo atsispindeti ir is ten paziurejus i priesinga north krypti (south), turi matytis area1 viewas
self.assertEqual(self.a2.view('south'), view())
#akurat.. matosi :)

class MudCommandTest(unittest.TestCase):
def setUp(self):
self.p1 = MudPlayer('player1')
self.a1 = MudArea('area1')
self.a2 = MudArea('area2')
self.o1 = MudObject('obj1', 'sight1', 'collide1', 'use1')
self.o2 = MudObject('obj2', 'sight2', 'collide2', 'use2')
self.a2.addObject('bread', self.o1)
self.a2.addObject('pig', self.o2)
self.a1.addArea('east', self.a2)
self.c = MudCommand(self.p1, self.a1)

def test_go_move(self):
#MudArea.go === MudArea.move
#test wrong way
self.assertEqual(self.c.go('somewhere'), 'There seems to be nothing that way.')
#test walk arround
self.assertEqual(self.c.go('east'), 'player1 moves to area2')
self.assertEqual(self.c.go('west'), 'player1 moves to area1')

def test_use(self):
self.assertEqual(self.c.use('bla'), 'you do not have bla')
#lets go east and take something to test using
self.c.go('east')
self.c.take('bread')
#as bread was only the looks, we know it's actually obj1, so lets use it
self.assertEqual(self.c.use('obj1'), self.o1.use())

def test_inventory(self):
self.c.go('east')
self.c.take('bread')
self.assertEqual(self.c.inventory(None), 'player1 has: obj1')

def test_help(self):
self.assertEqual(self.c.help(''), self.c.__doc__)
self.assertEqual(self.c.help('move'), self.c.move.__doc__)
self.assertEqual(self.c.help('blabla'), 'help topic not found')

def test_look(self):
self.assertEqual(self.c.look(''), 'player1 sees ' + self.a1.view())
self.assertEqual(self.c.look('at my balls'), 'player1 sees nothing.')
self.assertEqual(self.c.look('east'), 'player1 sees ' + self.a2.view())

def test_take(self):
self.c.go('east')
self.assertEqual(self.c.take('bread'), 'player1 puts obj1 in his inventory')
self.assertEqual(self.p1.inventory, {'obj1':self.o1})
#already taken!
self.assertEqual(self.c.take('bread'), 'you cannot take bread')

def test_touch(self): #perv test.. :)
self.assertEqual(self.c.touch('self'), 'there is no self arround!')
self.assertNotEqual(self.c.touch('bread'), self.o1.touch())
self.c.go('east')
#kad paliesti reik pirma nueiti
self.assertEqual(self.c.touch('bread'), self.o1.touch())

def test_drop(self):
self.assertEqual(self.c.drop('smelly thing'), None)
self.c.go('east')
self.c.take('bread')
self.c.go('west')
self.assertEqual(self.c.drop('obj1'), 'obj1 was dropped..')
self.assertEqual(self.a1.objects, {'obj1':self.o1})

def test_say(self):
self.assertEqual(self.c.say('i love this game'), 'player1 says: i love this game')
self.assertNotEqual(self.c.say('python sucks'), 'player1 says: that\'s true!')

if __name__ == '__main__':
unittest.main()


To run the game:
python mud.py


To run the tests:
python testengine.py


Damn, I really miss such coding activities :)

2008-07-09

EuroPython 2008 - Day 3



The third and final day of EuroPython 2008 started with a little bit of rocket science by Michael Meinel from German Aerospace Center. He talked about FlowSimulator, which is a Python-controlled framework to unify massive parallel CFD workflows. Interesting point was that they used SWIG to allow Python to control code written in C/C++, so basically Python was a glue code.



Second talk I attended was called "Small team, big demands? - Use the batteries included" by Jussi Rasinmäki. It was a tale of a software project which started with C, failed miserably and finally ended with Python. The outcome was twice as fast as C code with tenfold smaller code base. C can be slow if your code is really really bad.



I went there for the "Batteries Included" line, which really was as simple as this:



There was one thing that I believe you should avoid in your code, and hell, in public presentations too. I mean a function named Age_pine_hemib_h_KalliovirtaTokola. Seriously, WTF?



Next, Raymond D. Hettinger gave a good talk on "Core Python Containers - Under The Hood". Well, before that he managed to amuse the audience with the usual behavior of Windows in his laptop. Why the hell anyone would use Windows here anyway?



However, Raymond revealed some useful Python internals and told us how to make optimal use of the collections.



Here's the moral of his story:



Last talk I've attended in this year's EuroPython was called "Functional Programming with Python, or Why It's Good To Be Lazy?" by Adam Byrtek. It was a great talk that covered the concept of functional programming, which went down to Pythonic functional programming features - map/filter/reduce and lambda functions.



Sadly I had some errands to run, so I couldn't make it to the Lightning Talks...



Hopefully I'll see you all in EuroPython 2009, which is going to be held in Birmingham UK.

2008-07-08

EuroPython 2008 - Day 2


I took way too much coffee during breaks on Day 1, that kept me awake till 3AM, so it was a tough day. Nevertheless, today was better than Day 1. Let's see where I've been.

Designing Large-Scale Applications in Python by Marc-André Lemburg basically was a beginner oriented tutorial on how to do enterprisey stuff properly. It got more serious later on when he started mentioning concrete patterns and techniques. It's good that this conference has a (so so, but still) working WI-FI that kept me entertained till the next session. It's good to chew on some RSS feeds in the morning.



Then Steve Alexander from Canonical gave an inspiring talk on how they developed a very large python web application LEAN style. Launchpad to be exact. One of the greatest points was the use of pre-commit continuous integration, which ensures the developers that trunk is never broken. Also, he mentioned that canonical is hiring ~20 python developers (see their ad in my post about EuroPython 2008 Day 1).



Cool stuff with Jython by Frank Wierzbicki (from Sun) and Jim Baker was somehow boring and Jim's words "we write Java so you don't have to broke my heart, so I got back to reading RSS feeds". Frank was bragging about new hot NetBeans refactoring, which Eclipse has since.. uh.. forever? Read more on this topic in this great post. Dear pythonists, throw away your NetBeans CDs and visit eclipse.org instead.



There were a few Lightning Talks worth noticing.



Here's the full list.



I liked Jure Vrščaj's talk on Remote Module Importing where he showed us how to implement custom Python path resolvers that can seek modules from internet or source control repositories.



Mikhail Kashkin introduced a better style of Python programming - The Drunken Monkey style. Thumbs up for this one. :)



It was amazing to see how Holger Krekel unit-tested JavaScript with pytest.



Geoffrey French deserves a medal for his very alpha code editor gSym Prototype, which visualizes Python code with as AST and adds a Lisp View (with lots and lots of braces that all pythonists just love).



Here's a screenshot of gSym visualizing some mathematical functions.



Finally, a charismatic professor from Sweden, Hans Rosling, made a totally mind blowing keynote called "Code that make sense of the world". It can be basically rephrased as "Instead of letting people generate images from raw statistics in their head we should generate images in front of their heads".



It was one of the best talks I've seen in my life. This 60 year old professor knows people like Larry Page and Bill Gates, he knew Fidel Castro he's also good at GTA 2. Possibly this has something to do with Fidel Castro :).

Some more pictures from his talk...







Here's a great point on how data should be represented to the public.



And the following symptom that technical people tend to have made the audience laugh and applaud.



Most of what he presented can be seen in the following video. You HAVE to see it.



One day to go. See you tomorrow!

2008-07-07

EuroPython 2008 - Day 1

It's the end of first day of EuroPython 2008, a good time to overlook what I've seen.





Right after the keynote, which was short and uplifting, I've headed to the first session - Dynamic Compilation in Python and Jython by Tobias Ivarsson and Jim Baker. It was long and boring, but still inspiring. They looked into things like bytecode versus AST manipulation, introduced nice tools like pyassem. It's nice to see that Java and JVM is a hot topic in smart programmer communities. I consider Python community as one of the smartest people in software development.



Then I went to listen to my native speaker Ignas Mikalajūnas from Programmers of Vilnius. He told Why he Wants Us to Use Eggs. I would disagree with saying "Eggs are to Pythons as Jars are to Java...". It's more like "Eggs may some day be to Pythons as Maven is for Java". For now Eggs look scary and unstable especially with things like Known Good Set (compare it to Maven Repository). Though I would definitely want to use it for Python projects. Better than nothing.





Then I made a mistake by visiting John Pinner's "Python at Home" talk. He was going to tell how he automated his boiler at home with use of Python. I expected a lot from that, instead I've seen some photos of a boiler wired to a motherboard and some source code like "boiler.ignition(On)" and "boiler.ignition(Off)". I would recommend John (and all the other speakers) not to dig deep into source code but concentrate on big picture instead.



I didn't want to go to vendor pitch sessions or things that does not sound interesting (Advanced Searching for Plone and stuff), so my choice was the Barcamp / Open Space, where Tommi Virtanen was giving a talk on Twisted. If you want messaging in Python, do it in Twisted. The guy gave a great quote of Torvalds Linus, which sounded something like "If you have to use debugging - you already have problems. Take a step back and review what could be wrong". It definitely was a great session.



I was going to visit "Discouraging the Use of Python" next, but I was tired and didn't want to be discouraged, so I've headed home to write all this down.

Most of attendees I've spoken to admit that last year's EuroPython was way better than this. But well, two more days to go.

Now for some fun moments:
Canonical was hiring Django developers and senior engineers.



Until the epic failure of their campaign:



All pythonistas got a copy of NetBeans 6.1 and Open Solaris (go Sun! :)) along with geeky looking Bazaar T-Shirt.



And of course, loads of free coffee, snacks and socializing!






See You there at Day 2!

Update

Yesterday I forgot to mention that Guido Van Rossum did not participate in the conference like the last year. I did not participate in his video keynote either...