Simple script – Attack of the Orcs v0.0.1
We have the required tools and the environment set up. It is now time to write our first Python program. It will be a simple game of chance, developed as a command-line application. As we advance further, we will add more complexity to the game and learn new techniques to develop efficient applications. So, get ready for action!
The game – Attack of the Orcs v0.0.1
The war between humans and their arch enemies, the Orcs, was in the offing. A huge army of Orcs was heading toward the human establishments. They were virtually destroying everything in their way. The great kings of the human race joined hands to defeat their worst enemy for the great battle of their time. Men were summoned to join the rest of the army. Sir Foo, one of the brave knights guarding the southern plains, began a long journey toward the east, through an unknown dense forest. For two days and two nights, he moved cautiously through the thick woods. On his way, he spotted a small isolated settlement. Tired and hoping to replenish his food stock, he decided to take a detour. As he approached the village, he saw five huts. There was no one to be seen around. Hesitantly, he decided to enter a hut... |
Problem statement
You are designing a simple game in which the player is required to choose a hut for Sir Foo. The huts are randomly occupied either by a friend or an enemy. It is also possible that some huts remain unoccupied. If the chosen one turns out to be an enemy hut, the player loses. In the other two scenarios, the player wins.
Pseudo code – version 0.0.1
Now that the goal is clear, open your favorite editor and note down the main steps. This is sometimes referred to as a pseudo code.
While the user wishes to keep playing the game:
- Print the game mission
- Create a
huts
list - Randomly place
'enemy'
or'friend'
or'unoccupied'
in 5 huts - Prompt the player to select a hut number
if enemy
: print"you lose"
else
: print"you win"
As you will notice, the key piece of the code is to randomly occupy the five huts with either enemy or friend and keep the remaining ones unoccupied. How do we do this? Let's quickly work this out using the Python interpreter. If you have installed IPython, start the IPython interpreter. Otherwise, just use the default Python interpreter by typing the command python
in a terminal window. First, we need a Python list to hold all the occupant types. Next, we will use the built-in random
module and call random.choice
to pick one element randomly from this list. This code is shown in the following screen capture:
Now, we just need to write the surrounding code. Let's review it next.
Reviewing the code
Download the source code, ch01_ex01.py
, from the supplementary code bundle provided for this chapter. The file extension, .py
, indicates that it is a Python file. Open it in a Python editor or an IDE of your choice. It is recommended that you keep this file handy while reading the following discussion. It is often easier to glance at the full code to understand it better. Observe the following code snippet. It is just a small portion of the code inside the if __name__ == '__main__'
condition block in the aforementioned file.
Tip
If you have Python 2.7.9 installed, there is a separate Python 2.7.9 compatible source provided in the supporting code bundle.
Let's review the code snippet in the preceding screenshot:
- The first two lines import two built-in modules to gain access to the functionality provided within these modules. The
textwrap
module essentially provides features to nicely format the messages printed on the command line. - The
if
condition block,if __name__ == '__main__'
, is invoked only when the file is run as a standalone script. In other words, the code inside this condition block won't be executed if you import this file in some other file. - Now, let's look at the code in this condition block. First, we will initialize a few variables. As demonstrated earlier, the list
occupants
stores the potential occupant types for the hut. - The last few lines are just to format the text printed in the terminal window. The
dotted_line
is a string that will show a 72-character long line with hyphen symbols. - The ASCII escape sequence is used to print the text in bold. The sequence
"\033[1m"
is to make bold text, and"\033[0m"
is to go back to normal printing style.
The next few lines essentially print further information about the game in the console:
Let's have a look at the code from the preceding screenshot:
- The variable
msg
is a very long string. This is where thetextwrap
module is used. - The
textwrap.fill
function wraps the message in such a way that each line is 72 characters long, as specified by thewidth
in our code.
Now, let's review the following while
loop.
Tip
For Python 2.7.9, the only change required in the first example is to replace all the calls to the built-in function input
with raw_input
:
# For Python 2.7 user_choice = raw_input(msg)
- This top-level loop gives the player an option to play the game again.
- Using
random.choice
, we randomly pick an occupant from the list ofoccupants
and add it to thehuts
list. This was illustrated earlier. - The built-in
input
function accepts a hut number of the user's choice as an integer. Theidx
variable stores a number.
Next, it reveals the occupants by printing related information. Finally, it determines the winner by checking the list item corresponding to the hut number. Note that the huts
list index starts at 0. Therefore, to retrieve the list element for a given hut number, idx
, we need to check the list index at idx-1
.
Running Attack of the Orcs v0.0.1
Assuming you already have Python in your system environment variable, PATH
(available as either python
or python3
), run the program from the command line as:
$ python ch01_ex01.py
That's all! Just play the game and try to save Sir Foo by choosing the right hut! The following snapshot of a Linux terminal window shows our game in action: