473,382 Members | 1,377 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,382 software developers and data experts.

text adventure question

I am working on a text adventure game for python to get back into
python programming. My version 0.1 used only functions so I could get
familiar with how those work. I want to move beyond that. I am not
sure what would be a good Python way of handling this. I was
wondering if classes would help? What things should be included in the
main program?

A couple of my goals are:
1) Remove the rooms (or areas) from the main program and have them
called in as needed.
2) Remove NPC's and monsters from the main program and have them
called in as needed.
3) A way of keeping track of time passing in the game
4) Having the main character info stored somewhere else.

Below is pasted a section of my code. Each room is a function that is
later called. I included only one room to keep this short. Thanks you
for suggestions and your time.

Code:

#A sample text adventure game
#Version 0.1
#By Ara Kooser

import random
import sys
import string

#Using global variables for the character
#Want to use a function instead

stre = 9
con = 8
inte = 11
agl = 14
app = 10
mag = 6
sz = 9

hp = 17

reputation = 0

stealth = False

quest1 = False
quest2 = False

cruse = False
poison = False
diseased = False

ducats = 50
lira = 25
florin = 80
equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1}
backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6,
'waterskin': 2}
belt_pouch = {}

################################################## ###################################

day = False

### Global variables for items ###

#grass blades in meadow_1
getGrass_m1 = 0
#mushroom in edge_forest1
getMushroom_ef1 = 0
#orc in forest2
aliveOrc = 0

################################################## ###################################

# help function that will give you a list of commands
def help():
print "look, examine (object), n, w, e, s, take (item)"
print "climb, stealth, fishing, herbalism, forage, haggle"
print "field dressing"
print "wield (object), attack, flee, close, withdraw, maintain"
print "backpack, belt pouch, cs"
print "Example: examine book, take ducats, attack orc"

def character_sheet():
print """\
================================================== ==========================
Name: Profession:
Social Class: Race:

================================================== ==========================
Strength
Constitution
Intelligence
Agility
Appearance
Magic
Size
================================================== ==========================
Ducats: Lira: Florin:

Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff,
Dagger, Field Dressing

Equipment: Backpack, Belt Pouch, Run of the Mill Sword, Dagger, Flint&Steel
1 week food, 2 waterskins, walking stick, dressing kit
================================================== ==========================
"""

def start():
print '''
SAMPLE TEXT ADVENTURE V0.1
You are the last person to leave the small village of Hommlet. The wooden
gate closes behind you and twilight reaches across the land. A dense mist
creeps up out of the ground, only to be kept at bay by the watchmens torches.
Somewhere deep in the woods lies the foul orcs you have tracked for several
days.

'''

print

def outside1():
global hp
global reputation
print " Current Hit Points = ",hp
print " Current Reputation = ",reputation
print ''' You are outside the town gates. The dirt road heads
(N)orth to another
town several days away. The forest lies (E)ast and (W)est through the
meadows. The
rumors you heard in town describe the orcs as being to the west. The town's gate
is to the (S)outh but it is locked for the night.
Type 'help' for a full list of commands.'''
print
prompt_out1()

def out1_desc():
print ''' The fog is growing denser as the sun sets on the meadows.
The exits are (N)orth, (E)ast and (W)est.'''
print
prompt_out1()

def prompt_out1():
global day
prompt_o1 = raw_input("Type a command: ").lower()
try:

if prompt_o1 == "help":
help()
print
prompt_out1()

elif prompt_o1 == "cs":
character_sheet()
print
prompt_out1()

elif prompt_o1 == "status":
print " Current Hit Points = ",hp
print " Current Reputation = ",reputation
prompt_out1()

elif prompt_o1 == "backpack":
print backpack
prompt_out1()

elif prompt_o1 == "belt pouch":
print belt_pouch
prompt_out1()

elif prompt_o1 == "equipment":
print equipment
prompt_out1()

################################################## ######################################
elif prompt_o1 == "examine fog":
print "The fog seems natural enough for this time of year."
print
prompt_out1()

elif prompt_o1 == "examine road":
print ''' The road is a well travelled dirt road
winding many leagues'''
print
prompt_out1()

elif prompt_o1 == "look":
out1_desc()

################################################## #####################################
elif prompt_o1 == "w":
meadow1()

elif prompt_o1 == "e":
meadow2()
elif prompt_o1 == "s":
#if day = False
print "The town's gate is closed for the night"
print
prompt_out1()
#elif
# town_1

elif prompt_o1 == "n":
n_road1()

################################################## ####################################
elif prompt_o1 == "haggle":
print "There is no one to haggle with here."
promt_out1()

