ics2O_python

include component="page" page="course_tabs_header"

include component="page" page="menu_ics2O_crumbs"

=Python= [edited to reflect the changes in Python 3.x] Link to [|Python's Binary]and [|Pygame's binary]. Note they NEED to be in the same directory. Right-click and Save_As...

Overview
You've got one programming language under your belt now - the next one's going to be easy!!! Python is a high-level (so uses syntax closer to English, rather than low-level which is closer to machine-language), structured (which means that code has one entry-point and one exit-point and avoids dangerous goto statements which can cause conflict in command structure), open-source programming language that can be used for a wide variety of programming tasks. Python is the language used in the development of such games as Battlefield, Civilization (4), EVE Online as well as hundreds of others. In addition programs and web-apps such as Dropbox, Bittorrent and Blender are written in Python.

[|ALL THINGS PYTHON] can be found on the official tutorial site. However, I prefer [|THIS BOOK] to get the ins and outs of regular python programming. Once you understand python you can start to appreciate [|PYGAME](a set of modules specifically crafted to enable video game design to be easier).

The basics
To start with, let's look at the very first output in a new language. Once you've opened the Python shell GUI IDLE we're ready to program type the following: code format="python" print("Hello World!"); code Hit  and see what happens.

So it's obvious that when using IDLE (Python's Editing window) you need not 'run' code to see it in action - the shell itself can execute the code on-the-fly. Prove it to yourself by typing in code 2*7 code 

What now, if we wanted to start entering multiple lines of code? Try it in your main window (called the shell). Type the following: code format="python" print("This will work"); print("because I want it to"); code You can't get to the 2nd line right? What you need to do in order to get this work is enter Python's Editing window. CTRL-n opens IDLE (which you should promptly save as 'test.py'). NOW try typing in:

code format="python" print("This will work"); print("because I want it to and I did it right this time"); code

We can hit F5 (just as in Small Basic) to get the code to run in the shell. However, is there an easier way of getting this to print over 2 lines? Well, if we want to carry the sting past a single line we need to end the line of code with '\n\'. Try the following: code format="python" print ("This will work because I want it to"); code This won't work because Python doesn't know how to interpret the 2nd line, or know why the first line doesn't end properly. Instead try this: code format="python" print("This will work \n because I want it to and I did it right this time"); code Single quotes will also work instead of double-quotes (but only if you don't need an apostrophe in your text, otherwise you're stuck with ") code format="python" print('This will work\n because I want it to and I did it right this time') code You can also set print functions (or any others) by using variables. code format="python" days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday'] print(days); code

There is one fundamental difference in Python with Small Basic (well, there are quite a few differences, but for the purposes of my point let's ignore those). In Small Basic, capitalized and uncapitalized variables (called identifiers in Python) were interchangeable. In Python the identifier Skinnymonkey is different than the identifier skinnymonkey. Make note of that as it will be the bane of your existence should you often forget. For the purposes of 'best practices':

code format="python" Variables should be named:

ballRectangleVariableName = "String Variable"

or

ballRectangleCoordinateName = (43,80)

While functions should be named like this: function_name_of_thing_youknow

code

Here is a list of reserved words (commands) in Python:

Keywords contain lowercase letters only.
 * and || exec || not ||
 * assert || finally || or ||
 * break || for || pass ||
 * class || from || print ||
 * continue || global || raise ||
 * def || if || return ||
 * del || import || try ||
 * elif || in || while ||
 * else || is || with ||
 * except || lambda || yield ||

When entering code in Python it is important to note that code is run hierarchically by indentation. If your indentation is off, then the debugger will yield an error. Try the following: code format="python" i=10 if i >= 10: print('the number is greater than 10') else: print ' the number is less than 10' code

First off, notice that I'm NOT typing in THEN, instead a simple colon is sufficient. Next, notice the code won't run. Why? Because the 1st and 2nd print lines are not indented properly. As in Small Basic, the code is indented properly if we simply hit enter after the 'else:' command.

code format="python" i=10 if i >= 10: print ('the number is greater than 10'); else: print(' the number is less than 10'); code

Another important feature of programming languages is the comment feature. In Python comments are denoted by a #. For example, using the previous lines of code: code format="python" i=10 if i >= 10: print ('the number is greater than 10'); #and I can comment here too!!! else: print(' the number is less than 10'); code
 * 1) I know this will work because I'm writing the example

In Python, there are a couple small changes with arithmetic operations - the standard operations are unchanged *, /, -, + but if you want an exponent, it is done by two multiplication signs side-by-side ** or " ^ ", and a remainder (modulus - the division with what's left over returned) is %.

Try these directly in the shell:

code format="python" 2*4 2/8 6+8 1987-2584 2**10 34%8 2^4/18 code

You can also use the built-in math module to solve math equations (or more complex things than subtraction/addition/multiplication/division0.

code format="python" import math #imports the math module math.sqrt(135) code

If you wanted to use this in a more complicated program then you'd use the IDLE program editor and write it as such:

code format="python" import math mathAnswer = math.sqrt(135) print(mathAnswer); code

But what about when you want to add true variables to the mix? Let's say you want to do the equivalent of textwindow.read....here's how we accomplish this in Python:

code format="python" print("Halt!"); s = input("Who Goes there? ") printedName = "You may pass, " + s + ". \n Have a nice day!" print(printedName); #you can't add strings and string-variables within the print command, this is why we 'manually' added them in the line above code
 * 1) notice the use of the \ below to force the print to 1 line.

One last little bit of code for you, before the assignment. When we want to pull a random number in Python, we first call on the random library (not within the math library like it was in small basic), then pull our random number:

code format="python" import random b =random.randint(0,8) print (b) code
 * 1) Calls on the random library
 * 1) executes the call to pull a random integer between 0 and 8

code format="python" from random import * b =randint(0,8) print (b) code
 * Alternatively - you could get the same thing by using FROM**.
 * 1) Calls on the random library
 * 1) executes the call to pull a random integer between 0 and 8

Assignment #8
1. Write a program that prints your full name and your birthday as separate strings. 2. Write a program that shows the use of all 6 math functions. 3. Write a program that requires a user to input their first name as a variable, then their second name as a variable, then displays them both together with a print command. 4. Write a program that pulls a random number between 4 and 85, then multiplies it by a user inputted number between 10 to 20. The answer is then printed. [note: by default the input command inputs strings, to make it integers you need to use something of the form numberVariable = eval(input("prompt of some kind")] 5. Write a program that prompts the user for a time, then spits out the Bugatti Veyron's speed (assuming it's a Bugatti 16.4 with steady acceleration and a top speed of 431 km/h). #approx acceleration is 35 km/h/s 6. Write a basic program that reads the user's input of their marks in their courses, then displays their rounded numerical average in a cleared window. 7. Write a basic program that both creates, then displays 5 random numbers between 1 and 100 8. Write a program that gets 2 string variables and 2 integer variables from user input. [|Concatenate]the 2 string variables and print them in the same line as the integers. Finally, multiply the two numbers on a new line.

Variables
In Python, as in Small Basic, you can use variables to hold user-inputted data. The two types of user-entered data are the same as in Small Basic: Integers (numbers) and Strings (text). By default Python assumes entry of information into a variable is in an string form. code format="python" number = input("This is going to be a number stored for future use: ") string = input("This is going to be a string, you can tell because the code says input not eval(input), int(input) or float(input): ") print ("Your number is: ", number) print ("Your string entry is: ", string) print ("Your string entry multiplied by 2 is: ", string*2) print ("Your number multiplied by 2 is: ", number*2) print ("Your number multiplied by 2.0 is: ", number*2.0) print ("Your number multiplied by 2.00 is: ", number*2.00) code You can see what happens when you take a number and multiply it by 2, as opposed to a string. Also note: when we uncomment lines 2, 3, 7, 8 and 11 we are examining ways of inputting, then manipulating string and number variables. By default IN OLDER VERSIONS OF PYTHON (2.X) THE DEFAULT ENTRY WAS A NUMBER, NOW IT IS A STRING.
 * 1) number = float(number)
 * 2) number2 = eval(input("This is going to be a number stored for future use: "))
 * 1) number = number/1.8347
 * 2) number = round(number,3)
 * 1) print ("Your number multiplied by 2 is: ", number2*2)



