Part 1: The game loop
Contents
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#
[ ]
Create a new file calledadventure.py
. (You might consider creating a new repo for it, if you’re comfortable with git.)[ ]
Give the file a docstring that includes the link to this page.
Part 1.2: Define main()
#
[ ]
Define amain()
function, and have it print"Welcome!"
[ ]
Inmain()
make awhile
loop with the conditionTrue
.[ ]
In the loop, call theinput()
function, with the prompt"> "
. Assign the returned value to the variablereply
.[ ]
Outside ofmain()
: Use an if statement to check if__name__ == "__main__"
.[ ]
In theif
statement, callmain()
.
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()
#
[ ]
Make ado_quit()
function.[ ]
In it, print"Goodbye."
[ ]
Then callquit()
Demo
B. In main()
, in the while loop:#
[ ]
After gettingreply
, check ifreply
is equal toq
orquit
.[ ]
If so, calldo_quit()
[ ]
Otherwise, print a message like:"No such command."
thencontinue
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()
#
[ ]
Define ado_shop()
function.[ ]
Have it print"Items for sale."
[ ]
Iterate over theITEMS
dictionary. Print thename
anddescription
of each.
B. Modify main()
#
[ ]
In between yourif
andelse
, add anelif
clause that checks ifreply
is equal toshop
.[ ]
If so, calldo_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