elif prompt_o1 == "stealth":
print "You try and be stealthy"
prompt_out1()

else:
print "Please choose another command. That command is invalid"
print
prompt_out1()

except ValueError:
print "Please choose another command. That command is invalid"
print
prompt_out1()

#there are 5 more rooms that follow using functions

start()
outside1()
--
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
an sub cardine glacialis ursae.
Dec 2 '06 #1
4 2703
On 2006-12-02, Ara Kooser <gh********@gmail.comwrote:
I am working on a text adventure game for python to get back
into python programming. My version 0.1 used only functions so
I could get familiar with how those work. I want to move beyond
that. I am not sure what would be a good Python way of handling
this. I was wondering if classes would help? What things
should be included in the main program?
The language used by the Infocom implementors was called ZIL, and
it so happens that the ZIL manual is available for download.
It was sort of a wimpy version of Lisp.

http://www.mv.com/ipusers/xlisper/zil.pdf

Anyway, the ZIL manual explains how Infocom's "library" for text
adventures worked. That should be inspirational for your design.
It's also an entertaining historical artifact, if the history of
computer games is your thing. Here's an amusing sampling:

EXERCISE THREE
Design and implement a full-size game. Submit it to testing,
fix all resulting bugs, help marketing design a package, ship
the game, and sell at lest 250,000 units.

--
Neil Cerutti
Dec 3 '06 #2
On Sat, 02 Dec 2006 10:22:28 -0700, Ara Kooser wrote:
I am working on a text adventure game for python to get back into
python programming. My version 0.1 used only functions so I could get
familiar with how those work. I want to move beyond that. I am not
sure what would be a good Python way of handling this. I was
wondering if classes would help? What things should be included in the
main program?
Think about nouns and verbs. Verbs, "doing words", are functions and
methods. Nouns, "things", are classes and objects. You should model nouns
in your game with classes and objects, and verbs (actions) with functions
and methods.

Here is a simple example: a room. A room is a thing. So we might define a
room like this:
class Room:
def __init__(self, name):
self.name = name

Now we create a new room, and fill it:

bedroom = Room("King's Bedroom")
bedroom.description = "You are in a fancy bedroom."
self.contents.append("crown")

Now we create a function for looking around:

def look(here):
"Look around the place you are in"
print here.description

And when you are in the King's bedroom, you (the programmer) would call
the look function like this:

look(bedroom)
But look above: I said that the King's bedroom contains a "crown", using
only a built-in object (str). Maybe that's all you need. Or perhaps you
need something more fancy:

class Object:
# note: not "object", lower case, as that is a built-in type
def __init__(self, name, value, description):
self.name = name
self.value = value
self.description = description
crown = Object("King's crown", 15000, "a gold crown with many jewels")
scepter = Object("King's scepter", 10000, "a silver scepter")
vorpel_sword = Object("vorpel sword", 200, "a strange looking sword")
bedpan = Object("bedpan", 3, "a smelly metal bowl")
Now you can write a function to look at any object:

def look_at(something):
print something.description
and it will work for both objects and rooms.

Let's put some more things in the King's bedroom:

bedroom.contents.extend([crown, bedpan, vorpel_sword, scepter])

Rooms also need doors:

bedroom.north = "wall"
bedroom.south = "wall"
bedroom.west = "wall"
bedroom.east = Room("corridor") # a corridor is just a long, empty room

Perhaps that's not the best way to do it, because now the King's bedroom
has an exit into the corridor, but the corridor has no exit into the
bedroom! Perhaps you need to think about a better way to map the world.
But for now, we can make a really simple fix for that:

corridor = bedroom.east
corridor.west = bedroom
corridor.north = "wall"
corridor.south = "wall"
corridor.east = Room('kitchen')

Hmmm... we're doing a lot of unnecessary typing here. Better to create
rooms with four walls already! Go back and change the definition of a room:

class Room:
def __init__(self, name):
self.name = name
self.north = "wall"
self.south = "wall"
self.east = "wall"
self.west = "wall"
and now you only need to change the directions that AREN'T walls.
Now you have defined the rooms and objects in your text adventure. You
should do something similar for monsters, and any other thing in the game.
Then create functions for verbs:

def fight(what):
if type(what) == Room:
print "Mindlessly attacking the room doesn't " \
"accomplish anything except bruising your fists."
elif type(what) == Object:
print "My, you have a bad temper. You pummel the object. " \
"It doesn't notice."
elif type(what) == Monster:
fight_monster() # you have to write this function
elif type(what) == Royalty:
print "You try to punch the King. His bodyguards leap " \
"out from the shadows and kick the bejeebus out of you, " \
"then drag you into the deepest dungeon. You have a long, "\
long LONG time to consider what you did wrong as the rats " \
"nibble at your toes."
end_game()
else:
print "You don't know how to fight", what
def say(words, what):
"""Say <wordsto <what>."""
if "poot" in words:
print "Do you kiss your mommy with that potty-mouth?"

if type(what) == Room:
print "The room doesn't answer."
elif type(what) == Monster:
print "The monster doesn't understand English."
# and you can write the rest
One suggested improvement: if you find yourself writing lots of code like
the above, testing "if type(what) == Room" etc., there is a better way of
doing it. Move that block of code into a method of Room:

class Room:
# def __init__ stays the same as before
def hears(words):
"""The player says <wordsto the Room, and the Room responds."""
print "The room doesn't answer."

and then your function becomes much simpler:

def say(words, what):
"""Say <wordsto <what>."""
if "poot" in words:
print "Do you kiss your mommy with that potty-mouth?"
else:
# the player talks, so <whathears and responds.
what.hears(words)
There is more that you can do too. You need a variable to store the
player's current position:

start = Room("the village")
position = start

And you need a function that understands written commands. Here is one
suggestion: define a class for commands:

commandlist = {}
class Command:
def __init__(self, name):
self.name = name
commandlist[name] = self

then define commands themselves:

Command("go")
Command("eat")
Command("sleep")
Command("fight")

(There is a lot more to it that that, I leave the rest to you.)
--
Steven.

Dec 3 '06 #3
When I was playing around with adventure games using oop (in c++)
I had all charecters defined as a type, no need to seperate non-player
charecters with user defined charecters. Makes it easier to create a
party of charecters or monsters. I left it up to the logic of the
program to define behavior after it was loaded in.

http://www.stormpages.com/edexter/csound.html
Ara Kooser wrote:
I am working on a text adventure game for python to get back into
python programming. My version 0.1 used only functions so I could get
familiar with how those work. I want to move beyond that. I am not
sure what would be a good Python way of handling this. I was
wondering if classes would help? What things should be included in the
main program?

A couple of my goals are:
1) Remove the rooms (or areas) from the main program and have them
called in as needed.
2) Remove NPC's and monsters from the main program and have them
called in as needed.
3) A way of keeping track of time passing in the game
4) Having the main character info stored somewhere else.

Below is pasted a section of my code. Each room is a function that is
later called. I included only one room to keep this short. Thanks you
for suggestions and your time.

Code:

#A sample text adventure game
#Version 0.1
#By Ara Kooser

import random
import sys
import string

#Using global variables for the character
#Want to use a function instead

stre = 9
con = 8
inte = 11
agl = 14
app = 10
mag = 6
sz = 9

hp = 17

reputation = 0

stealth = False

quest1 = False
quest2 = False

cruse = False
poison = False
diseased = False

ducats = 50
lira = 25
florin = 80
equipment = {'Sword': 1, 'Dagger': 1, 'Walking staff': 1, 'Leather Armor':1}
backpack = {'Flint and steel': 1, 'Rations': 7, 'dressing kit': 6,
'waterskin': 2}
belt_pouch = {}

################################################## ###################################

day = False

### Global variables for items ###

#grass blades in meadow_1
getGrass_m1 = 0
#mushroom in edge_forest1
getMushroom_ef1 = 0
#orc in forest2
aliveOrc = 0

################################################## ###################################

# help function that will give you a list of commands
def help():
print "look, examine (object), n, w, e, s, take (item)"
print "climb, stealth, fishing, herbalism, forage, haggle"
print "field dressing"
print "wield (object), attack, flee, close, withdraw, maintain"
print "backpack, belt pouch, cs"
print "Example: examine book, take ducats, attack orc"

def character_sheet():
print """\
================================================== ==========================
Name: Profession:
Social Class: Race:

================================================== ==========================
Strength
Constitution
Intelligence
Agility
Appearance
Magic
Size
================================================== ==========================
Ducats: Lira: Florin:

Skills: Forage, Haggle, Stealth, Fishing, Herbalism, Climb, Sword, Staff,
Dagger, Field Dressing

Equipment: Backpack, Belt Pouch, Run of the Mill Sword, Dagger, Flint&Steel
1 week food, 2 waterskins, walking stick, dressing kit
================================================== ==========================
"""

def start():
print '''
SAMPLE TEXT ADVENTURE V0.1
You are the last person to leave the small village of Hommlet. The wooden
gate closes behind you and twilight reaches across the land. A dense mist
creeps up out of the ground, only to be kept at bay by the watchmens torches.
Somewhere deep in the woods lies the foul orcs you have tracked for several
days.

'''