Loops
So, we've begun playing around with Python and entering variables. After doing simple sequential coding in Small Basic we started performing more complex coding with loop structures. If you recall there were two major forms of repetition we talked about in class the "for" and the "while" loop.

For loops
The structure of a for loop is slightly changed from Small Basic, but it remains a powerful tool in reusing lines of code. The structure looks like this: code format="python" for i in range(0,10): print ("Hello",i) code

Notice this works exactly as we'd expect from our experiences in Small Basic. The only major changes include the fact we don't have to enter endfor as it is implied when we lose our indenting structure as we can see from the code below:

code format="python" for i in range(0,10): print ("Hello",i) print ("this is the bitter end") print ("this is the true end") code

What if we want to stop the loop for whatever reason? We can simply do this by putting in a control structure (if/then/else) or a simple "break" command (which was not available in Small Basic). code format="python" for i in range(0,10): print ("Hello",i) break print ("this is the bitter end")

code Neat huh? The break command will be used in abundance while programming in Python.

Iteration increases can also be done as follows:

code format="python" j = 20 for i in range(0,10): print ("Hello",i) j += 5 print (j) #break print ("this is the bitter end") code

While loops
Much like the for loop, the while loops are quite similar in structure to SB but altered in their syntax slightly.

code format="python" z=50 c='*' while z >= 10: print(z) for i in range(0,5): print(c) z = z-10 code Notice this is FAR more like the SB structure we once used. Again, the command can be used to end the loop structure (you RARELY use break commands unless you are using then in conjunction with a control structure of some kind (if/then/else) code format="python" z=50 c='*' while z >= 10:   print(z)    for i in range(0,5):        print(c)    break    z = z-10 code And, of course, everybody's favorite, the guessing game!!!! code format="python"
 * 1) Waits until a password has been entered.  Use control-C to break out without
 * 2) the password

password = 'temporary' print("Please enter a password"); while password != "unicorn": password = input("Password:"); #if password == "quit" or == 'exit': #or password == "exit": #break; print("Welcome in"); code Let's look at control structures now.
 * 1) note that != means not equal
 * 2) this next line must be there or the variable is considered undefined
 * 1) the loop begins

Control structures
With the exception of replacing the full text of elseif in SB with elif, there's no difference between control structures in SB vs. Python. For example; code format="python" i=0 while i <10: r=i%2 i=i+1 if r == 0: print (i, "modulus 2 is", r, " the remainder is equal to 0") else: print (i, "modulus 2 is", r, " the remainder is equal to 1") code Notice we have an **if** statement and an **else** statement. Of course we could throw an elseif statement in there too, and let's tie it to a break command. code format="python" i=0 while i <10: r=i%2 i=i+1 if r == 0: print (i, "modulus 2 is", r, " the remainder is equal to 0"); elif i == 8: print ('end of the line pilgrim'); break; else: print (i, "modulus 2 is", r, " the remainder is equal to 1"); print ('the program has ended....'); code When i is equal to 8 then the command break is initiated and the program ends. Notice however that the next line of code still runs AFTER the control structure because of indenting!



Function
Lastly, the subroutine function in SB has been replaced by the **function** in Python. Its use is interchangeable with calling a subroutine in SB. __Additionally__, in SB, the function command was never examined in its pure form as a named sequence of statements that performs a computation. In SB when you called a subroutine you wrote, for example:

code randomFunction

sub randomFunction 'does something endSub code

But in SB, calling math.getRandomNumber is ALSO a function. So in Python, you call functions which can either be the subroutines we're familiar with from SB (where the user defines the function by name and it runs some user-defined set of code) AND it is also a sequence of statements that runs some pre-defined "thing" like math.sqrt.Below - notice how the function is defined at the beginning of the code? Also notice how r is set to 0 to begin with, otherwise the program doesn't know how to start the while loop. Uncomment the r=0 command at the beginning to start. code format="python" def correct: print("That is the correct number"); def incorrect: print("That is not right!"); while r!=16: r = input('Please enter a number between 1 and 20: ') #comment this out at 4th step un-commenting r = eval(input) #type(r) #notice r in the line above is a string because the default variable is a string - un-comment 2nd and use from IDLE command #r = eval(input('Please enter a number between 1 and 20: ')) #un-comment 3rd #type(r) #now we have a number input for r instead un-comment 4th and use from IDLE #r = int(r) #un-comment 5th #type(r)#if we wanted we just wrote-over the string variable with the forced-conversion and use from IDLE at 5th step #of r to a number with the int (or float would have worked too) function if r==16: correct #break elif r==12: print("Holy jeez!") #break else: incorrect #break
 * 1) r=0 #un-comment 1st

code

As I stated at the beginning of the course - once you learn 1 program language (SB in your case) all others will follow suit. We will discuss some of libraries associated with Python next.

Function Recursion
Ready for this massive difference between SB and Python. What does this do? code format="python"
 * 1) Program by Mitchell Aikens
 * 2) No copyright
 * 3) 2012

def main: loopnum = int(input("How many times would you like to loop?\n")) counter = 1 recurr(loopnum,counter)

def recurr(loopnum,counter): if loopnum > 0: print("This is loop iteration",counter) recurr(loopnum - 1,counter + 1) else: print("The loop is complete.")

main code

Wait - what was that noise. Yup - that was your head exploding! A function can call itself!!!! This is immensely useful in running snippets of code without having to worry about overt control structures. Recursion is usually used to solve complex problems, that can be broken down into smaller, identical problems.

For example: code format="python" def main: num = int(input("Please enter a non-negative integer.\n")) fact = factorial(num) print("The factorial of",num,"is",fact)

def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1)

main code

Yup - *boom* Exploding head. Super-useful though.

 Thusfar we've only really seen functions as blank returns (that is to say that they run, but variable information stored within disappears as soon as the function is over. For sending information garnered within the function back to the main program we use a **RETURN**. The example above uses returns (return num*factorial(num-1)). The return means : “Return immediately from this function and use the following expression as a return value.” code format="python" import math
 * Function Returns**

def area(radius): return math.pi * radius**2

radius = eval(input("Please enter the radius of the circle \n" )); answer = area(radius); print(answer) code This function runs when the area(radius)is called with the main body of code and variable radius having been input by the user. The value is then sent into the function and the answer (return math.pi * radius **2) sent BACK to the code as the value calculated and made equal to the variable "answer".

Assignment #9
1. Try making a program that captures the user's height and weight and spits our their BMI to 2 decimal places. [Use the formula at [|BMI Formula]] 2. Fix [|the following code] 3. Modify the password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times print ``That must have been complicated.'' 4. Write a program that asks for two numbers. If the sum of the numbers is greater than 100 print ``That is big number''. 5. Write a program that asks the user their name if they enter your name say "That is a nice name" if they enter "John Cleese" or "Michael Palin" tell them how you feel about them - otherwise tell them "You have a nice name". 6. Write a program that counts down from 200 to 50 only printing even numbers 7. Create a fully functional text-based calculator (i.e. not graphical) that can store up to 5 results and can return results for any normal operations. 8. Write a function that prompts the user to input values for a, b, c and n, converts them to integers. Use these numbers and write a function called "check_fermat" to check whether they violate Fermat’s theorem. [hint: you'll need to look up Fermat's theorem] 9. Take [|the following code]and comment it explaining what each step does including a comment with the final output 10. Fix [|the following code]

Python Quiz
Write a **fully documented** program which prompts the user for:

* their name * a number between 1 and 5

The number will be multiplied by another randomly generated number between 3 and 8. Y ou will give the user a hint as to the range the resulting number is in. For example:

"Your number is between 1 and 10" "Your number is between 11 and 20"

"Your number is between 21 and 30"

"Your number is between 31 and 40"

After this prompt - have the user guess at the number and continue until they get it right. Finally print the correct answer and thank the user (by name) for playing.

__**Evaluation:**__ As always, documentation - 2/10 logic - 4/10 functionality - 4/10



Modules
Modules are sets of pre-packaged functions that are grouped together with commonality of design. For example, built-into the main distribution of Python are the Math and Random modules. They are called first by importing them as such:

