ICS2O
Introduction to Computer Studies - Grade 10
Introduction to Computer Studies - Grade 10
Overview | Computing basics | [HTML] | [smallBASIC] | [Python] |Construct | ActionScript | GameMaker | Kodu | Summative
Link to Python's Binary . Once you have Python installed. In the shell:
The best way to install pygame is with the pip tool (which is what python uses to install packages). Note, this comes with python in recent versions. We use the --user flag to tell it to install into the home directory, rather than globally. We MUST RUN THIS COMMAND FROM THE COMMAND PROMPT.
To get the command prompt we have to do the following:
py -m pip install -U pygame
To see if it works, run one of the included examples:
py -m pygame.examples.aliens
If it works, you are ready to go!
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).
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:
print("Hello World!");
Hit <Enter> 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
2*7
<Enter>
What now, if we wanted to start entering multiple lines of code? Try it in your main window (called the shell). Type the following:
print("This will work");
print("because I want it to");
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:
print("This will work");
print("because I want it to and I did it right this time");
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:
print ("This will work
because I want it to");
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:
print("This will work \n because I want it to and I did it right this time");
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 ")
print('This will work\n because I want it to and I did it right this time')
You can also set print functions (or any others) by using variables.
days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday']
print(days);
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':
Variables should be named:
ballRectangleVariableName = "String Variable"
or
ballRectangleCoordinateName = (43,80)
While functions should be named like this:
function_name_of_thing_youknow()
Keywords contain lowercase letters only.
and
exec
not
assert
finally
or
break
for
pass
class
from
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:
i=10
if i >= 10:
print('the number is greater than 10')
else:
print(' the number is less than 10')
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.
i=10
if i >= 10:
print ('the number is greater than 10');
else:
print(' the number is less than 10');
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:
# I know this will work because I'm writing the example
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');
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 :
print(2*4)
print(2/8)
print(6+8)
print(1987-2584)
print(2**10)
print(34%8)
print((2^4)/18)
You can also use the built-in math module to solve math equations (or more complex things than subtraction/addition/multiplication/division0. Try this in IDLE
import math #imports the math module
print(math.sqrt(135))
If you wanted to use this in a more complicated program then you'd use the IDLE program editor and write it as such:
import math
mathAnswer = math.sqrt(135)
print(mathAnswer);
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:
print("Halt!");
s = input("Who Goes there? ")
#notice the use of the \ below to force the print to 1 line.
#printedName = "You may pass, " + s + ". \n Have a nice day!" commented because this structure isn't needed in python 3.6.x
#print(printedName); #in older versions you couldn't add strings and string-variables within the print command, this is why we 'manually' added them in the line above. In the version of python we're using you can simply write:
print("You may pass, " + s + ". \n Have a nice day!");
To bring in a number variable we must use an EVAL command which lets the program know that a number is being input.
numberVariable=eval(input("Enter a variable "))
print(numberVariable)
#note, you STILL have to separate out some math functions on a separate line (and not in the print line) for any number variable. For example:
print(numberVariable * 2) #note this works. However
print (numberVariable=numberVariable +1) #doesn't. To fix it you'd have to have numberVariable=numberVariable +1 as a separate line, then use print(numberVariable afterwards)
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:
#Calls on the random library
import random
#executes the call to pull a random integer between 0 and 8
b =random.randint(0,8)
print (b)
Alternatively - you could get the same thing by using FROM.
#Calls on the random library
from random import *
#executes the call to pull a random integer between 0 and 8
b =randint(0,8)
print (b)
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.
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 a string form.
number = input("This is going to be a number stored for future use: ")
#number = float(number) #to be uncommented FIRST
#number2 = eval(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)
#number = number/1.8347
#number = round(number,3)
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 is: ", number2*2)
print ("Your number multiplied by 2.0 is: ", number*2.0)
print ("Your number multiplied by 2.00 is: ", number*2.00)
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.
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.
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:
for i in range(0,10):
print ("Hello",i)
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:
for i in range(0,10):
print ("Hello",i)
print ("this is the bitter end")
print ("this is the true end")
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).
for i in range(0,10):
print ("Hello",i)
break
print ("this is the bitter end")
Neat huh? The break command will be used in abundance while programming in Python.
Iteration increases can also be done as follows:
j = 20
for i in range(0,10):
print ("Hello",i)
j += 5
print (j)
#break
print ("this is the bitter end")
Much like the for loop, the while loops are quite similar in structure to SB but altered in their syntax slightly.
z=50
c='*'
while z >= 10:
print(z)
for i in range(0,5):
print(c)
z = z-10
Notice this is FAR more like the SB structure we once used. Again, the <break> 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)
z=50
c='*'
while z >= 10:
print(z)
for i in range(0,5):
print(c)
break
z = z-10
And, of course, everybody's favorite, the guessing game!!!!
# Waits until a password has been entered. Use control-C to break out without
# the password
#note that != means not equal
#this next line must be there or the variable is considered undefined
password = 'temporary'
#the loop begins
print("Please enter a password");
while password != "unicorn":
password = input("Password:");
#if password == "quit" or == 'exit': #or password == "exit":
#break;
print("Welcome in");
Let's look at control structures now.
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;
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")
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.
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....');
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!
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:
randomFunction()
sub randomFunction
'does something
endSub
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.
def correct():
print("That is the correct number");
def incorrect():
print("That is not right!");
#r=0 #un-comment 1st
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
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.
Ready for this massive difference between SB and Python. What does this do?
# Program by Mitchell Aikens
# No copyright
# 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()
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:
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()
Yup - *boom* Exploding head. Super-useful though.
Function Returns
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.”
import math
def area(radius):
return math.pi * radius**2
radius = eval(input("Please enter the radius of the circle \n" ));
answer = area(radius);
print(answer)
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".
Arrays are similar and different in python. For example, the traditional form of:
variable[index]
is still used (or can be used).
However, we have to "initiate" the array prior to use in Python. This is done as follows:
i=0
myList =[0 for i in range(5)]
for i in range(5):
myList[i]=input("Enter a name")
print(myList[i])
print(myList[3])
This will set i to 0, then initialize the array in line two. By line 3 we see the traditional for loop (or it could be a while loop if we wanted) that allows for repeated input/interaction. By line 4 we are storing name X/Y/Z as myList[1] or myList[2] etc... We're showing the input in line 5 and printing ONLY index 3 in line 6.
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
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. You 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 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:
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);
Pygame is a set of Python modules designed for writing games. Pygame adds functionality on top of the excellent SDL (Simple Direct-Media 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.
#imports the SDK library for pygame
import pygame, sys
from pygame.locals import *
# Initialize Pygame.
pygame.init()
# Set size of pygame window.
screen=pygame.display.set_mode((640,480))
#sets loop condition to true
mainloop = 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()
#Finish Pygame
pygame.quit()
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.update()function. 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:
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).
# 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
# Initialize Pygame.
pygame.init()
# Set size of pygame window.
screen=pygame.display.set_mode((640,480))
# Create empty pygame surface.
background = pygame.Surface(screen.get_size())
# Fill the background white color.
background.fill((255, 255, 255))
# Convert Surface object to make blitting faster.
background = background.convert()
# Copy background to screen (position (0, 0) is upper left corner).
screen.blit(background, (0,0))
#screen.blit(background, (50,50)) #uncomment after displaying.
# Create Pygame clock object.
clock = pygame.time.Clock()
mainloop = True
# Desired framerate in frames per second. Try out other values.
FPS = 30
# How many seconds the "game" is played.
playtime = 0.0
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()
# Finish Pygame.
pygame.quit()
# At the very last:
print("This game was played for {0:.2f} seconds".format(playtime))
Now - let's look at creating surfaces and drawing on the surface.
#the next three lines of code are CRUCIAL to all games made in pygame
import pygame, sys
from pygame.locals import *
pygame.init()
#set up the window surface
DISPLAYSURF = pygame.display.set_mode((500,400),0,32)
pygame.display.set_caption('Drawing')
#set up the colours
BLACK = (0,0,0)
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
x=0
y=0
#DRAW ON THE surface object
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()
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
#run the game loop
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))
## i=0
## j=0
## if x >=400:
## for i in range(0,6):
## j = j +50
## 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()
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.
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
# 3 - Load images - we use the convert_alpha because the boy.png is a PNG file and thus supports transparencies, otherwise we'd
# just use .convert() only
player = pygame.image.load("makinggames_src/boy.png").convert_alpha()
x = 50
y = 50
# 4 - keep looping through
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()
pygame.quit()
What about something more complex?
""" 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
"""
# 1 - Import library
import pygame
from pygame.locals import *
# 2 - Initialize the game
pygame.init()
width, height = 640, 480
screen=pygame.display.set_mode((width, height))
#sets up key entries as all false
keys = [False, False, False, False]
#sets up initial player position
playerpos=[100,100]
# 3 - Load images
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")
# 4 - keep looping through
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
#
#note, this also would have worked, though it clearly isn't as useful as movement
#is limited to the single key-press as opposed to the brief time we've pressed down
#the key
# if event.key==K_w:
# #player's y position is -5
# playerpos[1] += -5
# elif event.key==K_a:
# playerpos[0] += -5
# elif event.key==K_s:
# playerpos[1] += 5
# elif event.key==K_d:
# playerpos[0] += 5
# 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
pygame.quit()
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)
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.
#this first array example is flexible. You don't need to know the size of the array ahead of time
numbers2 = []
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"]]
##orrrrrrrrr you can use this - this is when you know your array dimensions, indexes and elements inside
## 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])
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
# For questions 5-7, refer to this line of code:
pygame.draw.line(screen,green,[0,0],[100,100],5)
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.
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.