print

def outside1():
global hp
global reputation
print " Current Hit Points = ",hp
print " Current Reputation = ",reputation
print ''' You are outside the town gates. The dirt road heads
(N)orth to another
town several days away. The forest lies (E)ast and (W)est through the
meadows. The
rumors you heard in town describe the orcs as being to the west. The town's gate
is to the (S)outh but it is locked for the night.
Type 'help' for a full list of commands.'''
print
prompt_out1()

def out1_desc():
print ''' The fog is growing denser as the sun sets on the meadows.
The exits are (N)orth, (E)ast and (W)est.'''
print
prompt_out1()

def prompt_out1():
global day
prompt_o1 = raw_input("Type a command: ").lower()
try:

if prompt_o1 == "help":
help()
print
prompt_out1()

elif prompt_o1 == "cs":
character_sheet()
print
prompt_out1()

elif prompt_o1 == "status":
print " Current Hit Points = ",hp
print " Current Reputation = ",reputation
prompt_out1()

elif prompt_o1 == "backpack":
print backpack
prompt_out1()

elif prompt_o1 == "belt pouch":
print belt_pouch
prompt_out1()

elif prompt_o1 == "equipment":
print equipment
prompt_out1()

################################################## ######################################
elif prompt_o1 == "examine fog":
print "The fog seems natural enough for this time of year."
print
prompt_out1()

elif prompt_o1 == "examine road":
print ''' The road is a well travelled dirt road
winding many leagues'''
print
prompt_out1()

elif prompt_o1 == "look":
out1_desc()

################################################## #####################################
elif prompt_o1 == "w":
meadow1()

elif prompt_o1 == "e":
meadow2()
elif prompt_o1 == "s":
#if day = False
print "The town's gate is closed for the night"
print
prompt_out1()
#elif
# town_1

elif prompt_o1 == "n":
n_road1()

################################################## ####################################
elif prompt_o1 == "haggle":
print "There is no one to haggle with here."
promt_out1()

elif prompt_o1 == "stealth":
print "You try and be stealthy"
prompt_out1()

else:
print "Please choose another command. That command is invalid"
print
prompt_out1()

except ValueError:
print "Please choose another command. That command is invalid"
print
prompt_out1()

#there are 5 more rooms that follow using functions

start()
outside1()
--
Quis hic locus, quae regio, quae mundi plaga. Ubi sum. Sub ortu solis
an sub cardine glacialis ursae.
Dec 3 '06 #4
On Sat, 02 Dec 2006 22:19:53 +0000, Dennis Lee Bieber wrote:
Suggest you try to go back and reread some of the responses to such
a subject from whenever (Unfortunately, I suspect my responses are no
longer available as I run with x-noarchive active).
That seems horribly anti-social, not to mention counter-productive. What's
the point of writing to the newsgroup if your response won't be around by
the time they go to read it? After all, what's the point of treating a
newsgroup like comp.lang.python as a chat group?

--
Steven.

Dec 3 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Zachary | last post by:
Hello, I've recently thought of how ideal Python is for the development of what used to be called text adventures. In case any of you don't know, these were basically sort of a computer game in...
4
by: drew197 | last post by:
I am a newbie. I am editing someone elses code to make it compatible with Firefox and Safari. In IE, when you click on the proper link, a block of text is shown in a nice paragraph form. But, in...
1
by: DannyB | last post by:
I am in the process of learning Python. I have the basics down and I now want to test my abilitiy to use them in a (very) small project. I have the idea for a (very) small text based game mapped...
6
by: portCo | last post by:
Hello there, I am creating a vb application which is some like like a questionare. Application read a text file which contains many questions and display one question and the input is needed...
0
by: Andy B | last post by:
Was just wondering if there was a tutorial like http://www.asp.net/learn/data-access/ but uses the newer adventure works database instead?
1
by: Carl Banks | last post by:
On Apr 11, 12:08 pm, "Neil Cerutti" <mr.ceru...@gmail.comwrote: That depends. No, it's prudence. If I am writing a banal, been-done-a-million-times before, cookie- cutter text adventure,...
0
by: fr5478bey | last post by:
bookworm adventure crack http://cracks.00bp.com F R E E
0
by: fr5478bey | last post by:
big city adventure crack http://cracks.00bp.com F R E E
42
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
I'm currently writing a program and I've got in mind to keep it as portable as possible. In particular I want it to run on Linux and Windows, but I'm also keeping an open mind to any machine that...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.