code format="python" import math import random def ma_formula(a, b, c): return a * b * c;

a = math.pi; b = random.randint(2,288); c = eval(input("Enter your number here: \n")); print(str(a) + ", " + str(b) + ", " + str(c)) answer = ma_formula(a, b, c); print(answer);

code 

Pygame as a module
Pygame is a set of Python modules designed for writing games. Pygame adds functionality on top of the excellent SDL (**S**imple **D**irect-**M**edia Layer) library. This allows you to create fully featured games and multimedia programs in python.

It's a good habit to get into to always include the following code into EVERY SINGLE GAME YOU DEVELOP IN PYGAME.

code format="python" import pygame, sys from pygame.locals import *
 * 1) imports the SDK library for pygame

pygame.init
 * 1) Initialize Pygame.

screen=pygame.display.set_mode((640,480))
 * 1) Set size of pygame window.

mainloop = True
 * 1) sets loop condition to true

while mainloop== True: # the events for the game will be listed here. we include the quit condition because without it, #  you can't quit the game and it causes your system to hang. It's good practice to get use to using it in EVERY game as the first if statement. for event in pygame.event.get: # User presses QUIT-button. if event.type == pygame.QUIT: mainloop = False #rest of your code goes in here pygame.display.flip pygame.quit
 * 1) Finish Pygame

code

By using the code above you import the pygame module, you set the size of the screen and you want, start the loop condition for the contents of the game and MOST CRUCIALLY - YOU CREATE AN QUIT CONDITION. If you don't set the loop to crash it will freeze Python when you go to test the program.

The most common cause of inadequate frame rates in pygame programs results from misunderstanding the pygame.display.updatefunction. With pygame, merely drawing something to the display surface doesn't cause it to appear on the screen - you need to call pygame.display.update. There are multiple ways of calling this function - I'll show 2:
 * 1) pygame.display.update - This updates the whole window (or the whole screen for fullscreen displays)- this refreshes the WHOLE screen which limits you (on a standard machine running a standard resolution) to 28 fps. That is unacceptably slow for most people.
 * 2) pygame.display.flip - This does the same thing, and will also do the right thing if you're using doublebuffered hardware acceleration. Again, not the fastest way to update the screen.

In more advanced graphics you only refresh those parts of the screen that have shown dedicated movement and thus the framerate can be much faster.

Let's look at a more complete program. While it doesn't do much, it does illustrate some key points. Foremost is the blitting process. Blitting stands for bit-level block transfer and is when several bitmaps are combined together to produce a final composited (combined) image. While it is necessary to do so to add various "layers" to a screen, in the end it is not as efficient as sprite-manipulation (which keeps the other images in a separate memory and NOT the main surface-display memory).

code format="python"
 * 1) the triple quote outlines a multi-line comment

""" Open a Pygame window and display framerate. Program terminates by pressing the ESCAPE-Key.

URL   : http://thepythongamebook.com/en:part2:pygame:step002 Author : horst.jens@spielend-programmieren.at License: GPL, see http://www.gnu.org/licenses/gpl.html """

from __future__ import print_function import pygame

pygame.init screen=pygame.display.set_mode((640,480)) background = pygame.Surface(screen.get_size) background.fill((255, 255, 255)) background = background.convert screen.blit(background, (0,0)) clock = pygame.time.Clock
 * 1) Initialize Pygame.
 * 1) Set size of pygame window.
 * 1) Create empty pygame surface.
 * 1) Fill the background white color.
 * 1) Convert Surface object to make blitting faster.
 * 1) Copy background to screen (position (0, 0) is upper left corner).
 * 1) screen.blit(background, (50,50)) #uncomment after displaying.
 * 2) Create Pygame clock object.

mainloop = True FPS = 30 playtime = 0.0
 * 1) Desired framerate in frames per second. Try out other values.
 * 1) How many seconds the "game" is played.

text2 = ": no keypress"

while mainloop: # Do not go faster than this framerate. milliseconds = clock.tick(FPS) # the += is the same as saying add to the previous value of the variable the new information. In small basic you'd have to say # milliseconds = milliseconds + clock.tick(FPS) playtime += milliseconds / 1000.0

