Tag Archives: python

Python || Aku Aku Snake Game Using Pygame

The following is another homework assignment which was presented in an Introduction to Game Design and Production class. This project is an implementation of the classic “Snake” game using Python 3.2 and Pygame 1.9.2a0.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Pygame - How To Install
Pygame - Download Here
How To Use Pygame
How To Create Executable Python Programs
Aku Aku Snake! Source Code - Click Here To Download
Aku Aku Snake! Executable File - Click Here To Download

==== 1. DESCRIPTION ====

Aku Aku Snake is a new take on the classic “snake” game. It features ten levels, with characters and sounds taken from the PlayStation hit: “Crash Bandicoot 2: Cortex Strikes Back.” The purpose of this game is to successfully complete all ten levels in the fewest amount of retries possible.

To advance in the game, each round the player must consume a specified number of fruit items. Once the required score is obtained during each round, a new one is started. This process is repeated until the player finishes all ten levels. But watch out! The game gets harder as the game progresses.

==== 2. USAGE ====

This game utilizes the python “pygame” module. To play this game, it is assumed that the user already has python 3 and pygame installed on their computer. If that is not the case, here are documents explaining how to obtain the necessary resources for play.

How to install Python:


Install Python

How to install Pygame:


Pygame - How To Install
Pygame - Download Here

After the required resources are obtained, to start the game, the easiest way this to do would be to extract the entire .zip file into the directory of your choice, and to simply run the “main.py” source file through the python interpreter. Once the “main.py” source file is ran through the python interpreter, the game should automatically start.

NOTE: Python and Pygame are not needed to play the executable file!

==== 3. EXTERNAL DEPENDENCIES ====

Other than the pygame module and the “main.py” file mentioned above, there are eight other source files this program depends on. The additional source files should be saved within the “libs” folder, which is located in the directory: “data -> libs”

The following is a brief description of each additional source file.

• “gameBoard.py” sets up the game board and background images for display. This class also reads files (images/fonts) from the “img” & “fnt” directory for use within this program.

• “gameMusic.py” sets up the game sounds and music. This class also reads files (.ogg) from the “snd” directory for use within this program.

• “gameSave.py” sets up the game to have the ability to save its current status. This class uses the “pickle” module to save the players current progress to a file.

• “snake.py” sets up the snake for display on the game board. This class also reads files (images) from the “img” directory for use within this program.

• “fruit.py” sets up the fruit for display on the game board. This class also reads files (images) from the “img” directory for use within this program.

• “enemy.py” sets up the enemies for display on the game board. This class also reads files (images) from the “img” directory, and uses the “spriteStripAnim” class for use within this program.

• “spriteSheet.py” handles sprite sheet animations.

• “spriteStripAnim.py” extends the spriteSheet.py module, providing an iterator (iter() and next() methods), and a __add__() method for joining strips, which comes in handy when a strip wraps to the next row.

These additional files are located within the directory: “data -> libs” folder.

==== 4. FEATURES ====

This game features various colorful images and background music which are taken from the original Crash Bandicoot game. Each level in this game features background music that are unique to each level.

The most useful feature implemented in this game is the “save game” element, which allows a player to save their current progress at any moment during gameplay. This allows a player to save their current status and continue playing the game at a later date if they desire.

To save the game, during gameplay simply click on the boss image in the upper right corner. Once the save is complete, a sound jingle will play confirming the successful save.

This game also features two modes of operation: “Easy” and “Hard” mode. When easy mode is selected, the game saves the user’s current game progress every time they die, but when hard mode is selected, that feature is turned off and the user HAS to save their current progress manually, or else it will be lost after each death.

Here are screenshots of the game during play. (on all images, click to enlarge)

Aku Aku Snake! Screenshots SelectShow

==== 5. DOWNLOAD AND PLAY ====

Aku Aku Snake! Source Code - Click Here To Download
Aku Aku Snake! Executable File - Click Here To Download

NOTE: Python and Pygame are not needed to play the executable file!

Python || Brainy Memory Game Using Pygame

The following is another homework assignment which was presented in an Introduction to Game Design and Production class. This project is an implementation of the classic “Memory” game using Python 3.2 and Pygame 1.9.2a0.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

Pygame - How To Install
Pygame - Download Here
How To Use Pygame
How To Create Executable Python Programs
Brainy Memory Game Source Code - Click Here To Download
Brainy Memory Game Executable File - Click Here To Download

==== 1. DESCRIPTION ====

