As the title says, I am just learning to code in python and have been reading the book "Learn python the hard way". In chapter 45 he basically says: "Ok, go figure out how to make a text based game" ... So before I get too far in this I just want to be sure I'm not doing anything stupid. The code as it is is fairly functional just not too many rooms etc :p
I am running this under windows.
from sys import exit
from random import randint
import curses,random
screen = curses.initscr()
screen.border(0)
width = screen.getmaxyx()[1]
height = screen.getmaxyx()[0]
size = width*height
char = [" ", ".", ":", "^", "*", "x", "s", "S", "#", "$"]
b = []
curses.start_color()
curses.init_pair(1,0,0)
curses.init_pair(2,1,0)
curses.init_pair(3,3,0)
curses.init_pair(4,4,0)
global x
x = 1
def cls():
screen.clear()
screen.border(0)
screen.addstr(20,1,">")
screen.refresh()
def info_special(message,message2):
screen.move(19,x)
screen.clrtoeol()
screen.addstr(19,x,message,curses.A_BOLD)
screen.addstr(message2)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def info(message):
screen.move(19,x)
screen.clrtoeol()
screen.addstr(19,x,message)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def help():
screen.move(19,x)
screen.clrtoeol()
string = "Commands:"
for j in commands:
string = "%s\n\t %s" % (string,j)
screen.addstr(10,x,string)
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
def intro():
curses.curs_set(0)
screen.clear
welcome = """_ _ ____ __ ___ __ _ _ ____
/ )( \( __)( ) / __)/ \ ( \/ )( __)
\ /\ / ) _) / (_/\( (__( O )/ \/ \ ) _)
(_/\_)(____)\____/ \___)\__/ \_)(_/(____)
"""
dragon = """ ______________
,===:'., `-._
`:.`---.__ `-._
`:. `--. `.
\. `. `.
(,,(, \. `. ____,-`.,
(,' `/ \. ,--.___`.'
, ,' ,--. `, \.;' `
`{D, { \ : \;
V,,' / / //
j;; / ,' ,-//. ,---. ,
\;' / ,' / _ \ / _ \ ,'/
\ `' / \ `' / \ `.' /
`.___,' `.__,' `.__,'
"""
for i in range(size+width+1): b.append(0)
while 1:
for i in range(int(width/9)): b[int((random.random()*width)+width*(height-1))]=65
for i in range(size):
b[i]=int((b[i]+b[i+1]+b[i+width]+b[i+width+1])/4)
color=(4 if b[i]>15 else (3 if b[i]>9 else (2 if b[i]>4 else 1)))
if(i<size-1): screen.addstr( int(i/width),
i%width,
char[(9 if b[i]>9 else b[i])],
curses.color_pair(color) | curses.A_BOLD )
screen.addstr(0,1,welcome,curses.color_pair(3))
screen.addstr(dragon,curses.color_pair(4))
screen.refresh()
screen.timeout(30)
if (screen.getch()!=-1): break
screen.timeout(0)
curses.curs_set(1)
class Monster(object):
def __init__(self,name,strength,location):
self.sname = name.split(' ')[0]
self.name = name
self.strength = strength
self.location = location
class Weapon(object):
def __init__(self,name,strength, location):
self.sname = name.split(' ')[0]
self.name = name
self.strength = strength
self.location = location
class Character(object):
def __init__(self,name,location):
self.name = name
self.location = location
self.inv = []
def look(self):
cls()
place = self.location
string = "Current Room:"
screen.addstr(1,x,string,curses.A_REVERSE)
string = " %s" % place.name
screen.addstr(string)
description = place.description.split('\n')
i = 2 # starting line
for line in description:
screen.addstr(i,x,line)
i += 1
try:
items = place.items
for item in items:
string = "The %s is %s" % (item.name,item.location)
screen.addstr(i+1,x,string)
except:
pass
def inventory(self):
i = 10
while i <= 18:
screen.move(i,x)
screen.clrtoeol()
i += 1
screen.move(19,x)
screen.clrtoeol()
screen.addstr(9,x,"Your inventory contains:")
i = 10 #starting line for list
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
if not len(self.inv):
string = '\tNOTHING!'
screen.addstr(i,x,string,curses.color_pair(1))
else:
for item in self.inv:
string2 = item.name.split(' ')
string1 = "\t%s " % string2.pop(0)
string2 = ' '.join(string2)
screen.addstr(i,x,string1,curses.color_pair(1))
screen.addstr(string2)
i += 1
screen.move(20,3)
screen.clrtoeol()
screen.border(0)
screen.refresh()
class Room(object):
def __init__(self,name,description):
self.name = name
self.description = description
self.paths = []
self.items = []
Start = Room('Start',"""
You are in a dark room.
There is a door to the West and East.
""")
BearRoom = Room('Bear Room',"""
There is a bear!
""")
TreasureRoom = Room('Treasure Room',"""
Treasure has Been Stolen.
The room is empty!
""")
Sword = Weapon('Sword of Truth',5, 'Propped up against the wall')
Lantern = Weapon('Lantern',100, 'In Inventory')
#[n,w,s,e]
Start.paths = [0,BearRoom,0,TreasureRoom]
Start.items = []
BearRoom.paths = [0,0,0,Start]
BearRoom.items = [Sword]
TreasureRoom.paths = [0,Start,0,0]
TreasureRoom.items = []
character = Character('Bob Loblaw',Start)
character.inv = [Lantern] #starting items
commands = ['go north,west,south, or east','take item','attack creature','drop item','(l)ook = Examine room','(i)nventory = get inventory','help = this list']
intro()
character.look()
while True:
command = screen.getstr(20,3,80)
command = command.split(' ')
if command[0] == "go":
try:
if command[1] == "north":
if character.location.paths[0] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[0]
character.look()
elif command[1] == "west":
if character.location.paths[1] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[1]
character.look()
elif command[1] == "south":
if character.location.paths[2] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[2]
character.look()
elif command[1] == "east":
if character.location.paths[3] == 0:
string = "You cannot go that way."
info(string)
else:
character.location = character.location.paths[3]
character.look()
else:
string = "I Don't Understand the direction: %s" % command[1]
info(string)
except:
string = "I need a direction such as north,east,south or west."
info(string)
elif command[0] == "take":
try:
if command[1]:
if character.location.items:
i = 0
for item in character.location.items:
if command[1] in (item.sname,item.sname.lower()):
character.inv.append(item)
del character.location.items[i]
string = "%s " % item.name
string2 = "added to inventory"
info_special(string,string2)
else:
string = "Can't Find item: %s" % command[1]
info(string)
i += 1
else:
string = "There are no items to take in this room."
info(string)
except:
string = "Take What?"
info(string)
elif command[0] == "drop":
try:
if command[1]:
i = 0
for item in character.inv:
if command[1] in (item.sname,item.sname.lower()):
del character.inv[i]
character.location.items.append(item)
item.location = "On the floor."
string = "%s " % item.name
string2 = "dropped"
info_special(string,string2)
else:
string = "Can't Find item: %s" % command[1]
info(string)
i += 1
except:
string = "Drop What?"
info(string)
elif command[0] in ('inv','inventory','i'):
character.inventory()
elif command[0] in ("look","l"):
character.look()
elif command[0] in ('help','commands'):
help()
elif command[0] == "attack":
try:
pass
except:
pass
elif command[0] in ("end","quit","exit","q"):
screen.clear()
screen.refresh()
curses.endwin()
print "Sorry to see you go so soon."
exit(0)
else:
string = "I Dont Understand the command: %s" % command[0]
info(string)
color=(4 if b[i]>15 else (3 if b[i]>9 else (2 if b[i]>4 else 1)))isn't nice, nor aretryandifstatements that are nested to a depth of five. Try condensing your repetitive code with functions and add some comments. – Blender Dec 30 '12 at 9:38