Search code examples
pythoncoordinateadventure

Best way assigning story to location in a game?


I have a simple question. Here is my story game so far:

x = 0
y = 0
coords = (x,y)
def move(player) :
while 1 :
    global x
    global y
    global coords
    user_in = raw_input()
    if user_in == "w":
        y += 1
    elif user_in == "d":
        x += 1
    elif user_in == "a":
        x -= 1
    elif user_in == "s":
        y -= 1
    else :
        print "Thats not an assigned key"
    coords = (x,y)
    print player, "moved to", coords

move("Mason")

I know that I could make an if statement for each set of coordinates, but I'm feeling pythonic, and I would like to find a fast and efficient way to do this. Thanks in advance for the help!


Solution

  • Like @isedev said in a comment, I recommend using a dictionary that maps location tuples to data about what is found in that location.

    I would make a class called Room or Area that defines what exists at that location. Then make a dictionary called world or something that maps all the locations a player can go. If there is no Area object at a given location, then it is impossible to go there (maybe it's impassible forest, solid rock, or whatever makes sense in your game).

    I suggest you read through a tutorial on how to write an adventure game in Python. The book Learn Python the Hard Way has a chapter devoted to this, and you can get that book for free on the Internet:

    http://learnpythonthehardway.org/book/ex43.html

    It might make more sense if you read through the whole book in order.

    If you don't like that one, try a Google search for "adventure game tutorial Python" and you will find others.

    Good luck and have fun.