Part 1: The game loop#

In this section we’ll be writing the game loop–the main interface that allows the player to enter commands, do something, print messages to the player, and continue with the game.

We’ll write a main() function to be the core of this interface. In it we’ll use an infinite while loop to run the game. Every time the loop runs it will ask the player for input, then do something based on their response.

We will eventually write a function to correspond to each of the commands available in the game, which will be called from main() when the player enters the relevant command.

For now though, we’re just setting up the basic framework.

Part 1.1: Setup#

  1. [ ] Create a new file called adventure.py. (You might consider creating a new repo for it, if you’re comfortable with git.)

  2. [ ] Give the file a docstring that includes the link to this page.

Part 1.2: Define main()#

  1. [ ] Define a main() function, and have it print "Welcome!"

  2. [ ] In main() make a while loop with the condition True.

  3. [ ] In the loop, call the input() function, with the prompt "> ". Assign the returned value to the variable reply.

  4. [ ] Outside of main(): Use an if statement to check if __name__ == "__main__".

  5. [ ] In the if statement, call main().

Demo
Code
 1"""
 2Text-based adventure game
 3https://alissa-huskey.github.io/python-class/exercises/adventure.html
 4"""
 5
 6def main():
 7    print("Welcome!")
 8    while True:
 9        reply = input("> ")
10
11
12if __name__ == "__main__":
13    main()
14

Part 1.3: Your first command: quit#

In this section we will actually look at what the player says, and make our first command: the quit command.

A. Define do_quit()#

  1. [ ] Make a do_quit() function.

  2. [ ] In it, print "Goodbye."

  3. [ ] Then call quit()

Demo

B. In main(), in the while loop:#

  1. [ ] After getting reply, check if reply is equal to q or quit.

  2. [ ] If so, call do_quit()

  3. [ ] Otherwise, print a message like: "No such command." then continue

Code
 1"""
 2Text-based adventure game
 3https://alissa-huskey.github.io/python-class/exercises/adventure.html
 4"""
 5
 6def do_quit():
 7    """Exit the game."""
 8    print("Ok, goodbye.")
 9    quit()
10
11def main():
12    print("Welcome!")
13    while True:
14        reply = input("> ")
15
16        if reply in ["q", "quit", "exit"]:
17            do_quit()
18
19        else:
20            print("No such command.")
21            continue
22
23        print()
24
25if __name__ == "__main__":
26    main()
27

Part 1.4 Create ITEMS#

We’re going to make our first real command: shop. We’re skipping ahead a bit so we can have our program do something interesting.

Create a dictionary ITEMS that is a global variable. This is where you’ll keep the information about the items that are for sale, or objects in any of the rooms.

This will be a nested dictionary, where the key is a unique identifier for each item, and the value is a dictionary with detailed information about that item. The keys of the child dictionary will be:

  • "key" – the same thing as the key

  • "name" – a short description

  • "description" – a longer description

  • "price" – how much it costs

Make a few items for your shop.

Here is an example:

ITEMS = {
    "elixr": {
        "key": "elixr",
        "name": "healing elixr",
        "description": "a magical elixr that will heal what ails ya",
        "price": -10,
    },
}
Code
 1"""
 2Text-based adventure game
 3https://alissa-huskey.github.io/python-class/exercises/adventure.html
 4"""
 5
 6ITEMS = {
 7    "elixir": {
 8        "key": "elixir",
 9        "name": "healing elixir",
10        "description": "a magical elixir that will heal what ails ya",
11        "price": -10,
12    },
13    "dagger": {
14        "key": "dagger",
15        "name": "a dagger",
16        "description": "a 14 inch dagger with a double-edged blade",
17        "price": -25,
18    }
19}
20
21def do_quit():
22    """Exit the game."""
23    print("Ok, goodbye.")
24    quit()
25
26def main():
27    print("Welcome!")
28    while True:
29        reply = input("> ")
30
31        if reply in ["q", "quit", "exit"]:
32            do_quit()
33
34        else:
35            print("No such command.")
36            continue
37
38        print()
39
40if __name__ == "__main__":
41    main()
42

Part 1.5: Make do_shop() function#

In this section we’ll make a shop command that will list the items that we defined in ITEMS above.

Demo

A. Define do_shop()#

  1. [ ] Define a do_shop() function.

  2. [ ] Have it print "Items for sale."

  3. [ ] Iterate over the ITEMS dictionary. Print the name and description of each.

B. Modify main()#

  1. [ ] In between your if and else, add an elif clause that checks if reply is equal to shop.

  2. [ ] If so, call do_shop()

Code
 1"""
 2Text-based adventure game
 3https://alissa-huskey.github.io/python-class/exercises/adventure.html
 4"""
 5
 6ITEMS = {
 7    "elixir": {
 8        "key": "elixir",
 9        "name": "healing elixir",
10        "description": "a magical elixir that will heal what ails ya",
11        "price": -10,
12    },
13    "dagger": {
14        "key": "dagger",
15        "name": "a dagger",
16        "description": "a 14 inch dagger with a double-edged blade",
17        "price": -25,
18    }
19}
20
21def do_shop():
22    """List the items for sale."""
23    print("\nItems for sale.\n")
24
25    for item in ITEMS.values():
26        print(f'{item["name"]:<13}  {item["description"]}')
27
28    print()
29
30def do_quit():
31    """Exit the game."""
32    print("Ok, goodbye.")
33    quit()
34
35def main():
36    print("Welcome!")
37    while True:
38        reply = input("> ")
39
40        if reply in ["q", "quit", "exit"]:
41            do_quit()
42
43        elif reply in ["shop"]:
44            do_shop()
45
46        else:
47            print("No such command.")
48            continue
49
50        print()
51
52if __name__ == "__main__":
53    main()
54