RCRPG/Python

Revision as of 17:48, 26 May 2010 by rosettacode>Raelifin (Created page with '{{collection|RCRPG}} This Python 3.1 version of RCRPG uses the standard text interface. All the commands listed on the blog post are implemented, as well…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

This Python 3.1 version of RCRPG uses the standard text interface.

RCRPG/Python is part of RCRPG. You may find other members of RCRPG at Category:RCRPG.

All the commands listed on the blog post are implemented, as well as move and unequip.

Code

<lang python>import re from random import random

directions = {'north':(0,-1,0),

             'east':(1,0,0),
             'south':(0,1,0),
             'west':(-1,0,0),
             'up':(0,0,1),
             'down':(0,0,-1)}

aliases = {'north': ['move','north'],

          'south': ['move','south'],
          'east': ['move','east'],
          'west': ['move','west'],
          'up': ['move','up'],
          'down': ['move','down']}

roomNames = {(0,0,0):'the starting room',

            (1,1,5):'the prize room'}

class Room:

   passages = []
   items = []
   def __init__(self, items=[]):
       self.passages = dict(zip(directions.keys(),[False]*len(directions.keys())))
       self.items = items
   def describe(self, location):
       result = 'You are at '
       if (location in roomNames.keys()):
           result += roomNames[location]
       else:
           posStr = ",".join(list(str(v) for v in location))
           result += posStr
       
       if (len(self.items)):
           result += '\nOn the ground you can see: '+', '.join(self.items)
       result += '\nExits are: '
       exits = list(filter(lambda x: self.passages[x], self.passages.keys()))
       if (len(exits) == 0):
           exits = ['None']
       result += ', '.join(list(map(lambda x: x.capitalize(), exits)))
       return result
   def take(self, target):
       results = []
       if (target == 'all'):
           results = self.items[:]
           self.items = []
           print('You now have everything in the room.')
       elif (target in self.items):
           index = self.items.index(target)
           results = self.items[index:index+1]
           self.items = self.items[0:index]+self.items[index+1:]
           print('Taken.')
       else:
           print('Item not found.')
       return results

def get_new_coord(oldCoord, direction):

   return (oldCoord[0]+directions[direction][0],
           oldCoord[1]+directions[direction][1],
           oldCoord[2]+directions[direction][2])

def opposite_dir(direction):

   if (direction == 'north'):
       return 'south'
   elif (direction == 'south'):
       return 'north';
   elif (direction == 'west'):
       return 'east';
   elif (direction == 'east'):
       return 'west';
   elif (direction == 'up'):
       return 'down';
   elif (direction == 'down'):
       return 'up';
   else:
       raise Exception('No direction found: '+direction)

def make_random_items():

   rand = int(random()*4)
   if (rand == 0):
       return []
   elif (rand == 1):
       return ['sledge']
   elif (rand == 2):
       return ['ladder']
   else:
       return ['gold']

class World:

   currentPos = 0,0,0
   rooms = {(0,0,0): Room(['sledge'])}
   inv = []
   equipped = 
   def look(self):
       return self.rooms[self.currentPos].describe(self.currentPos)
   def move(self, direction):
       if (direction == 'up' and
           not ('ladder' in self.rooms[self.currentPos].items)):
           print("You'll need a ladder in this room to go up.")
           return
       if (not (direction in directions.keys())):
           print("That's not a direction.")
           return
       if (self.rooms[self.currentPos].passages[direction]):
           self.currentPos = get_new_coord(self.currentPos, direction)
       else:
           print("Can't go that way.")
   def alias(self, newAlias, *command):
       aliases[newAlias] = list(command)
       print('Alias created.')
   def inventory(self):
       if (len(self.inv)):
           print('Carrying: '+', '.join(self.inv))
       else:
           print("You aren't carrying anything.")
       if (self.equipped != ):
           print('Holding: '+self.equipped)
   def take(self, target):
       self.inv += self.rooms[self.currentPos].take(target)
   def drop(self, target):
       if (target == 'all'):
           self.rooms[self.currentPos].items += self.inv[:]
           self.inv = []
           print('Everything dropped.')
       elif (target in self.inv):
           index = self.inv.index(target)
           self.rooms[self.currentPos].items += self.inv[index:index+1]
           self.inv = self.inv[0:index]+self.inv[index+1:]
           print('Dropped.')
       else:
           print('Could not find item in inventory.')
   def equip(self, itemName):
       if (itemName in self.inv):
           if (self.equipped != ):
               self.unequip()
           index = self.inv.index(itemName)
           self.equipped = "".join(self.inv[index:index+1])
           self.inv = self.inv[0:index]+self.inv[index+1:]
           print('Equipped '+itemName+'.')
       else:
           print("You aren't carying that.")
   def unequip(self):
       if (self.equipped == ):
           print("You aren't equipped with anything.")
       else:
           self.inv += [self.equipped]
           print('Unequipped '+self.equipped+'.')
           self.equipped = 
   def name(self, *newRoomNameTokens):
       roomNames[self.currentPos] = ' '.join(newRoomNameTokens)
   def dig(self, direction):
       if (self.equipped != 'sledge'):
           print("You don't have a digging tool equipped.")
           return
       if (not (direction in directions.keys())):
           print("That's not a direction.")
           return
       if (not self.rooms[self.currentPos].passages[direction]):
           self.rooms[self.currentPos].passages[direction] = True
           joinRoomPos = get_new_coord(self.currentPos, direction)
           if (not (joinRoomPos in self.rooms)):
               self.rooms[joinRoomPos] = Room(make_random_items())
           self.rooms[joinRoomPos].passages[opposite_dir(direction)] = True
           print("You've dug a tunnel.")
       else:
           print("Already a tunnel that way.")
       

world = World() print("Welcome to the dungeon!\nGrab the sledge and make your way to room 1,1,5 for a non-existant prize!") while True:

   print('\n'+world.look())
   tokens = re.split(r"\s+", input("> ").strip().lower())
   if (tokens[0] == 'quit'):
       break
   while (len(tokens)):
       if (tokens[0] in aliases.keys() and tokens[0] != aliases[tokens[0]][0]):
           tokens = aliases[tokens[0]] + tokens[1:]
           continue
       
       try:
           getattr(world, tokens[0])(*tokens[1:])
       except AttributeError as ex:
           print('Command not found.')
       except TypeError as ex:
           print('Wrong number of args.')
           
       break

print("Thanks for playing!") </lang>