RCRPG/Python: Difference between revisions

From Rosetta Code
Content added Content deleted
(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…')
 
No edit summary
Line 5: Line 5:


==Code==
==Code==
<lang python>import re
<lang python>directions = {'north':(0,-1,0),
from random import random

directions = {'north':(0,-1,0),
'east':(1,0,0),
'east':(1,0,0),
'south':(0,1,0),
'south':(0,1,0),
Line 26: Line 23:


class Room:
class Room:
passages = []
items = []

def __init__(self, items=[]):
def __init__(self, items=[]):
self.passages = dict(zip(directions.keys(),[False]*len(directions.keys())))
self.passages = dict.fromkeys(directions.keys(), False)
self.items = items
self.items = items[:]


def describe(self, location):
def describe(self, location):
result = 'You are at '
result = 'You are at '
if (location in roomNames.keys()):
if location in roomNames:
result += roomNames[location]
result += roomNames[location]
else:
else:
posStr = ",".join(list(str(v) for v in location))
posStr = ",".join(str(v) for v in location)
result += posStr
result += posStr
if (len(self.items)):
if self.items:
result += '\nOn the ground you can see: '+', '.join(self.items)
result += '\nOn the ground you can see: '+', '.join(self.items)
result += '\nExits are: '
result += '\nExits are: '
exits = list(filter(lambda x: self.passages[x], self.passages.keys()))
exits = [k for k,v in self.passages.items() if v] or ['None']
if (len(exits) == 0):
result += ', '.join(map(str.capitalize, exits))
exits = ['None']
result += ', '.join(list(map(lambda x: x.capitalize(), exits)))
return result
return result


def take(self, target):
def take(self, target):
results = []
results = []
if (target == 'all'):
if target == 'all':
results = self.items[:]
results = self.items[:]
self.items = []
del self.items[:]
print('You now have everything in the room.')
print('You now have everything in the room.')
elif (target in self.items):
elif target in self.items:
index = self.items.index(target)
self.items.remove(target)
results = self.items[index:index+1]
results = [target]
self.items = self.items[0:index]+self.items[index+1:]
print('Taken.')
print('Taken.')
else:
else:
Line 71: Line 62:


def opposite_dir(direction):
def opposite_dir(direction):
if (direction == 'north'):
if direction == 'north':
return 'south'
return 'south'
elif (direction == 'south'):
elif direction == 'south':
return 'north';
return 'north';
elif (direction == 'west'):
elif direction == 'west':
return 'east';
return 'east';
elif (direction == 'east'):
elif direction == 'east':
return 'west';
return 'west';
elif (direction == 'up'):
elif direction == 'up':
return 'down';
return 'down';
elif (direction == 'down'):
elif direction == 'down':
return 'up';
return 'up';
else:
else:
Line 87: Line 78:


def make_random_items():
def make_random_items():
rand = int(random()*4)
from random import randrange
if (rand == 0):
rand = randrange(4)
if rand == 0:
return []
return []
elif (rand == 1):
elif rand == 1:
return ['sledge']
return ['sledge']
elif (rand == 2):
elif rand == 2:
return ['ladder']
return ['ladder']
else:
else:
Line 98: Line 90:


class World:
class World:
def __init__(self):
currentPos = 0,0,0
rooms = {(0,0,0): Room(['sledge'])}
self.currentPos = 0,0,0
self.rooms = {(0,0,0): Room(['sledge'])}
inv = []
equipped = ''
self.inv = []
self.equipped = ''


def look(self):
def look(self):
Line 107: Line 100:


def move(self, direction):
def move(self, direction):
if (direction == 'up' and
if direction == 'up' and \
not ('ladder' in self.rooms[self.currentPos].items)):
'ladder' not in self.rooms[self.currentPos].items:
print("You'll need a ladder in this room to go up.")
print("You'll need a ladder in this room to go up.")
return
return
if (not (direction in directions.keys())):
if direction not in directions:
print("That's not a direction.")
print("That's not a direction.")
return
return
if (self.rooms[self.currentPos].passages[direction]):
if self.rooms[self.currentPos].passages[direction]:
self.currentPos = get_new_coord(self.currentPos, direction)
self.currentPos = get_new_coord(self.currentPos, direction)
else:
else:
Line 124: Line 117:


def inventory(self):
def inventory(self):
if (len(self.inv)):
if self.inv:
print('Carrying: '+', '.join(self.inv))
print('Carrying: '+', '.join(self.inv))
else:
else:
print("You aren't carrying anything.")
print("You aren't carrying anything.")
if (self.equipped != ''):
if self.equipped:
print('Holding: '+self.equipped)
print('Holding: '+self.equipped)


Line 135: Line 128:


def drop(self, target):
def drop(self, target):
if (target == 'all'):
if target == 'all':
self.rooms[self.currentPos].items += self.inv[:]
self.rooms[self.currentPos].items.extend(self.inv)
self.inv = []
del self.inv[:]
print('Everything dropped.')
print('Everything dropped.')
elif (target in self.inv):
elif target in self.inv:
index = self.inv.index(target)
self.inv.remove(target)
self.rooms[self.currentPos].items += self.inv[index:index+1]
self.rooms[self.currentPos].items.append(target)
self.inv = self.inv[0:index]+self.inv[index+1:]
print('Dropped.')
print('Dropped.')
else:
else:
Line 148: Line 140:


def equip(self, itemName):
def equip(self, itemName):
if (itemName in self.inv):
if itemName in self.inv:
if (self.equipped != ''):
if self.equipped:
self.unequip()
self.unequip()
index = self.inv.index(itemName)
self.inv.remove(itemName)
self.equipped = "".join(self.inv[index:index+1])
self.equipped = itemName
self.inv = self.inv[0:index]+self.inv[index+1:]
print('Equipped '+itemName+'.')
print('Equipped '+itemName+'.')
else:
else:
print("You aren't carying that.")
print("You aren't carrying that.")


def unequip(self):
def unequip(self):
if (self.equipped == ''):
if not self.equipped:
print("You aren't equipped with anything.")
print("You aren't equipped with anything.")
else:
else:
self.inv += [self.equipped]
self.inv.append(self.equipped)
print('Unequipped '+self.equipped+'.')
print('Unequipped '+self.equipped+'.')
self.equipped = ''
self.equipped = ''
Line 170: Line 161:


def dig(self, direction):
def dig(self, direction):
if (self.equipped != 'sledge'):
if self.equipped != 'sledge':
print("You don't have a digging tool equipped.")
print("You don't have a digging tool equipped.")
return
return
if (not (direction in directions.keys())):
if direction not in directions:
print("That's not a direction.")
print("That's not a direction.")
return
return
if (not self.rooms[self.currentPos].passages[direction]):
if not self.rooms[self.currentPos].passages[direction]:
self.rooms[self.currentPos].passages[direction] = True
self.rooms[self.currentPos].passages[direction] = True
joinRoomPos = get_new_coord(self.currentPos, direction)
joinRoomPos = get_new_coord(self.currentPos, direction)
if (not (joinRoomPos in self.rooms)):
if joinRoomPos not in self.rooms:
self.rooms[joinRoomPos] = Room(make_random_items())
self.rooms[joinRoomPos] = Room(make_random_items())
self.rooms[joinRoomPos].passages[opposite_dir(direction)] = True
self.rooms[joinRoomPos].passages[opposite_dir(direction)] = True
Line 191: Line 182:
while True:
while True:
print('\n'+world.look())
print('\n'+world.look())
tokens = re.split(r"\s+", input("> ").strip().lower())
tokens = input("> ").strip().lower().split()
if (tokens[0] == 'quit'):
if tokens[0] == 'quit':
break
break
while (len(tokens)):
while tokens:
if (tokens[0] in aliases.keys() and tokens[0] != aliases[tokens[0]][0]):
if tokens[0] in aliases and tokens[0] != aliases[tokens[0]][0]:
tokens = aliases[tokens[0]] + tokens[1:]
tokens[0] = aliases[tokens[0]]
continue
continue

Revision as of 19:56, 26 May 2010

RCRPG/Python is part of RCRPG. You may find other members of RCRPG at Category: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 as move and unequip.

Code

<lang python>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:

   def __init__(self, items=[]):
       self.passages = dict.fromkeys(directions.keys(), False)
       self.items = items[:]
   def describe(self, location):
       result = 'You are at '
       if location in roomNames:
           result += roomNames[location]
       else:
           posStr = ",".join(str(v) for v in location)
           result += posStr
       
       if self.items:
           result += '\nOn the ground you can see: '+', '.join(self.items)
       result += '\nExits are: '
       exits = [k for k,v in self.passages.items() if v] or ['None']
       result += ', '.join(map(str.capitalize, exits))
       return result
   def take(self, target):
       results = []
       if target == 'all':
           results = self.items[:]
           del self.items[:]
           print('You now have everything in the room.')
       elif target in self.items:
           self.items.remove(target)
           results = [target]
           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():

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

class World:

   def __init__(self):
       self.currentPos = 0,0,0
       self.rooms = {(0,0,0): Room(['sledge'])}
       self.inv = []
       self.equipped = 
   def look(self):
       return self.rooms[self.currentPos].describe(self.currentPos)
   def move(self, direction):
       if direction == 'up' and \
          'ladder' not in self.rooms[self.currentPos].items:
           print("You'll need a ladder in this room to go up.")
           return
       if direction not in directions:
           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 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.extend(self.inv)
           del self.inv[:]
           print('Everything dropped.')
       elif target in self.inv:
           self.inv.remove(target)
           self.rooms[self.currentPos].items.append(target)
           print('Dropped.')
       else:
           print('Could not find item in inventory.')
   def equip(self, itemName):
       if itemName in self.inv:
           if self.equipped:
               self.unequip()
           self.inv.remove(itemName)
           self.equipped = itemName
           print('Equipped '+itemName+'.')
       else:
           print("You aren't carrying that.")
   def unequip(self):
       if not self.equipped:
           print("You aren't equipped with anything.")
       else:
           self.inv.append(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 direction not in directions:
           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 joinRoomPos not 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 = input("> ").strip().lower().split()
   if tokens[0] == 'quit':
       break
   while tokens:
       if tokens[0] in aliases and tokens[0] != aliases[tokens[0]][0]:
           tokens[0] = aliases[tokens[0]]
           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>