Warning - This site is moving to https://getthecodingbug.anvil.app
Topics covered
​ CSV Files
Complete game
CSV Files
To make it easier to add rooms, characters and items, it might be better to place all the text into a file and read the file at the start during a setup phase. Python makes it very easy to read text files and even has a special library to handle CSV format files.
The CSV format stands for - Comma Separated Variables. This is a special kind of text file which has groups of text, separated by commas. For example, one line might contain, three variables, separated by commas:
R,Kitchen,A dank and dirty room buzzing with flies
By importing the csv library, you can read this file, like this:
import csv
reader = csv.reader(file)
for row in reader:
print(row[0]) # prints "R"
print(row[1]) # prints "Kitchen"
print(row[2]) # prints "A dank and dirty room buzzing with flies"
We can then recognise the "R" to mean we want to create a room and the next two variables will be the name and description.
Complete Game
I have created a new file, called "setup.py" for the functions needed to read and parse the CSV file.
One other change, the player starts in a random room to start the game.
Copy and Paste the 6 files below into a new folder, called, say "adventure2", then run the main program "main2.py":
room.py
# room.py class Room(): def __init__(self, name): self.name = name self.description = None self.linked_rooms = {} self.character = None self.item = None def set_character(self, new_character): self.character = new_character def get_character(self): return self.character def set_description(self, description): self.description = description def get_description(self): return self.description def set_name(self, name): self.name = name def get_name(self): return self.name def set_item(self, item_name): self.item = item_name def get_item(self): return self.item def describe(self): print(self.description) def link_room(self, room_to_link, direction): self.linked_rooms[direction] = room_to_link def get_details(self): print(self.name) dashes = "" for dash in range(len(self.name)): dashes += "-" print(dashes) print(self.description) for direction in self.linked_rooms: room = self.linked_rooms[direction] print("The " + room.get_name() + " is " + direction) print() def move(self, direction): if direction in self.linked_rooms: return self.linked_rooms[direction] else: print("You can't go that way") return self
# character.py class Character(): # Create a character def __init__(self, name, description): self.name = name self.description = description self.conversation = None self.fighter = False # Describe this character def describe(self): print(self.name + " is here!") print(self.description) # Set what this character will say when talked to def set_conversation(self, conversation): self.conversation = conversation # Talk to this character def talk(self): if self.conversation is not None: print("[" + self.name + " says]: " + self.conversation) else: print(self.name + " doesn't want to talk to you") def hug(self): print(self.name + " hugs you back!") class Enemy(Character): enemies_defeated = 0 def __init__(self, name, description): super().__init__(name, description) self.weakness = None self.fighter = True def fight(self, combat_item): if combat_item == self.weakness: print("You fend " + self.name + " off with the " + combat_item) Enemy.enemies_defeated += 1 return True else: print(self.name + " crushes you, puny adventurer!") return False def get_enemies_defeated(self): return Enemy.enemies_defeated def set_weakness(self, item_weakness): self.weakness = item_weakness def get_weakness(self): return self.weakness def steal(self): print("You steal from " + self.name) # How will you decide what this character has to steal?
# item.py class Item(): def __init__(self, name): self.name = name self.description = None def set_description(self, description): self.description = description def get_description(self): return self.description def set_name(self, name): self.name = name def get_name(self): return self.name def describe(self): print(self.description)
# setup.py from room import Room from character import Character from character import Enemy from item import Item import csv import os.path # Define functions to handle each type of class def makeRoom(rooms, room_name, room_description): room = Room(room_name) room.set_description(room_description) rooms.append(room) def getRoom(rooms, room_name): for r in rooms: if r.get_name() == room_name: return r print(room_name + " not found") return None def linkRoom(rooms, room_name, link): room = getRoom(rooms, room_name) if not room == None: direction, next_room_name = link.split("=") next_room = getRoom(rooms, next_room_name) if not next_room == None: room.link_room(next_room, direction) def makeCharacter(characters, rooms, name, description, room_name, conversation): character = Character(name, description) character.set_conversation(conversation) characters.append(character) room = getRoom(rooms, room_name) if not room == None: room.set_character(character) def makeEnemy(characters, rooms, name, description, room_name, conversation, weakness): character = Enemy(name, description) character.set_conversation(conversation) character.set_weakness(weakness) characters.append(character) room = getRoom(rooms, room_name) if not room == None: room.set_character(character) def makeItem(items, rooms, name, description, room_name): item = Item(name) item.set_description(description) items.append(item) room = getRoom(rooms, room_name) if not room == None: room.set_item(item) # Read instructions from file and populate object lists def populate(from_file): # Create empty lists rooms = [] characters = [] items = [] # Check if file exists if not os.path.exists(from_file): print("File does not exist: " + from_file) return rooms, characters, items # Open file file = open(from_file, "r") reader = csv.reader(file) # Read in each line until end of file for row in reader: # Permit empty lines if len(row) < 1: pass # Handle Rooms elif row[0] == "R": makeRoom(rooms, row[1], row[2]) # Handlle Linking Rooms elif row[0] == "L": colnum = 0 for col in row: if colnum >= 2: linkRoom(rooms, row[1], row[colnum]) colnum += 1 # Handle Characters elif row[0] == "C": name = row[1] description = row[2] room_name = row[3] conversation = row[4] makeCharacter(characters, rooms, name, description, room_name, conversation) # Handle Enemies elif row[0] == "E": name = row[1] description = row[2] room_name = row[3] conversation = row[4] weakness = row[5] makeEnemy(characters, rooms, name, description, room_name, conversation, weakness) # Handle Items elif row[0] == "I": name = row[1] description = row[2] room_name = row[3] makeItem(items, rooms, name, description, room_name) file.close() # Return populated object lists to the caller return rooms, characters, items
setup.py
item.py
character.py
main2.py
# main2.py from setup import populate from room import Room from character import Character from character import Enemy from item import Item import random import sys # Read file to populate rooms, characters and items rooms, characters, items = populate("rooms.csv") if len(rooms) < 1: # Can't open file, so exit sys.exit() else: # Describe game print("Adventure Game") print("--------------") print("Defeat at least 3 enemies to win the game") print("Experiment with different commands to navigate the house") # Place player in a random room room_index = random.randint(1, len(rooms)-1) current_room = rooms[room_index] # Start with an empty backpack backpack = [] # Define functions to be used during game def inventory(): if len(backpack) < 1: print("Your backpack is empty") else: print("You have these items in your backpack") for item in backpack: print(" " + item.name + ": " + item.get_description()) def itemInBackpack(item_name): for i in backpack: if i.name == item_name: return True return False def show_help(): print("Try one of these short-hand letters: c,d,e,f,h,i,n,q,s,t,u or w") # Start the game here dead = False attempts = 0 # Main loop while dead == False: print("") # Describe the room we are in current_room.get_details() # Describe any inhabitant of the room inhabitant = current_room.get_character() if inhabitant is not None: inhabitant.describe() # Describe any item which micght be present item = current_room.get_item() if item is not None: item.describe() # Get player's command command = input("> ") # Convert short-hand to commands if command == "?": command = "help" if command == "c": command = "chat" if command == "d": command = "down" if command == "e": command = "east" if command == "f": command = "fight" if command == "h": command = "hug" if command == "i": command = "inventory" if command == "n": command = "north" if command == "q": command = "quit" if command == "s": command = "south" if command == "t": command = "take" if command == "u": command = "up" if command == "w": command = "west" print(command) # Act on given command if command == "quit": dead = True elif command in["up", "down", "north", "south", "west", "east"]: # Move in given directions current_room = current_room.move(command) elif command == "inventory": # Show what in your backpack inventory() elif command == "chat": # Talk to imhabitant - check if there is one if inhabitant == None: print("There is no-one here, to talk with") else: inhabitant.talk() elif command == "fight": # Fight with the inhabitant, if there is one if inhabitant == None: print("There is no-one here, to fight with") elif inhabitant.fighter == False: print(inhabitant.name + " doesn't want to fight with you") else: print("What will you fight with?") fight_with = input() # Do I have this item ? if not itemInBackpack(fight_with): print("You don't have that item") else: if inhabitant.fight(fight_with) == True: # What happens if you win? print("Hooray, you won the fight!") current_room.character = None if inhabitant.get_enemies_defeated() >= 3: print("You win") dead = True else: # What happens if you lose? print("Oh dear, you lost the fight.") print("That's the end of the game") dead = True elif command == "hug": if inhabitant == None: print("There is no-one here, to hug") elif isinstance(inhabitant, Enemy): print("I wouldn't do that if I were you...") else: inhabitant.hug() elif command == "take": # Take an item and put it in the backpack, and rove it fomroom if item == None: print("There is no item to take from here") else: backpack.append(item) current_room.set_item(None) inventory() elif command == "help": show_help() else: attempts += 1 print("Invalid command: " + command) if attempts > 2: attempts = 0 show_help()
R,Garden,An overgrown area mostly brambles and a small pond R,Kitchen,A dank and dirty room buzzing with flies R,Dining Hall,A large room with ornate golden decorations on each wall R,Ballroom,A vast room with a shiny wooden floor R,Hallway,A long narrow room with poor lighting and a staircase R,Landing,A dingy area full of cobwebs with a staircase and a ladder R,Master Bedroom,A wide brightly decorated room with comfortable bed R,Bathroom,A magnificently tiled room with sunken bath and shower cubicle R,Small Bedroom,A small room with single bed and a view of the garden R,Attic,A long room with angled walls and not much headroom R,Sun Room,A room with glass walls on two sides and lounging chairs R,Games Room,A room full of toys and games and a small snooker table R,Roof,A flat roof area with a small parapet with a long rope going down L,Kitchen,south=Dining Hall,west=Hallway L,Hallway,east=Kitchen,up=Landing L,Dining Hall,north=Kitchen,west=Ballroom L,Ballroom,east=Dining Hall L,Landing,down=Hallway,east=Small Bedroom,south=Master Bedroom,up=Attic L,Master Bedroom,north=Landing,east=Bathroom L,Bathroom,west=Master Bedroom,north=Small Bedroom L,Small Bedroom,south=Bathroom,west=Landing L,Attic,down=Landing,east=Sun Room,south=Games Room L,Games Room,north=Attic,east=Roof L,Sun Room,west=Attic,south=Roof L,Roof,down=Garden,west=Games Room I,cheese,A large and smelly block of cheese,Ballroom I,key,An ornate silver key,Bathroom I,book,An old leather-bound book with strange writings,Games Room I,fish,A stinky dead fish with maggots crawling over it,Sun Room E,Dave,A smelly zombie,Dining Hall,Brrlgrh... rgrhl... brains...,cheese E,Grumpy,An old man sitting in the corner,Small Bedroom,Don't talk to me!,book E,Wizard,A tall man with a long beard and pointed hat,Attic,Abracadabra,key C,Catrina,A friendly skeleton,Ballroom,Why hello there C,Angel,A grey ghost who walks through walls,Master Bedroom,Don't go into the garden
rooms.csv