Created
January 24, 2013 22:25
-
-
Save KGZM/4628721 to your computer and use it in GitHub Desktop.
A friend of mine is learning to program with Python and started making a simple text game. He hit on the novel, if impractical solution, of using a function for each room... but was writing them all explicitly. I decided to show him about first class functions and closures with this example here. It's very rough and based on his architecture for…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
commands = ["look", "smell"] | |
def make_room(description, exits): | |
def room(skip = False, command = ""): | |
if not skip or command == "look": | |
print description | |
print "You can go: " + ",".join(exits.keys()) | |
if command in exits.keys(): | |
return rooms[exits[command]] | |
if command and command not in commands: | |
print "I don't understand that." | |
return room | |
return room | |
def get_command(): | |
return raw_input("> ") | |
rooms = {} | |
rooms['forest'] = make_room("A deep dark forest.", {'east': 'shack'}) | |
rooms['shack'] = make_room("A small shack.", {'west': 'forest'}) | |
def main(): | |
room = rooms['forest'] | |
skip = True | |
command = "" | |
room(False,"") | |
while 1: | |
command = get_command() | |
new_room = room(skip, command) | |
if new_room != room: | |
room = new_room | |
room(False, "") | |
else: | |
skip = True | |
if command == "quit": | |
print "Bye." | |
break | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment