4
\$\begingroup\$

I've started writing a game and I need help, because I know there are many ways to improve what I am doing. I am doing it the basic way I know I can but I know there is more complex ways of doing it.

import time
print"Created on 3/12/2013"
print"ver 1.2"
print"Created by: Daniel Vargas"
print'At any point type "help" for commands'
print"===== Hello ====="
print"Welcome to ZOTD3000!"
time.sleep(2)
print("To find your fate")
###         This is the first Fate        ###
while True:
    fate = raw_input('Write A, B, or C:\n')
    if fate == 'A':
        print"You have selected choice A"
        time.sleep(2)
        break
    elif fate == 'help':
        print"You can only type A, B, or C."
    else:
        print"You can only type A, B, or C."
        time.sleep(2)
###         Here is the first decision          ###
###         From  Fate A            ###
def Forest(Health,Hunger,Inventory):
    print'You wake up in the middle of the forest'
    Inventory = 'Inventory: '
    Squirrel =  'Squirrel'
    while True:
        Choice1 = raw_input('You...\n')
        if Choice1 in ('Life', 'life'):
            print('Health: '+str(Health))
            print('Hunger: '+str(Hunger))
        elif Choice1 in ('Look',  'look'):
            print 'You see many trees, and what looks like an edible dead Squirrel, \na waterfall to the north and a village to the south.'
        elif Choice1 in ('Pickup', 'pickup'):
            p1 = raw_input('Pickup what?\n')
            if p1 == Squirrel:
                if Inventory == 'Inventory: ':
                    print'You picked up a Squirrel!'
                    Inventory = Inventory + Squirrel + ', '
                elif Inventory == 'Inventory: Squirrel, ':
                        print'You already picked that up!'
            else:
                print"You can't find a "+str(p1)+"."
        elif Choice1 in ('Inventory', 'inventory'):
            print Inventory
        elif Choice1 in ('Eat', 'eat'):
            print Inventory
            e1 = raw_input('Eat what?\n')
            if e1 == Squirrel:
                while True:
                    if Inventory == 'Inventory: ':
                        print("You don't have one.")
                        break
                    else:
                        print("It taste's funny. You feel sick.")
                        print("Your health is lowered. But your not hungry.")
                        Health = Health - 1
                        Hunger = Hunger + 1
                        Inventory = 'Inventory: '
                        break
            else:
                print"You don't have a "+str(e1)+"."
        elif Choice1 in ('Kill', 'kill'):
            print'There is nothing to kill.'
        elif Choice1 in ('Goto', 'goto'):
            print"There isn't a place you can Goto in sight."
        elif Choice1 in ('North', 'north'):
            print('Heading North!')
            Waterfall(Health,Hunger,Inventory)
            break
        elif Choice1 in ('East', 'east'):
            print('Heading East!')
            Desert(Health,Hunger)
            break
        elif Choice1 in ('South', 'south'):
            print('Heading South!')
            Village(Health,Hunger)
            break
        elif Choice1 in ('West', 'west'):
            print('Heading West!')
            Forest2(Health,Hunger)
            break
        elif Choice1 in ('help', 'Help'):
            print('You can type Inventory, Life, North, East, South, West, Look, Pickup, Eat, Kill, Goto.')
        else:
            print"You can't do that! Remember CaSe SeNsItIvE!\n Type"' "help" for commands.'
def Waterfall(Health,Hunger,Inventory):
    while True:
        Choice2 = raw_input('You...\n')
        if Choice2 in ('help', 'Help'):
                print('You can type Inventory, Life, North, East, South, West, Look, Pickup, Eat, Kill, Goto.')
        elif Choice2 in ('Life', 'life'):
            print('Health: '+str(Health))
            print('Hunger: '+str(Hunger))
        elif Choice2 in ('North', 'north'):
            print("You can't go up the waterfall!")
        elif Choice2 in ('South', 'south'):
            print('Heading South!')
            Forest(Health,Hunger,Inventory)
            break
        elif Choice2 in ('East', 'east'):
            print('Heading East!')
            Desert(Health,Hunger)
            break
        elif Choice2 in ('West', 'west'):
            print('Heading West!')
            Hills(Health,Hunger)
            break
        elif Choice2 in ('Inventory', 'inventory'):
            print Inventory
        else:
            print"You can't do that! Remember CaSe SeNsItIvE!\n Type"' "help" for commands.'
###         From Fate B             ###
###         From Fate C             ###
###         Main            ###
def main():
    Inventory = 'Inventory: '
    if fate == 'A':
        Forest(10,10,Inventory)


main()
\$\endgroup\$
4
\$\begingroup\$

The existing code is not easy to maintain. If you want to add new places or new actions you will have to write a lot of very specific and deeply nested code.

