Member Avatar for Mouche

I'm working on a text adventure game just for fun. I am not planning to complete it, but I decided to try it just to learn classes. Seeing the text game in another post using functions, I realize that that is a very nice way to make a simple game, but I went about this for educational purposes, not for ease.

I started out creating a character class and gave it some attributes just for fun. Then I created a room class and made some coordinates for the rooms (and a commented map). Finally I made a monster class and a menu system for the user.

I've learned a bit about classes from "Python Programmin for the Absolute Beginner," and have had to try to apply those concepts to this evolving game.

Honestly, I don't have a direct problem or anything except "where do I go next?"

I'd love to figure out a monster fighting system. I think a unique monster is put in a room, but I'm not sure how that works. If a monster is picked from a list and has a 1/3 chance of being placed in the room, is it really unique?


Current Goal:
* 4 rooms: bedroom, garden, pathway, kitchen
- Bedroom: has a bed that you can sleep in to regain health; one open exit to the garden; one locked exit to the kitchen (unlocked if you have key; uses key so it's no longer in your inventory)
- Garden: has one first level monster that can be easily beat; two exits.. one to bedroom one to pathway; a weapon is dropped by the monster (respawned after going to another map; 50% chance you can flee)
- Pathway: second level monster; drops key to get into kitchen
- Kitchen: For a later date...to figure out how to create a NPC (non-playing character); have an item in the kitchen which only appears after you talk to someone in a forest (yes, new room) who wants the item; take the item and bring it back to the person and they reward you with something...which then unlocks a new room...etc.
* Simple fighting system; (atk points for char and monsters...weapons = +atk ??)


Here's my current code:

import random

# Monster class
class Monster(object):
    """Monster"""
    def __init__(self,name,level):
        self.name = name
        self.level = level

# Monsters
Green_Blob = Monster("Green Blob","1")            
Red_Blob = Monster("Red Blob","2")            
Blue_Blob = Monster("Blue Blob","3")            
Yellow_Blob = Monster("Yellow Blob","4")            
Black_Blob = Monster("Black Blob","5")            

def make_monster():
        # 2 = monster in room; else, no monster
        monster_in = random.randrange(3)
        if monster_in == (0 or 1):
                return 0
        monster = random.randrange(5)
        if monster == 0:
                monster = Green_Blob
        elif monster == 1:
                monster = Red_Blob
        elif monster == 2:
                monster = Blue_Blob
        elif monster == 3:
                monster = Yellow_Blob
        elif monster == 4:
                monster = Black_Blob
        return monster
     
# Room class
class Room(object):
    """ Room """
    def __init__(self,name,description,monster_y_n):
        self.name = name
        self.description = description
        self.monster_y_n = monster_y_n
        if self.monster_y_n == "y":
            monster = make_monster()
            self.monster = monster

# Rooms
# last input is coordinates (n,e,s,w)
#
# ++++ Room Map +++++
#
# ===================
# |                 |
# |                 |
# |        1        |
# |                 |
# |     3  2        |
# |                 |
# |                 |
# |                 |
# |                 |
# ===================
#
# Template:
# room# = Room(name,description,monster in it? (y/n))
# Then add the coordinates below the room creators

room1 = Room("Bedroom","You are you in your own bedroom.\nTo the south, there is a garden past the back door.", "n")
room2 = Room("Garden","You are in a garden with many flowers and a narrow stone path. \nTo the north, you see the backdoor of your house that enters your bedroom.\nA pathway leads west.","y")
room3 = Room("Pathway","You are in a narrow stone path with hedges on both sides of you.\nTo the east, there is a garden.","y")

# Room coordinates (had to create all the rooms to assign them to coordinates)
room1.coordinates = [0,0,room2,0]
room2.coordinates = [room1,0,0,room3]
room3.coordinates = [0,room2,0,0]
#room4 = Room("Classroom","You are in a classroom with a 5 rows of desks that face a whiteboard.")

# Character class
class Character(object):
    def __init__(self,name,gender,hair,age,location = room1):
        self.name = name
        self.gender = gender
        self.hair = hair
        self.age = age
        self.location = location
        self.inv = []

    def look(self):
        place = self.location
        print place.description
        if place.monster_y_n == "y":
            if place.monster != 0:
                room_monster = place.monster
                print "There is a",room_monster.name,"in the room.\n"
        else:
            print ""
                #if item == True:
                        
                        #print item.description
                        
#class item(object):
        #def __init__(self,description):
                #self.description = description

characters = []
Zyrkan = Character("Zyrkan","m","black",20)
characters.append(Zyrkan)
currentchar = Zyrkan
print "Welcome to Mouche's first text based game."
print
print 'Type "commands" to see the command list'
print "You are currently:",currentchar.name

# Menu
# "commands" shows the commands available
# "look" looks around in the current room
#
while True:
    command = raw_input("")
    if command == "commands":
        print '"n","e","s", and "w" make your character go north, east, south, and west respectively'
        print '"end" to break'
        print '"look" to look around the room'
        print '"players" to see the player list'
    if command == "look":
        currentchar.look()
    if command == ("n" or "north"):
        if currentchar.location.coordinates[0] == 0:
            print "You cannot go that way."
        else:
            currentchar.location = currentchar.location.coordinates[0]
            currentchar.look()
    if command == ("e" or "east"):
        if currentchar.location.coordinates[1] == 0:
            print "You cannot go that way."
        else:
            currentchar.location = currentchar.location.coordinates[1]
            currentchar.look()
    if command == ("s" or "south"):
        if currentchar.location.coordinates[2] == 0:
            print "You cannot go that way."
        else:
            currentchar.location = currentchar.location.coordinates[2]
            currentchar.look()
    if command == ("w" or "west"):
        if currentchar.location.coordinates[3] == 0:
            print "You cannot go that way."
        else:
            currentchar.location = currentchar.location.coordinates[3]
            currentchar.look()
    if command == "end":
        break
    if command == "players":
        print "You are",currentchar
        print
        i = 1
        print "Players:"
        for player in characters:
            print player.name,"(" + str(i) + ")"

Don't take this post as a request to complete my program for me. I have little resources (I know more than my programming teacher because I'm ahead of the class and he's learning a couple days ahead of the students (first year teaching this class))...so he's just having me do whatever I want just to learn... It'd be great to receive both some conceptual help and some coding help. I've read a bit about class inheritance and I think that might be handy for rooms, but I'm not sure how I would implement that.

Thank you very much. (glad there are resources like this on the web)

I have to applaud your teacher for teaching Python rather than the usual "ugly syntax stuff" like C, C++ or Java. Colleges with their all too often ultra conservative teachers are just warming up to Python. So you and your teacher are way ahead!

I will be playing around with your code to get a feel, then let you know what I think.

Here is a quote from Donald Knuth who has written many books on computer science:

Donald E. Knuth, December 1974 -->
"We will perhaps eventually be writing only small
modules which are identified by name as they are
used to build larger ones, so that devices like
indentation, rather than delimiters, might become
feasible for expressing local structure in the
source language."

Member Avatar for Mouche

I have to applaud your teacher for teaching Python rather than the usual "ugly syntax stuff" like C, C++ or Java. Colleges with their all too often ultra conservative teachers are just warming up to Python. So you and your teacher are way ahead!

I have barely touched C++, but I understand how complex it is and its alien syntax. Python is so much easier to read and write. As a student who understands much of the programming concepts, I have realized that just because the syntax is easier doesn't mean it's not powerful and useful. Someone at school was arguing that C is more powerful. I was thinking... "More powerful for what? What do you need to do that wields such power? I'm just tinkering around with learning classes and such."

I think all programmers should start off with a higher level language such as Python to get the feel for programming concepts: variables, conditionals, loops, functions, eventually classes. Then, if they want more power, they write modules in C or however that works...or, if need be, completely turn over to C/C++.

Meh, I don't know a lot about programming, but I'm starting to understand what you can do with it, and that's exciting.


Thanks for taking the time to look at the code and help me.

i did this once in C++

i just made race classes e.g human/drwarf/elf each with different properties. Worked well, less than 8 pages of code can make a good engine

It will save you alot fo time if ou learn .txt file I/O and get the engine to read the text from thier for the mission e.g standard encounter but the x's (from text file) change e.g

you find yourself in x - it is x and you see an x

For the person that thinks C is so much more powerful than Python, give this small problem to solve in C. The Python code is here ...

# split a text string into its words and sort the words ...

text = "explain to me why C is so much more powerful than Python"

word_list = text.split()

# sort case insensitive (using lower case)
word_list.sort(key=str.lower)

# show the result ...
for word in word_list:
    print word

Another coding problem would be to print out the monthly calendar for October 2006.

October 2006
Mo Tu We Th Fr Sa Su
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Here is the Python code that will do it ...

import calendar

calendar.prmonth(2006, 10)

Would be fun, and shut up a big mouth!

Member Avatar for Mouche

Seeing that you seem to be one of the head Python programmers at these forums,vegaseat, could you check out my intital post please?

Your class constructs are fine.

command = raw_input("Enter command: ").lower()  # added prompt text and lower()

You need to do a little more hand holding for the user. At the start of the game you are simply stuck. Give me some info here in the prompt. Also, you may want to start with a "look".
This type of code has to be changed ...

#if command == ("e" or "east"):
if command == "e" or command == "east":

I realize this is just the start, once I leave my bedroom I can go south then west and that's the end.

Member Avatar for Mouche

Thanks...

I guess what I need some suggestions on is the monster attacking system. How can I most effectively make it to where a monster heals a little for each room that you move that you're not in it and fight it when you do see it?

Each time you move s, n, e, or west heal the monster(s) a little. That would be in your while loop's if command == 's' etc.

Each time you move s, n, e, or west heal the monster(s) a little. That would be in your while loop's if command == 's' etc.

Right. I would probably have a Maze class, Room class, and a Monster class, and then maintain a dictionary like this:

class Maze(object):
    
     def __init__(self):

            ...
            self.monsters = {room1:None, room2:None, ...}

class Room(object):

    def __init__(self, maze):
        ...
        self.maze = maze
        ...

    def enter(self):
        if self.maze.monsters[self] == None:
            self.create_monster()

        for m in monsters:
            if monsters[m]:
                 monsters[m].regenerate()

    def create_monster(self):
       monster_type = random.choice(MONSTER_NAMES)
       monster_level = random.randrange(1,MAX_MONSTER_LEVEL)
       self.maze.monsters[self] = Monster(monster_type, monster_level)

class Monster(object):

    ...
    
    def regenerate(self):

        self.hp += 0.1 *self.max_hp
        if self.hp > self.max_hp:
             self.hp = self.max_hp

        # or replace the three lines above with the sexy way: 
        # self.hp = (self.hp + 0.1 * self.max_hp) % self.max_hp

BTW, give your teacher my regards: I'm teaching Computer Programming for the first time this year, using "Python Programming for the Absolute Beginner." Good book choice!

Jeff

P.S. Some free advice ... create the __str__ function for each of your classes early on, so that you can print your objects easily for debugging!

I incorrectly suggested

self.hp = (self.hp + 0.1 * self.max_hp) % self.max_hp

as a slick way of capping the monster's hitpoints. This of course is wrong, and will lead to your monsters suddenly falling sick as soon as they get to their max_hp.:p:cheesy:

The right way would be

self.hp = min(self.hp + 0.1 * self.max_hp, self.max_hp)

which will choose the smaller of the regenerated hp or else the max_hp.

Sorry to mislead!

Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.