for event in pygame.event.get: # User presses QUIT-button. if event.type == pygame.QUIT: mainloop = False elif event.type == pygame.KEYDOWN: # User presses ESCAPE-Key if event.key == pygame.K_ESCAPE: mainloop = False if event.key == pygame.K_r: text = " OMG this Works!"

# Print framerate and playtime in titlebar. Equivalent of saying graphicsWindow.title in SmallBasic text = "FPS: {0:.2f}  Playtime: {1:.2f}".format(clock.get_fps, playtime) pygame.display.set_caption(text + text2)

#Update Pygame display. pygame.display.flip

pygame.quit
 * 1) Finish Pygame.

print("This game was played for {0:.2f} seconds".format(playtime))
 * 1) At the very last:

code

Now - let's look at creating surfaces and drawing on the surface.

code format="python" import pygame, sys from pygame.locals import * pygame.init
 * 1) the next three lines of code are CRUCIAL to all games made in pygame

DISPLAYSURF = pygame.display.set_mode((500,400),0,32) pygame.display.set_caption('Drawing')
 * 1) set up the window surface

BLACK = (0,0,0) WHITE = (255,255,255) RED = (255,0,0) GREEN = (0,255,0) BLUE = (0,0,255)
 * 1) set up the colours

x=0 y=0

DISPLAYSURF.fill(WHITE) pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106))) pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4) pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120)) pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4) pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0) pygame.draw.ellipse(DISPLAYSURF, RED, (300, 250, 40, 80), 1) pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50)) PIC = pygame.image.load("d:/temp/ball.gif").convert
 * 1) DRAW ON THE surface object

pixObj = pygame.PixelArray(DISPLAYSURF) pixObj[480][380] = BLACK pixObj[482][382] = BLACK pixObj[484][384] = BLACK pixObj[486][386] = BLACK pixObj[488][388] = BLACK del pixObj

done = False while done == False: for event in pygame.event.get: #user did something if event.type == QUIT: #user clicks on close done = True #changes our loop condition to false thus ending it       if event.type == MOUSEBUTTONDOWN: #calls the x, y coordinates from the mousebuttondown event x, y = event.pos #x_pos = str(x) #y_pos = str(y) #pygame.display.set_caption(x_pos + ", " + y_pos) pygame.draw.circle(DISPLAYSURF,RED,(x,y),3,1) #DISPLAYSURF.fill(BLACK) #DISPLAYSURF.blit(PIC,(x,y))
 * 1) run the game loop
 * 1)            i=0
 * 2)            j=0
 * 3)            if x >=400:
 * 4)                for i in range(0,6):
 * 5)                    j = j +50
 * 6)                    pygame.draw.circle(DISPLAYSURF, RED,(j,y), 3, 1)

#event = pygame.event.wait #very useful in relatively static applications to keep the CPU useage low. pygame.display.update pygame.quit

code

In this example we show the standard startup in the first 3 lines of code. We set up the display surface called DISPLAYSURF (a variable name). We then set up the colours with the appropriate variable names. Also we gave the values x and y starting conditions so that when it came to call them inside our main loop they had an appropriate starting location.

We then draw a variety of shapes on the surface showing off the various pygame draw commands. PIC is a variable. This use is a lot like using the "shapes" command in Small Basic. We use the .convert to help render times.

The next command (pygame.PixelArray) shows rudimentary array use in python.

Now for the "game" loop. We set up the exit/quit condition why making done = False. Once in the loop we set the default exit for the event.type QUIT. We ALSO start making the game-code. We give an event.type==MOUSEBUTTON to make a simple interactivity. As we uncomment the code we can start to see the range of things possible in pygame is just like small basic.

Let's look at the precursor to something more interactive now.

code format="python" import pygame from pygame.locals import *
 * 1) 1 - Import library

pygame.init width, height = 640, 480 screen=pygame.display.set_mode((width, height))
 * 1) 2 - Initialize the game

player = pygame.image.load("makinggames_src/boy.png").convert_alpha
 * 1) 3 - Load images - we use the convert_alpha because the boy.png is a PNG file and thus supports transparencies, otherwise we'd
 * 2)      just use .convert only

x = 50 y = 50

loop = True while loop == True: for event in pygame.event.get: # check if the event is the 'X' button at top right if event.type==pygame.QUIT: # if it is quit the game loop = False if event.type == MOUSEBUTTONDOWN: #if event.type == MOUSEMOTION: x,y = event.pos # clear the screen before drawing it again # screen.fill(0) # draw the screen elements screen.blit(player, (x,y)) # update the screen pygame.display.flip
 * 1) 4 - keep looping through

pygame.quit

code

What about something more complex?

code format="python" """ from: Julian Meyer

http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python

Game resources package here: http://cdn3.raywenderlich.com/downloads/BB_Resources.zip

"""

import pygame from pygame.locals import *
 * 1) 1 - Import library

pygame.init width, height = 640, 480 screen=pygame.display.set_mode((width, height)) keys = [False, False, False, False] playerpos=[100,100]
 * 1) 2 - Initialize the game
 * 1) sets up key entries as all false
 * 1) sets up initial player position

player = pygame.image.load("BB_Resources/resources/images/dude.png") grass = pygame.image.load("BB_Resources/resources/images/grass.png") castle = pygame.image.load("BB_Resources/resources/images/castle.png")
 * 1) 3 - Load images

loop = True while loop == True: # loop through the events for event in pygame.event.get: # check if the event is the X button if event.type==pygame.QUIT: # if it is quit the game loop = False # the movement will occur as long as the keydown event occurs if event.type == pygame.KEYDOWN: # keys[0] means that the variable keys at array position 0 is set to true if event.key==K_w: keys[0]=True elif event.key==K_a: keys[1]=True elif event.key==K_s: keys[2]=True elif event.key==K_d: keys[3]=True # this will be used to stop the motion if event.type == pygame.KEYUP: if event.key==pygame.K_w: keys[0]=False elif event.key==pygame.K_a: keys[1]=False elif event.key==pygame.K_s: keys[2]=False elif event.key==pygame.K_d: keys[3]=False # displayes the key set on the title for debuggins key_display = str(keys) pygame.display.set_caption(key_display) # 5 - clear the screen before drawing it again screen.fill(0) #defines the ranges as integers x_range = int(width/grass.get_width) y_range = int(height/grass.get_height) # drawing the castles and blue background 'grass' for x in range(x_range+1): for y in range(y_range+1): screen.blit(grass,(x*100,y*100)) screen.blit(castle,(0,30)) screen.blit(castle,(0,135)) screen.blit(castle,(0,240)) screen.blit(castle,(0,345)) # 6 - draw the screen elements screen.blit(player,playerpos) # 7 - update the screen pygame.display.flip # 8 - Move player playerpos[1] which is the playerpos[y] value so, if 'W' was pressed # then keys[0] was made true then playerspos[1] - or the y value of player position # is subtracted by 5 as long as the key was pressed down. Note the same code could have been # acheived by writing #      if keys[0] == True: #          playerpos[1] = playerpos -5 # note also that the Y movements have been isolated with if/elseif statemetns if keys[0]: playerpos[1]-=5 elif keys[2]: playerpos[1]+=5 if keys[1]: playerpos[0]-=5 elif keys[3]: playerpos[0]+=5
 * 1) 4 - keep looping through
 * 1) note, this also would have worked, though it clearly isn't as useful as movement
 * 2) is limited to the single key-press as opposed to the brief time we've pressed down
 * 3) the key
 * 4)            if event.key==K_w:
 * 5)                #player's y position is -5
 * 6)                playerpos[1] += -5
 * 7)            elif event.key==K_a:
 * 8)                playerpos[0] += -5
 * 9)            elif event.key==K_s:
 * 10)                playerpos[1] += 5
 * 11)            elif event.key==K_d:
 * 12)                playerpos[0] += 5
 * 1)                playerpos[0] += 5

pygame.quit code

While it seems complex, let's analyze it. In the game initialization steps (Section #2) we are setting up screen height/width and setting up the default key entries as all being false. We also set up the playerpos value of x=100 and y=100.

In section #3 we load the game resources and make them equal to a variable name (just like "shape" in small basic).