I've never written a game like this, but it's a good case for modelling with classes. You have a Place, which has a set of neighbours which are also Places. You have a Player who has an inventory which contains Items. The Player has a level of health and hunger which can be modified by Items in his inventory. An Item can be a medicine, a source of food, a physical object, etc.

To illustrate one aspect of this, I would consider something like:

class Place(object):
    def __init__(self, name):
        self.name = name
        self.neighbours = {"North": None,
                           "South" : None
                           "East" : None
                           "West" : None}

    def add_neighbour(self, direction, neighbour):
        self.neighbours[direction] = neighbour

    def leave(self):
        # this is maybe one way to handle movement
        # if the player stores a reference to their location
        # but by no means the only way or the best way

        # get direction from user
        return self.neighbours[direction]

Which will allow you to set up your world separately like:

Waterfall = Place("Waterfall")
Forest = Place("Forest")
Waterfall.add_neighbour("South", Forest)

Your character could look something like (as a starting point)

class Character(object):
    def __init__(self, name, initial_location=None):
        self.name = name
        self.inventory = []
        self.location = initial_location
        self.health = 100
        self.hunger = 0

There are ways to make the direction choices robust, for example making sure that a's southern neighbour is b's northern neighbour and so on, but hopefully this gives you a general sense of what I am talking about. Eventually you will get a feel for what the entities in your code are and what they do and how they interact.

\$\endgroup\$
3
\$\begingroup\$

Here are some small fixes:

  • Make the input lowercase. By replacing Choice2 = raw_input('You...\n') with Choice2 = raw_input('You...\n').lower() you can replace Choice1 in ('East', 'east') by Choice1 == 'east'.
  • Making the inventory a list. Create it with Inventory = [], adding a item would be Inventory += ['squirrel']) and printing the inventory would be print 'Inventory:' + ', '.join(inventory).

You can also return the state and the next place in the functions, like this:

def forest(health, hunger, inventory, here=['squirrel']):
    place = forest
    choice = raw_input("Forest: ").lower()
    if choice == "house":
        place = house
    elif choice in here:
        inventory += [choice]
        here.remove(choice)
    elif choice == "eat":
        choice = raw_input("Eat what? ").lower()
        if choice in inventory:
            if choice == "squirrel":
                inventory.remove(choice)
                health -= 50
                hunger -= 50
        else:
            print "You don't have %s." % choice
    else:
        print "Err, what?"
    return (place, health, hunger, inventory))

def house(health, hunger, inventory):
    print "You won!"
    exit(0)

def main():
    place, health, hunger, inventory = forest, 100, 0, []
    while true:
        if hunger >= 100:
            health -= 10
        if health <= 0: 
            print "You die!"
            break
        hunger += 10

        place, health, hunger, inventory = place(health, hunger, inventory)

main()
\$\endgroup\$
  • \$\begingroup\$ I know what you meant by Choice2 = raw_input('You...\n').lower() but I like having it as it is it helps my eyes. \$\endgroup\$ – John Doe Smith Mar 12 '13 at 23:59
  • \$\begingroup\$ But the inventory thing I like and will use thank you for your help! \$\endgroup\$ – John Doe Smith Mar 13 '13 at 0:01
  • \$\begingroup\$ I tried it out the way you had it and I got confused? \$\endgroup\$ – John Doe Smith Mar 13 '13 at 0:11
0
\$\begingroup\$

If you don't like to follow propeller's suggestion of converting input to lowercase, you can do this instead:

Choice1 = raw_input('You...\n').capitalize()
if Choice1 == 'Life':

This will also accept eg. 'LIFE'. It is easier to maintain than if Choice1 in ('Life', 'life'):

\$\endgroup\$
  • \$\begingroup\$ You mean Choice1 = raw_input('You...\n').capitalize() (which is robuster, by turning LIFE to Life as well). \$\endgroup\$ – YvesgereY Mar 14 '13 at 10:36
  • \$\begingroup\$ @JohnOptionalSmith Thanks, I'd forgotten about capitalize(). \$\endgroup\$ – Janne Karila Mar 14 '13 at 10:52
0
\$\begingroup\$

Since the game has you traveling, you might want to store your locations in a 2d arrray of functions:

map  = [[Forest , Forest2  , Hills], 
        [Forest2, Waterfall, Village], 
        [Hills  , Waterfall, House]]

From this type of approach (white space might not be correctly, not a Python expert), you can programatically derive the directions you can go.

You could even create an items map, to place the squirel and other stuff

items  = [[""          , "Squirrel", ""], 
          ["Squirrel"  , ""        , ""], 
          [""          , ""        , ""]]

Which would place then squirrels only in Forest2 locations.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.