Brainy Memory Game is a mind stimulating educational card game in which an assortment of cards are laid face down on a surface, and the player tries to find and uncover two identical pairs. If the two selected cards match, they are removed from gameplay. If the two selected cards do not match, both of the cards are turned back over, and the process repeats until all identical matching cards have been uncovered! The object of this game is to find identical pairs of two matching cards in the fewest number of turns possible. This game can be played alone or with multiple players, and is especially challenging for children and adults alike.

==== 2. USAGE ====

This game utilizes the python “pygame” module. To play this game, it is assumed that the user already has python and pygame installed on their computer. If that is not the case, here are documents explaining how to obtain the necessary resources for play.

How to install Python:


Install Python

How to install Pygame:


Pygame - How To Install
Pygame - Download Here

After the required resources are obtained, to start the game, the easiest way to do this would be to extract the entire .zip file into the directory of your choice, and to simply run the “memory.py” source file through the python interpreter. Once the “memory.py” source file is ran through the python interpreter, the game should automatically start.

NOTE: Python and Pygame are not needed to play the executable file!

==== 3. EXTERNAL DEPENDENCIES ====

Other than the pygame module and the memory.py file mentioned above, there are two other source files this program depends on. They are named “gameBoard.py” and “gameMusic.py.”

• “gameBoard.py” sets up the game board and playing cards for display. It also reads files (images/fonts) from the “img” & “fnt “directory for use within this program.

• “gameMusic.py” sets up the game sounds and music. It also reads files (.ogg/.wav) from the “snd” directory for use within this program.

Both of these source files should be located in the same directory as “memory.py”

==== 4. FEATURES ====

This game features various colorful images and sounds for a pleasant user experience. By default, there are 27 playing cards (image size: 80×80) for use located in the “img” folder, and more can be added by the player in the future if they desire.

There are four attainable memory ranks available in this game, with two of them being displayed below. Play the full game to discover the rest!

Here are screenshots of the game during play. (on all images, click to enlarge)

Brainy Memory Game Screenshots SelectShow

==== 5. DOWNLOAD AND PLAY ====


Brainy Memory Game Source Code - Click Here To Download
Brainy Memory Game Executable File - Click Here To Download

NOTE: Python and Pygame are not needed to play the executable file!

Python || Random Number Guessing Game Using Random MyRNG & While Loop

Here is another homework assignment which was presented in introduction class. The following is a simple guessing game using commandline arguments, which demonstrates the use of generating random numbers.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

How To Get User Input
Getting Commandline Arguments
While Loops
MyRNG.py - Random Number Class

==== 1. DESCRIPTION ====

The following program is a simple guessing game which demonstrates how to generate random numbers using python. This program will seed the random number generator (located in the file MyRNG.py), select a number at random, and then ask the user for a guess. Using a while loop, the user will keep attempting to guess the selected random number until the correct guess is obtained, afterwhich the user will have the option of continuing play or exiting.

==== 2. USAGE ====

The user enters various options into the program via the commandline. An example of how the commandline can be used is given below.


python3 guess.py [-h] [-v] -s [seed] -m 2 -M 353

Where the brackets are meant to represent features which are optional, meaning the user does not have to specify them at run time.

The -m and -M options are mandatory.

• -M is best picked as a large prime integer
• -m is best picked as an integer in the range of 2,3,..,M-1

NOTE: The use of commandline arguments is not mandatory. If any of the mandatory options are not selected, the program uses its own logic to generate random numbers.

==== 3. FEATURES ====

The following lists and explains the command line argument options.

-s (seed): Seed takes an integer as a parameter and is used to seed the random number generator. When omitted, the program uses its own logic to seed the generator

-v (verbose): Turn on debugging messages.

-h (help): Print out a help message which tells the user how to run the program and a brief description of the program.

-m (minimum): Set the minimum of the range of numbers the program will select its numbers from.

-M (maximum): Set the maximum of the range of numbers the program will select its numbers from.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output:

Seed = 806189064, Minimum = 1, Maximum = 1000

I'm thinking of a number between 1 and 1000. Go ahead and make your first guess.
>> 500

Sorry that was not correct, please try again...

>> 400

WARMER

>> 600

COLDER

>> 300

WARMER

>> 150

WARMER

>> 100

COLDER

>> 180

COLDER

>> 190

COLDER

>> 130

WARMER

>> 128

WINNER! You have guessed correctly!
It took you 10 attempt(s) to find the answer!

Would you like to play again? (Yes or No): y

------------------------------------------------------------

Make a guess between 1 and 1000

>> 500

Sorry that was not correct, please try again...

>> 600

COLDER

>> 400

WARMER

>> 300

WARMER

>> 280

WARMER

>> 260

WARMER

>> 250

COLDER

>> 256

WINNER! You have guessed correctly!
It took you 8 attempt(s) to find the answer!

Would you like to play again? (Yes or No): n

Thanks for playing!!

Python || Custom Random Number Generator Class MyRNG

The following is sample code for a simple random number generator class. This random number generator is based on the Park & Miller paper “Random Number Generators: Good Ones Are Hard To Find.

This class has three functions. The constructor initializes data members “m_min” and “m_max” which stores the minimum and maximum range of values in which the random numbers will generate.

The “Seed()” function stores the value of the current seed within the class, and the “Next()” function returns a random number to the caller using an algorithm based on the Park & Miller paper listed in the paragraph above. Each time the “Next()” function is called, a new random number is generated and returned to the caller.


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

===== DEMONSTRATION HOW TO USE =====

Use of the above class is very simple to use. A sample function demonstrating its use is provided on line #64 in the above code snippet.

After running the code, the following is sample output:

SAMPLE OUTPUT:


1037, 1296, 1123, 1900, 1375, 1676, 1798, 662, 664, 674, 746, 1249, 793, 1578, 1112,

Python || Pdf Merge Using PyPdf

The following is a simple pdf file merger program which utilizes the “pyPdf” library to manipulate pdf files. This program has the ability to merge entire selected pdf files together, and save the selected files into one single new pdf file.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

PyPdf - What Is It?
How To Create Executable Python Programs
Display The Time In Python
Metadata With PyPdf
Pdf Merge Executable File - Click Here To Download

This program first asks the user to place the pdf file(s) they wish to merge into a specified folder. The default input folder is titled “Files To Merge.” After the input pdf file(s) have been placed into the specified input folder, the program prompts the user to select which file(s) they wish to merge together. As soon as the input pdf file(s) have been selected, the file merging begins, with the files being saved to the output pdf file in the exact same order as specified by the user. As soon as the file merging is complete, the single merged pdf file is saved into an output folder titled “Completed Merged Files.”


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Click here to download a Windows executable file demonstrating the above use.

Python || Pdf Split & Extract Using PyPdf

The following is a simple pdf file split & extractor program which utilizes the “pyPdf” library to manipulate pdf files. This program has the ability to extract selected pages from an existing pdf file, and save the extracted pages into a new pdf file.

REQUIRED KNOWLEDGE FOR THIS PROGRAM

PyPdf - What Is It?
How To Create Executable Python Programs
Display The Time In Python
Metadata With PyPdf
Pdf Split Executable File - Click Here To Download

This program first asks the user to place the pdf file(s) they wish to extract pages from into a specified folder. The default input folder is titled “Files To Extract.” After the input pdf file(s) have been placed into the specified input folder, the program prompts the user to select which file they wish to extract pages from. As soon as an input pdf file has been selected, the user is asked to enter in the page numbers they wish to extract from the specified input pdf file. After the page extraction is completed, the selected pages are merged into one single pdf file, and is saved into an output folder titled “Completed Extracted Files.”


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Click here to download a Windows executable file demonstrating the above use.

Python || How To Install PyPdf Using Python 3

pyPdf” is a pure Python library built as a PDF toolkit. It is capable of:

• Extracting document information (title, author, ...),
• Splitting documents page by page,
• Merging documents page by page,
• Cropping pages,
• Merging multiple pages into a single page,
• Encrypting and decrypting PDF files.

By being pure Python, it should run on any Python platform without any dependencies on external libraries. It can also work entirely on StringIO objects rather than file streams, allowing for PDF manipulation in memory. It is therefore a useful tool for websites that manage or manipulate PDFs.

=== 1. INSTALLING PYPDF ===

A Windows installer for pyPdf is available here. At the time of this writing, the installer that was listed on the download page was titled “pyPdf-1.13.win32.exe.”

Note: If you are using Python 2 and want to install pyPdf, the Windows installer available on the download page should be all you need. No further installation instructions are necessary.

Next, follow the command prompts from the installer and wait!

When the pyPdf installer is completed, you should see the newly installed files which correspond to this module located in the following directory:


C:\Python32\Lib\site-packages\pyPdf

Note: Python 3.2 is installed on my system, and the above directory reflects that. The Python directory may be named something different on your individual system depending on the Python version you are using.

If everything installed correctly, proceed to the next step.

=== 2. UPDATE EXISTING PYPDF FILES ===

pyPdf was originally written for Python 2, but a Python 3 compatible branch has since been made available. The updated files can be found here, and enable pyPdf to be integrated with Python 3.

To update these new Python 3 files with the old Python 2 files, locate the following directory on your system:


C:\Python32\Lib\site-packages\pyPdf

Here is a sample screenshot demonstrating the files which resides in the above directory: (click to enlarge)

Next, update all of the old Python 2 files that’s listed in the above directory with the new Python 3 files that’s listed on this page.

One way to update the files that’s currently stored on your computer is to locate the file on your system with the exact same file name as listed here, and copy/paste the contents of the new file into the contents of the old file that’s currently stored on your computer.

Or you can download all of the files at once here, and move/replace these new files with the existing files that’s currently located on your system.

=== 3. UBUNTU USERS ===

If you are an Ubuntu Linux user and want to install pypdf, open the terminal and run the following command:

NOTE: Replace “python3.2” with whatever version of python that’s installed on your system.


sudo mkdir /usr/local/lib/python3.2/dist-packages/pyPdf


Next, copy and paste the files located in the above download link into the following directory:


/usr/local/lib/python3.2/dist-packages/pyPdf


Once the following steps are completed, you should now be ready to use pyPdf with Python 3 programs!

Python || How To Create An Executable Using Cx_Freeze

Python is a simple and powerful programming language for scripting and application development. Various GUI packages available for Python makes it a great choice for developing applications. But what if you want to create an executable file from the Python script you just created? This page demonstrates that process using a free third party module called “cx_Freeze.” This module is ideal for use because it supports Python 2.7 or higher, including Python 3.

Contents

1. Introduction
2. Installing cx_freeze
3. Verify Installation
4. Create The Setup Script
5. Begin Compilation
6. Output Directory


1. Introduction

cx_Freeze is a set of scripts and modules for freezing Python scripts into executables, in much the same way that py2exe and py2app do. Unlike these two tools, cx_Freeze is cross platform and should work on any platform that Python itself works on. It supports Python 2.7 or higher, including Python 3.


2. Installing cx_freeze

In the terminal (cmd), install by running the following command:


pip install cx-Freeze

– OR –


python -m pip install cx-Freeze

If this process completes with no errors, skip to the next step!

Note: If using Windows and you get an error that says 'python' is not recognized as an internal or external command, a simple solution is to navigate in the terminal (cmd) to the directory of your Python installation folder, and then follow the steps below.

The default Python installation directory is the following:


C:\Users\YOUR_USERNAME\AppData\Local\Programs\Python\Your-Python-Version\

Once you have navigated to the Python folder for the version you are using, in the terminal (cmd), run the following command.


python.exe -m pip install cx-Freeze

Tip: If you want to run the Python command from the terminal without having to navigate to the installation folder, it is recommended that you add your Python directory to the Windows Path. Click here for information on how this is done.


3. Verify Installation

Once the cx_Freeze installation is complete, you should see the newly installed files for this module located in the following directory (Windows):


C:\Path-To-Your-Python-Version\Lib\site-packages\cx_Freeze

If everything installed correctly, you should now be ready to create executable Python programs!


4. Create The Setup Script

To use cx_Freeze we need to create a setup.py file which tells the cx_Freeze “compiler” what you want to do. Here’s a sample setup.py file whose simplicity is appropriate for our sample “Hello World” program.

This is the sample Python file.

This is the setup.py file.


5. Begin Compilation

In order to start compiling the hello.py file, we need to open the terminal (cmd).

Next, once you have created the setup.py file, save the setup.py file into the same directory as your project, and run the following command in the terminal (cmd) from your project directory:


python setup.py build

This command essentially starts compiling the hello.py file.

If this process completes with no errors, skip to the next step!

Note: If using Windows and you get an error that says 'python' is not recognized as an internal or external command, a simple solution is to copy and paste the setup.py file and ALL of the Python files associated with your project into the directory of your Python installation before running the command.

The default Python installation directory is the following:


C:\Users\YOUR_USERNAME\AppData\Local\Programs\Python\Your-Python-Version\

Note: I have Python installed in the following directory, so the steps below will use this path.


C:\Python39

Here is a sample screenshot of the instructions after copy and pasting the files into the Python installation directory: (click to enlarge)

Next, copy and paste these commands into the terminal (cmd).

#1. Change directories into your Python installation folder


cd C:\Python39