In section #4 we have the main-game loop. We take care of the QUIT condition first, then start looking for activity. The first thing the code sniffs for is the Keydown event. When a KEYDOWN event is found to have happened it quickly evaluates if the event was with the w, a, s, or d keys. If it is then the variable array "**keys**" is set to 0, 1, 2 or 3. The same thing could have worked if we set each to their own "flag" like wFlag, aFlag, sFlag or dFlag being True. Using that 1-dimensional array (or linear array) is FAR more useful though. Think of it like a single battleship game row, you ONLY are calling for A (or in this case "keys") and at position [number-varies]. So row a at column position 6 is A[6] (you sunk my battleship).



A 2 dimensional array would mean that you have both a row array as well as multiple columns. Here is shown Rows and Clumns for the 2D array **"Name".** So that row 2 column 5 would return small 'e'. That would be displayed as follows:

print(Name[2][5]) would print the letter 'e' to the screen



Immediately after the KEYDOWN event is the KEYUP event. The game piece is moved only as long as we're pressed down. If we commented this section out, then we would have our little rabbit friend run forever in a particular direction.

Lastly in this first section before #5 we have a debug line or two of code which displays on the caption what's pressed (by first converting the keypress to a string)

Section #5 clears the screen quickly before redrawing it with the towers and the grass. It then blits them back onto the screen.

In section #6 we blit the player back on in his position.

In section #7 we update the screen (redraw) committing the changes to the surface.

In section #8 we change the player's X/Y values (only to be redrawn on the next loop). Arguably these should be before the player's new position is blitted, but the refresh occurs so quickly it doesn't matter for the purposes of this demonstration. Try moving all of block 8 to before Section #6. You'll see that gameplay is unaffected.

In section #8 we also have to tackle the actual movement code. As commented in the code, player playerpos[1] represents the playerposition y value. This is a 1 dimensional array with 1 row - player, and 2 columns, X and Y. So, if 'W' was pressed then keys[0] was made true, and playerspos[1] and is subtracted by 5 units per loop cycle as long as the key was pressed down. In short, w subtracts 5 from the Y value of Playerpos - which is used to move the player.

=Example of array use in python= code format="python" numbers2 = []
 * 1) this first array example is flexible. You don't need to know the size of the array ahead of time

for i in range(2): temp_string = input("enter a number: ") #stores your input numbers2.append(temp_string) #appends your input from temp_string into the next array entry

for i in range(len(numbers2)-1) #counts down from existing index number print (numbers2[i])

code format="python"


 * 1) orrrrrrrrr you can use this - this is when you know your array dimensions, indexes and elements inside
 * 2) for example when you know you're on a 400x600 screen and each pixel has an index element

numbers=[i for i in range(3)] #if you know the range for your index (e.g. 300x300 pixels or somesuch)

for i in range(3): numbers[i] = int(input("enter 3 values")); for i in range(3): print(numbers[i])

code

 =Assignment # 10= Submit commented code that solves the following: 1. Make a screen with a #003D5A colour background that is a user-defined size. You must have 4 geometric entities on the screen (e.g. line, triangle, square and point) 2. Using your knowledge of code, create a pattern on the screen that only uses 1 shape. [hint, think loops] 3. Make an image in paint.NET that is controlled by w, a, s, d keys. on a continually cleared screen (i.e. no "trails" of past movement) 4. Use the image you made for #3 and make a program that controls the character with the mouse code format="python" pygame.draw.line(screen,green,[0,0],[100,100],5)
 * 1) For questions 5-7, refer to this line of code:

code 5. What does screen do? 6. What does [0,0] do? What does [100,100] do? 7. What does 5 do? 8. Write a program that draws and bounces a rectangle up and down in the middle of the screen 9. Write a program that uses your image and code from #3. Include now a score tied to the game timer where every 5 seconds is 1 point. Have the game stop when the score reaches 5 points. 10. Use the code from number #3 and #9 to make a simple game that randomly spawns a rectangle somewhere on the screen. If your player happens to be in the rectangle when it spawns you die.

 =Assignment #11=

Port your game from Game-Off #3 over to Python. Most of you won't have a problem, however, there will be some getting used to the new timer function and colour detection.