Category Archives: python and pygame

Go Loopy (Part I)

While loop

Repeats the execution of a block of code if its condition is true,  the while loop is sometimes referred to as a repeating if statement because the block of code will only execute if a condition evaluates as True. Using IDLE create and run a file with the following (or download this file and run)

# Initialise what is needed by the game
done = False
score = 0
high_score = 121
# game loop, where a game is played
while not done:
    answer = input('Quit Game(y/n):')
    if 'y' == answer.lower():
        done = True
    # Game Logic, simulate by adding points to the game score
    # can input negative and positive integers
    points = int(input('Enter points won this iteration:'))
    score += points
# Display the score plus if you have the high score
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
elif score == high_score:
    print('Your score equals the high_score of ', high_score)
else:
    print('Your score is ', score)

print('Good Bye')

An example of a run on the console looks like:

while_score

The while statement is on line 6 with where the block of code associated with the while state on lines 7 to 13. The while’s condition uses a ‘not’ operation. This boolean operation inverts the boolean value, i.e. inverts True to False and inverts False to True.

When the program executes line 6,  it evaluates the condition to check if we are not done. If this condition is True, i.e. when done is False, then the while’s block of code is executed.

The block of code repeats until the user inputs a ‘y’ or ‘Y’ for the input on line 7,  which causes the variable ‘done’ to be assigned to True and the while’s condition will evaluate to False after completing the while’s block of code.

When the condition evaluates to False the while’s block of code is skipped and code execution skips to line 15 and the score is displayed.

Tuple Type

Like strings tuples are a sequences of used to refer to a set of values. The main difference between tuples and strings is that instead of values been single characters for a tuple the values can be any type,  integers (int),  floats,  strings and even a tuple. As with strings the individual values can be refers using a index to there position in the sequence starting at zero.

Also the values in a tuple once created cannot be changed. Which makes tuples a good type for values that do not change, i.e. constants in a program.

In a python console type the following:

my_info = ('skelly', 'kiernan', 95)
type(my_info)
my_info[0]
my_info[2]
type(my_info[0])
type(my_info[2])
my_info[0] = 'no change'

In the console this will look like:

tuple

Defining Colours

In PyGame tuples are commonly  used to define colours in the form of RGB values.  RGB is a additive colour model based on adding light from Red, Green and Blue light to create the desired colour. The following website gives a short explanation and a color picker that displays the Red, Green and Blue values.

RED    = (255,   0,   0)
GREEN  = (  0, 255,   0)
BLUE   = (  0,   0, 255)
YELLOW = (255, 255,   0)
BLACK  = (  0,   0,   0)
WHITE  = (255, 255, 255)

For the example above we define RED ( a constant as do not expect the values in the tuple to change) in terms of it’s RGB components.

Advertisements

Check the Answer

Boolean Type

When asking a question it would be good to be able check if the answer given is right or wrong,  but instead of right or wrong Python uses True or False these are stored as a Boolean type. In python console type the following(or download this file and run)

is_correct = False
print(is_correct)
is_correct = True
print(is_correct)
print(type(is_correct))

On the console see the following:

bool_type

Relational Operators

To compare an answer with an expected answer relational operators are used to compare two objects and return a True or False. The objects can be numbers,  strings and booleans. The following are relational operators that are commonly used

  • ==‘  is equal (note difference with assignment operator)
  • !=‘ not equal
  • <‘ less than
  • >‘ greater than
  • <=‘ less than or equal too
  • >=‘ greater than or equal too

In a python console type the following:

answer = 7
answer > 10
answer < 10
answer != 7
answer == 7

On the console see the following:

relational_console

IF/ELIF/ELSE Statement

IF statement gives a program the ability to select if a block of code executes or not based on a condition,  for example using a relational operator. In python a block of code is where a group lines of code have the same minimum level indentation, how far to right the start of the line begins( recommended 4 spaces). Using IDLE create and run a file with the following code for input values 10, 100 and 110. (or download this file and run)

Note: IDLE will indent automatically.

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
print('Your score is ', score)

On the console see the following:

if_only

For the if statement on line 3,  when score is greater than 100 the condition is true and the block of code at lines 4 and 5 runs and displays the new high score. If the score is less than or equal to 100 the block of code at lines 4 and 5 is skipped. Line 6 is outside the block and is always run and displays your score.

Using an else statement gives us the ability to select which of two blocks of code is run based on the condition in the if statement. Using IDLE create and run a file with the following code (or download this file and run):

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
else:
    print('Your score is ', score)

On the console see the following:

if_else

The block of code associated with the else statement is only executed when the condition in the if statement is false. So if the score is less than or equal to than 100 ‘Your score’ is displayed if the score is greater than 100 then ‘New High Score’ is displayed.

We can also use the elif statement to select a single block of code from a number of different conditions. Note that elif is short for else if.

Using IDLE create and run a file with the following code (or download this file and run):

high_score = 100
score = int(input('Input a score:'))
if score > high_score:
    high_score = score
    print('New High Score ', high_score)
elif score == high_score:
    print('Your score equals the high_score of ', high_score)
else:
    print('Your score is ', score)

On the console see the following:

elif

In the above example,

  • the block associated with the if statement(lines 4 and 5) is only executed when score is greater than 100
  • the block associated with the elif statement(line 7) is onky executed when score is equal too 100
  • the block associated with the else statement(line 8) is only executed when all the previous if and elif conditions are False,  in this example when score is less than 100

Note: can have as many elif conditions and blocks as need.

A Quiz Question

The final example shows how to check if a given answer to a question is correct,

Using IDLE create and run a file with the code below (or download this file and run) and input the following:

  • The correct value: Dublin
  • An correct value but using all lowercase characters: dublin

This example shows that checking string values can be difficult as only a small unexpected difference have unexpected results been displayed.

score = 0
city = input('What city is the capital of Ireland? ')
if city == 'Dublin':
    score += 3
    print('Correct')
else:
    score -= 1
    print('Wrong,  Correct answer is Dublin')
print('Your score is ', score)

On the console see the following:

quiz


Ask a Question

Show the Question

As well as numbers python can operate on text, called strings. Where a string is just a sequence of characters, in Python the type is named ‘str‘. Below is an example of using a variable to refer to a string. In the Python console type the following

question = 'What is your name? '
print(question)

The quotation mark lets Python know that a string is starting and a closing quotation to end the string. Where both single and double quotations can be used.

question = "What is your age? "
print(age)

When talking about numbers we pictured that the number to be contained within  a box.  For a string we can picture a string as a stack of boxes where each box contains a single character.

string-stack_boxes

Assigning a variable to a string can be pictured as attaching the label to the stack of boxes (not the boxes that contains the characters).

To refer to a single character in a string we use the index number of the box.The index reflects it’s position in the string, where the first character index is 0, second character is 1 and so on. In a Python console type the following ( or download from here)

name = 'Skelly'
print(name)
print(name[0])
print(name[1])
print(name[2])
print(name[5])

Using IDLE to run the code should see the following

name

Rather than depicting these with images an easier way (to draw anyway) is with a diagram like below:

name_dia

Note: In Python there is no type for a single character and each container in a string for a character is a string that contains a single value,  in the Python Console type the following shows the class of the container used to store the first character of ‘Skelly’ is a string (str) itself.

name = 'Skelly'
type(name)
type(name[0])

As with numbers we can perform operations on strings, in a python console type the following:

'Spider' + 'man'
'Ho ' * 3

There is a lot more that can be done with strings in Python,  and these will be explored later as needed, but first exploring how to use python to get an answer.

Get an Answer

After asking a question there needs to be a way to allow the user input an answer, using IDLE create a python file and type in the following code: (or download file from here)

print('What is your name? ')
name = input()
greeting = 'Hello ' + name
print(greeting)
print('"name" refers to a', type(name), end=' ')
print('that contains', name)

Using IDLE to run the code should see the following
hello_you

When running we see that the input function waits for a line to be typed in, and returns the string of characters you typed. In the example above we used the variable ‘name’ to label the returned string containing the characters of the typed in line.

Note: instead of having to print the question we can place the question string in the input function, which reduces the amount of typing to ask a question and get an answer.

name = input('What is your name? ')
print('Hello ' + name)

The string inside the parentheses, (), after input is called the prompt, prompting you that keyboard input is expected at that point.  As the input function returns a string we need to add some more code to convert to an integer (int) or float when we expect the answer to be a number. Add the following code to the Python file created earlier ( or download full program/script from here)

age = input('What age are you? ')
age = int(age)
print('Your age is ', age)
print('"age" refers to a', type(age), end=' ')
print('that contains', age)
# suspicious question next !!!, be careful
# which questions you answer truthfully
money = input('How much money is in your pocket you? ')
money = float(money)
print('You have €', money)
print('"money" refers to a', type(money), end=' ')
print('that contains', money)

Running in IDLE should see

a_bit_personal

Try running the program and type in answers that are not numbers to see what happens !!! (Generally for any program this is a good test as users of a program will always do something different to what the programmer expected. For example when asked age a valid answer is ‘nine’ rather than 9 as expected by the program above.


Python as a Calculator

To use the Python console as a calculator, Open IDLE
StartIDLE_001

In the Python console type the following:

13 + 5
39 - 13
5 * 3
12 / 2
10 % 3

In the Python Console will see the following
cal_000a
As can be seen python preforms the following operations resulting a number (for the  expressions above):

  • +‘ performs addition
  • ‘ performs subtraction
  • *‘ performs multiplication
  • /‘ performs division
  • %‘ performs a modulo operation, returns the remainder after a division

The result of the the division operation result appears different, it has a decimal point
cal_001a
This highlights that Python has two types of numbers,

  • Integers (int), whole numbers sometimes called counting numbers i.e. numbers without fractions
  • Floats (float), any number with a decimal point and are used when when more precision is need. As dollars and euros have cents, meters have centimeters, grams have milligrams a lot of real world measurement units can be divided.

Expressions are not limited to just one operator and can have many, but need to be careful of operator precedence ( i.e. which operators are evaluated first). For example in the following code is the result of the expression on line 1 equal to 16 or 13 and on line 2  equal to 1 or 10

1 + 3*4
12 - 8/4

The result of the expression on line 1 is equal to 13 and on line 2 equal to 10 as  the multiplication and division have a higher precedence than addition and subtraction. For the python operators see here, highest precedence operators are listed first below

  1. *‘, ‘/‘, ‘%‘ (multiplication, division and modulo)
  2. +‘, ‘‘ (addition and subtraction)

Variables

Variables are used by nearly all programs and  give programs a great deal of flexibility. Variables can be used to refer to anything a program needs,  to display,  change or use. The first usage explored here is to use variables is to refer to numbers.

In Python we can  think of variables as labels that refer to a box( or container) that contains a value such as the score in a game, the result of calculation, an answer to a question or even portion of a program that can perform a calculation. Where there are different types of boxes (or containers) such as an integer and float to hold different types of numbers.

Below is an example of a variable that refers to a number used to store the score of a game. In this example the assignment operator(‘=‘ ) is used to label an integer that contains the value:

score = 400294

cal_007

Below is an program  that uses variables to update the score and health of a character in a game. The program also uses a variable to get a value that does not change, i.e. a constant used to add a bonus

In a python console type the following:

BONUS = 10
score = 0
# character fell while climbing a tree
health = 100 - 6
print(health)
# character reached top tree
score = score + 24
# found golden coin in the tree
score = score + BONUS
print(score)
# fell again
health = health - 6
print(health)

Note: The text after ‘#’ is ignored by Python and are comments typically used to explain the meaning of code, also in the code the subtraction of 6 occurs twice where we should use a variable with a meaningful name in these expressions, e.g.

 FALL_PENALTY = 6

The advantage of using a variable is that if we want to change the variable we only need to change it in one place plus it makes the code easier to read,

 health = health - FALL_PENALTY

indicates why health has decreased.

 

cal_003

Up until now we have using the python console which can be slow,

  • Open File, on the IDLE menu press File, then press New File from the drop down menu and a new window will appear
    cal_004
  • Copy or type the code into the new window(Can also download from here)
    cal_005
  • Save file, On the keyboard press CTRL+S or on the menu press File, then Save on the drop down menu and a “Save As” dialog will appear. In the dialog select an location and name for the file with a “py” extension, i.e. example.py
    cal_006
  • Run the script, on the keyboard press F5 or on the menu press Run, then Run Module on the drop down menu
    cal_008
  • On the IDLE Console window will see
    cal_010

The advantage is we run this code as many times and when we like without having to type in all in again. In IDLE press File on the menu, then Open on the drop down menu and a Open Dialog will open which will allow selection of a python file.

Note: To reduce the amount of typing programming languages often have operations that reduce the amount of typing a programmer needs to do to achieve an effect(often these operations are run faster as when a program is executed) in the example code there are two such examples

score = score + 24

can be directly replaced by

score += 24

And

health = health - 4

can be directly replaced by

health -= 4

 

In Python these are called “augmented assignment” operators and as well as addition and subtraction there are multiplication, division and modulo versions as well, i.e.

result = 5
result *= 4
result /= 2
result %= 3

 


PyGame and Python Online Resources

The web has alot of good and bad to help get started with Python and PyGame the following is a collection free online resources that I would call very good

  1. http://programarcadegames.com/, has online videos, labs,  quizes and worksheets
  2. http://inventwithpython.com, a number of online books, (free to download)
  3. http://www.codecademy.com/tracks/python,  Codeacademy python online tutorials

The above sites provide very good guidance on getting started programming with Python and PyGame. Over the next few months the steps needed to program a game will be covered,  but first say hello to python

greeting = "Hello Python!"
print(greeting)

Python + PyGame Install

The following are instructions for a Windows Computer to:

  1. Install Python
  2. Install PyGame
  3. Run a PyGame Example

Note: After should see the following space game

aliens_game

Note also that for Linux the following website has instructions

Install Python

  • Download Python 3.4.2 from https://www.python.org/downloads/
    PythonDownload
  • Run the installer(python-3.4.2.msi) and follow the on screen instructions
  • Press Run Button on the “Open File – Security Question” Dialog for “Do you want to run this file?” question
    pythonsecurityquestion3
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Select whether …” question
    PythonSetup_001
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Select Destination Directory” question
    PythonSetup_002
  • Press Next button on the “Python 3.4.2 Setup” Dialog for “Customize Python 3.4.2” question
    PythonSetup_003
  • Press Yes for “User Account Control” Dialog
  • Press Finished button on the “Python 3.4.2 Setup” Dialog for “Complete the Python 3.4.2 Installer” question
    PythonSetup_004

Install PyGame

  • Download PyGame from pygame-1.9.2a0-cp34-none-win32.whl (Now on a Dropbox as link keeps breaking)
  • Copy the file pygame-1.9.2a0-cp34-none-win32.whl to the directory C:\python3.4\Scripts
  • Open a Command Window in the directory C:\python3.4\Scripts
  • In windows Explorer Press Shift Key and the Right button on the mouse
  • Select “Open command window here”
    CommandWindow
  • In the Command Window type “pip3 install pygame-1.9.2a0-cp34-none-win32.whl”
    pygame_install

Run a PyGame Example

  • Using the Windows Start Button, Select “All Programs” and Find the IDLE Python GUI
    StartIDLE_001
  • Double click “IDLE (Python 3.4 GUI – 32 bit)”,  the following screen will appear
    IDLE_PYTHON_CONSOLE
  •  Type in the following command, to check that PyGame is correctly installed:
import pygame
  • Type in the following commands to run an example game, to check that PyGame is working
import pygame.examples.aliens as game
game.main()

IDLE_RUN_PYGAME


damian mooney

bits and bytes