#2. Start compiling the hello.py program using the setup.py file


python.exe setup.py build


6. Output Directory

If the cx_Freeze build finished with no errors, then the process should be complete!

By default, the Python executable should be located in a folder titled ‘build‘, located in the same directory as where your setup.py resides.

If you followed the steps above to copy and paste your files during the build process, it should be located at the following:


C:\Path-To-Your-Python-Version\build\exe.win-3.9

Here is a sample screenshot demonstrating the directory where the executable file resides: (click to enlarge)

Note: In order for the executable file to run, the other files within that folder that are generated by cx_Freeze must be bundled with the executable file at all times.

And there you have it! Here is a sample screenshot of the running ‘Hello World’ executable: (click to enlarge)

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Python || Snippet – How To Input Numbers Into A List & Display Its Contents Back To User

This snippet demonstrates how to place numbers into a list. It also shows how to display the contents of the list back to the user via stdout.

REQUIRED KNOWLEDGE FOR THIS SNIPPET

Python Lists
For Loops


QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Once compiled, you should get this as your output

How many items do you want to place into the list?: 3

Enter item #1: 6
Enter item #2: 4
Enter item #3: 2008

The current items inside the list are:
Item #1: 6
Item #2: 4
Item #3: 2008

Python || Using If Statements & String Variables

As previously mentioned, you can use “int” and “float” to represent numbers, but what if you want to store letters? Strings help you do that.

==== SINGLE CHAR ====

This example will demonstrate a simple program using strings, which checks to see if the user entered the correctly predefined letter.

Notice in line 11 I declare the string data type, naming it “userInput.” I also initialized it as an empty variable. In line 23 I used an “If/Else Statement” to determine if the user entered value matches the predefined letter within the program. I also used the “OR” operator in line 23 to determine if the letter the user entered into the program was lower or uppercase. Try compiling the program simply using this
if (letter == 'a') as your if statement, and notice the difference.

The resulting code should give this as output

Please try to guess the letter I am thinking of: A
You have guessed correctly!

==== CHECK IF LETTER IS UPPER CASE ====

This example is similar to the previous one, and will check if a user entered letter is uppercase.

Notice in line 21, an If statement was used, which checks to see if the user entered data falls between letter A and letter Z. We did that by using the “AND” operator. So that IF statement is basically saying (in plain english)

IF ('letter' is equal to or greater than 'A') AND ('letter' is equal to or less than 'Z')

THEN it is an uppercase letter

The resulting code should give this as output

Please enter an UPPERCASE letter: g
Sorry, 'g' is not an uppercase letter..

==== CHECK IF LETTER IS A VOWEL ====

This example will utilize more if statements, checking to see if the user entered letter is a vowel or not. This will be very similar to the previous example, utilizing the OR operator once again.

This program should be very straight forward, and its basically checking to see if the user entered data is the letter A, E, I, O, U or Y.

The resulting code should give the following output

Please enter a vowel: K
Sorry, 'K' is not a vowel..

==== HELLO WORLD v2 ====

This last example will demonstrate using the string data type to print the line “Hello World!” to the screen.

The following is similar to the other examples listed on this page, except we display the entire string instead of just simply the first character.

The resulting code should give following output

Please enter a sentence: Hello World!
You Entered: 'Hello World!'

Python || Hello World!

This page will consist of creating the typical “hello world!” application. First, open a text editor and save the file as “HelloWorld.py“. The “.py” is the file extension for python applications.

When you have everything loaded up, you will start your code off by declaring a “main” function like so. This should be placed at the bottom of your source code.

In simple terms, line #1 from above tells the python interpreter to check to see if the current source code thats being executed is the main module; and if it is, line #2 tells the python interpreter to look for the function within the source code whose name is “main.”

NOTE: Main functions are not needed in python, but it is worth noting that without the main sentinel, the entire source code will be executed even if the script was imported as a module.

Next, we will define the main function. This should be placed at the top of your source code.

Unlike most programming languages, brackets “{}” are not needed when defining a function, but statements following each function block must be uniformly indented throughout the code. Also, an important fact to remember is, functions must be declared before they are used.

We are halfway finished, now all we have to do is say hello to the world! You will do that by adding this line of code to your program, which basically outputs data to the screen

So when you add everything together, your full code will look something like this

To execute the above code, simply hit the “run” button in whichever IDE you are using. If you are using a unix system along with a text editor, enter the command below in the terminal.


python3 HelloWorld.py

And there you have it. After executing the above code, you should get this as your output


Hello World!