Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Python Application Development

You're reading from   Learning Python Application Development Take Python beyond scripting to build robust, reusable, and efficient applications

Arrow left icon
Product type Paperback
Published in Sep 2016
Publisher Packt
ISBN-13 9781785889196
Length 454 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Ninad Sathaye Ninad Sathaye
Author Profile Icon Ninad Sathaye
Ninad Sathaye
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Developing Simple Applications FREE CHAPTER 2. Dealing with Exceptions 3. Modularize, Package, Deploy! 4. Documentation and Best Practices 5. Unit Testing and Refactoring 6. Design Patterns 7. Performance – Identifying Bottlenecks 8. Improving Performance – Part One 9. Improving Performance – Part Two, NumPy and Parallelization 10. Simple GUI Applications Index

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...

The game – Attack of the Orcs v0.0.1

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:

Pseudo code – version 0.0.1

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.

Reviewing the code

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:

Reviewing the code

Let's have a look at the code from the preceding screenshot:

  • The variable msg is a very long string. This is where the textwrap module is used.
  • The textwrap.fill function wraps the message in such a way that each line is 72 characters long, as specified by the width 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)
Reviewing the code
  • 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 of occupants and add it to the huts list. This was illustrated earlier.
  • The built-in input function accepts a hut number of the user's choice as an integer. The idx 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:

Running Attack of the Orcs v0.0.1
You have been reading a chapter from
Learning Python Application Development
Published in: Sep 2016
Publisher: Packt
ISBN-13: 9781785889196
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime