Python 2024
Python 2024
NAME :________________________
CLASS :________________________
Content by:
www.aimsity.com Aimsity
TABLE OF CONTENT
TURTLE MODULE
8 Introduction 17
9 Setting up the window 18
10 Drawing using Python Turtle 19-23
11 Colour them up! 23-24
12 Circle 24-26
13 Combining the shapes 27-29
14 Project 1: Drive it 30-33
15 Project 2: Let them race! 34-45
16 Project 3: Aliens war! 46-64
2
Introduction
Python is a text-based programming language and it is easy to learn (a high
programming language). Widely use in company such as Google, Facebook,
Amazon and etc.
Flow of a program
A program it’s like our human brain where we take in information (input) and process
it into output.
Activity 1
1)Can you give an example of a situation involving input→process→output?
3
Notes
● To comment on the use “# or ‘ ”
Notice we need to
input “ 3 times as
we have 3 lines of
comments.
Variables
Variables are used to store information which can be in text (string) or number
format.
For example:-
Input Output
We had created a file name “robot” to store our information. The information stored
is the number “3”. When use “print” command we are actually asking the computer
to display the information stored in the file.
4
Activity 2
a = 2
b = 3
c = ‘shark’
Math = a+b
Notes
●Variable’s name can be in letters or numbers but always start with a letter.
●Symbols such as -, /, # or @ are not allowed.
●Spaces won’t be recognized.
●The name “Timer” and “timer” is different item in Python as Uppercase and Lowercase
is recognized differently in Python.
●The word that is use as a command in Python should also be avoided such as print,
def, if and etc.
Data Types
There are several data types that are commonly use in Python. In this lesson, we will
focus on 3 types of data which are Numbers, Strings and Booleans.
Numbers
There are 2 types of numbers available which are “Integers” and “Floats”. Integers
are numbers without decimal points which is also known as “whole numbers”. This is
usually use for counting objects. Floats are number with a decimal point which is
usually use to measure and objects.
5
Numbers
Integers Floats
(Example: 2) (Example: 2.3)
We can use this to solve various mathematical questions with the combination of
variables.
Notes
The mathematical symbols use in programming is slightly different from the ones you learn
in your math class.
SYMBOL DESCRIPTION
+ ADDITION
- SUBSTRACTION
* MULTIPLICATION
/ DIVISION
For example,
(Below can be done using the shell window for quick outputs)
>>> 10 + 2
12
>>> 10 / 2
5.0
(In Python, division will always return a float number)
>>> (4 + 2) * 3
18
(Like in your math class, brackets can be use emphasize which part of the equation
to do first. In this case, 4+2=6 then only we take 6*3=18)
>>> 10 - (6 / 2)
7
6
>>> #Using variables in an equation
>>> robots = 20
>>> spaceships = 3
>>> tech = robots + spaceships
>>> print (tech)
23
Activity 3
1)Using the above example of the variables in an equation, what will happen if we
continue the code as below?
>>> robots = 20
>>> spaceships = 3
>>> tech = robots + spaceships
>>> print (tech) Type this below
>>> spaceships = 5
>>> print (tech)
3)Sarah is selling cookies to raise funds for a local charity. She sells 3 types of
cookies-Chocolate, Butter and Caramel cookies. She has 10 boxes of Chocolate
cookies, 15 boxes of Butter cookies and 8 boxes of Caramel cookies.
7
Activity 3(cont’d)
ii)If she has sold 5 boxes of Chocolates cookies, what is the total cookies she has?
iii)If she has split the boxes of Caramel cookies by a quarter to give to her brother,
how many boxes of caramel cookies are left to sell?
iv)If 1 box of cookies is RM2.50 and she has sold 10 boxes, how much has she
earned?
Strings
Strings are referred to the text/sentences in the code. We can also use addition
symbol to join sentences together. Keep in mind you can’t add string type data and
number type data.
For example,
>>> a = ‘Learning ’
>>> b = ‘is fun!’
>>> c = a + b
>>> print(c)
Learning is fun!
#Keep in mind you can’t add string type data and number type data.
To know the length of the string we can use the “len()” function.
>>>print(len(a))
9
(The number return my Python includes all the characters and spaces inside the
string)
Sometimes we need to use string and numbers together.
8
For example,
>>>Ava_age = input (‘How old is Ava?’)
>>>Aim_age = input (‘How old is Aim?’)
>>>print( Ava_age+Aim_age)
How old is Ava? 2
How old is Aim? 3
23
#The answer 23 is wrong as the answer is supposed to be 5. This happens
because when we input the questions the computer recognises it as string.
Therefore, it will treat 2 and 3 as string instead of numbers. We can fix
this using the code below.
>>>print( Ava_age+Aim_age)
How old is Ava? 2
How old is Aim? 3
5
9
We can create patterns using strings.
OUTPUT
>>> print(‘’, ‘8’*2, ‘’, ‘8’*2)
>>> print(‘8’, ‘’, ‘8’, ‘’, ‘8’)
>>> print(‘8’, ‘’, ‘ ’, ‘8’)
>>> print(‘’, ‘8’, ‘ ’, ‘8’)
>>> print(‘ ’, ‘8’, ‘ ’, ‘8’)
>>> print(‘ ’, ‘8’)
For each character in the string it is automatically allocated a number based on the
position of the character in the string. We can extract the characters based on the
position number of the character.
For example,
A I M S I T Y Python always
count from 0
0 1 2 3 4 5 6
>>> a = ‘AIMSITY’
10
Activity 4
1)From the word “Everything” can you find out the below words using code?
E V E R Y T H I N G
i)Every
ii)Very
iii)Thing
Boolean
Boolean always has 2 outcomes, “True” or “False”. Boolean is commonly use to help
program make decision on what to do.
OPERATORS DESCRIPTION
== EQUALS TO
(Uses 2 equal signs as one is to assign a
value to a variable)
!= NOT EQUAL TO
> GREATER THAN
< LESS THAN
>= GREATER THAN OR EQUAL TO
<= LESS THAN OR EQUAL TO
11
For example,
>>> software_engineers = 5
>>> hardware_engineers = 3
Or
Activity 5
1) >>> alien = 6
>>> spaceship = 3
>>> attack = ‘Ka boom’
Write down the code and the outcome for the below questions.
i) Is alien equals to 5 or spaceship equals to 3
ii) Is alien equals to 6 and attack equals to ‘Ka boom’ or is alien equals to 6 and
spaceship equals to 2
12
Loops
Sometimes in programming we need to repeat certain lines of codes and this can be
time-consuming, therefore, we can use loops (a.k.a. iterations) to control the
repetition of the codes.
“For” loops
This is use when you know how many times you would want to repeat the code.
For example,
13
“For” loops can also be use as a nested loop which is the loop inside an outer loop.
The outer loop will only repeat itself when the nested loop has finished the required
loop.
For example,
‘a’ is between 1,3 range.
>>> x = ‘Hello’ ‘b’ is between 1,4 range.
>>> y = ‘there!’
‘a’ will repeat 2 times.
>>> n = 2 Outer loop ‘b’ will repeat 3 times.
>>> for a in range (1, n+1):
>>> for b in range (1, n+2): Each time the loop runs,
>>> print(x, y) the inner loops will run 3
Hello there! times and in total the
Hello there! outer loop need to run 2
Hello there! Inner loop times.
Hello there!
Therefore, there are 6
Hello there!
repetitions.
Hello there!
“While” loops
“While” loops is use when you are not sure how many times you need to repeat the
action until it reach a certain condition. This is also known as the “loop condition” and
it can be either True or False.
For example,
14
Lists
Lists can be store using the variable. It is made up of a group of values or strings,
separated by commas, between a square brackets [ ].
VALUE LIST
>>> a = 1 >>> ListA = [1, 2, 3]
>>> b = a >>> ListB = ListA
>>> print (‘a=’, a, ‘b=’, b) >>> print (‘ListA=’, ListA,
a= 1 b= 1 ‘ListB=’, ListB)
ListA= [1, 2, 3] ListB= [1, 2, 3]
For example,
>>> print(list2)
>>> print(‘Smallest value =’, a)
>>> print(‘Largest value =’, b)
15
Smallest value = 2
Largest value = 543
list4 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list5 = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
list6 = [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
#Reverse a list
>>> list1 = [1, 2, 3, 4, 5]
>>> list1.reverse()
>>> print(list1)
[5, 4, 3, 2,1]
16
Brain Teaser
string = ‘I am happy’
How to change it to ‘happy I am’?
Functions
Function is a piece of code that will perform a certain task that you had given it. It
groups a set of code into a name and the function can be perform by “calling” the
name.
There are certain functions that are already in Python such as “print()” (to display text
or outcome of a code), “input()”(allow the user to key in data in the program),
“randint()” (generate a random number) and etc
You can also make your own function to store your set of codes.
For example,
You can also combine with the ready function in Python such as “input()”
>>> def num (shark):
>>> key = input(shark)
>>> change_to = int(key)
>>> return change_to
>>> a = num(‘Enter a’)
>>> b = num(‘Enter b’)
>>> print (‘a+b = ’,a + b)
Enter a 6
Enter b 8
a+b = 14
Turtle
Introduction
Turtle graphics is a Logo (derives from Greek, meaning word or thought) programming
language developed by Wally Feurzig and Seymour Papert in 1966. Turtle feature is
like a drawing board, where we can control the turtle to draw what we want.
17
Setting up the window
Before we are able to use the turtle library, we need to import the module from Python
library. Try the below activity to see how to set up the window.
Activity 6
Key in
import turtle #To import the turtle library.
This will make all the turtle functions available to us. Next let’s create our drawing
board which is our window (known as wn) and our turtle (pencil) to draw.
Key in
wn = turtle.Screen() #to set “wn” as the turtle screen
wn.bgcolor(‘blue’) #background colour
wn.title(‘Activity 6’) #top title
#Pencil
pencil = turtle.Turtle() #setting the name and stating it is an object with
capital "Turtle"-class name. The small "turtle" -module name is indicating
it is imported from the turtle library.
Window
title
Pencil
18
Drawing using Python turtle
1)Straight line
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Straight line’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.forward(100) Go forward by 100 pixels. Pixel is the
single point on the screen (the smallest unit
that can be represented). Your computer
screen is made up of tiny small square dots
which are the pixels.
90◦
270◦
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Heading’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.setheading(45) #Set to 45◦
pen.forward(100)
19
If we change heading to (-45)
pen.setheading(-45)
“pen.setheading(-45)”
will be the opposite
direction.
3)Square
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Square’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.pensize(10) #Adjust the
pen size
pen.forward(100)
pen.left(90) #Turn 90◦ left
(anti-clockwise)
pen.forward(100)
pen.left(90)
pen.forward(100)
pen.left(90)
pen.forward(100)
pen.left(90)
20
4)Square at an angle
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Square angle’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.pensize(10)
pen.setheading(45)
pen.forward(100)
pen.left(90)
pen.forward(100)
pen.left(90)
pen.forward(100)
pen.left(90)
pen.forward(100)
pen.left(90)
5)Star
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Star’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.pensize(10)
pen.forward(200)
pen.left(144)
pen.forward(200)
pen.left(144)
pen.forward(200)
pen.left(144)
pen.forward(200)
pen.left(144)
pen.forward(200)
pen.left(144)
21
Activity 7
1)Draw the following shapes with pen size set to 10 and length is 100.
i)Triangle
i)2Square
22
Activity 7 (cont’d)
iii)2Square1Triangle
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Triangle’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.pensize(10)
pen.fillcolor(‘aqua’)
pen.begin_fill()
pen.forward(100)
pen.left(120)
pen.forward(100)
23
pen.left(120)
pen.forward(100)
pen.left(120)
pen.end_fill()
Activity 8
Draw the following square with pen size set to 10 and length is 100.
Circle
● Circumference
● Diameter
● Radius
24
For example,
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Circle’)
#Pen
pen = turtle.Turtle()
pen.pencolor(‘aqua’)
pen.pensize(10)
pen.circle(100)
import turtle
#Window setup
wn = turtle.Screen()
wn.bgcolor(‘black’)
wn.title(‘Circle’)
#Pen
pen = turtle.Turtle()
pen.pensize(10)
pen.color(‘yellow’, ‘aqua’)
pen.begin_fill() -180 is the angle of the
pen.circle(100,180) circle.
pen.end_fill()
25
Activity 9
1)Draw the below shapes
i)
ii)
26
Combining the shapes
We can combine different shapes to make an object.
For example,
import turtle
#Bird House
bird = turtle.Turtle()
bird.speed(10)
bird.pensize(4)
bird.color(‘olive’, ‘saddleBrown’)
bird.setposition(-50, 0)
#Roof
bird.begin_fill()
bird.forward(180)
bird.left(120)
bird.forward(180)
bird.left(120)
bird.forward(180)
bird.left(120)
bird.end_fill()
#Body
bird.forward(25)
bird.right(90)
bird.fillcolor(‘wheat’)
bird.begin_fill()
bird.forward(130)
bird.left(90)
bird.forward(130)
bird.left(90)
bird.forward(130)
bird.left(90)
bird.end_fill()
#Window
bird.penup()
bird.forward(65)
bird.left(90)
bird.forward(30)
bird.right(90)
bird.pendown()
bird.color(, ‘black’)
27
bird.begin_fill()
bird.circle(20)
bird.end_fill()
bird.hideturtle()
Activity 10
1)Draw the below objects.
28
Activity 10(cont’d)
ii)
29
PROJECT 1: DRIVE IT
1)import turtle
import time
-Import the respective modules to use it’s function.
2)#WINDOW SETUP
-Write the title for the next group of codes. Always after importing the necessary
modules then set up the window.
3) wn=turtle.Screen()
-To let the computer knows that we are setting up the window. Take note that for
screen we are using capital “S”.t=turtle.Turtle().
4) wn.bgcolor(‘dark blue’)
-To change the background colour of the window. Notice the spelling of is ‘color’ and
not ‘colour’.
5) turtle.tracer(3)
-Updating the window. Without this the user will see every drawing step in a
complicated image. (no control when the updates occur.)
6) #Pen (body)
pen = turtle.Turtle()
pen.color(‘coral’)
pen.penup()
pen.shape(‘square’)
pen.turtlesize(4,12)
- pen = turtle.Turtle()
=Setting the name and stating it is an object with capital “Turtle()”. If initially we did
not put “from turtle import Turtle” then it would be “turtle.Turtle()” where lowercase
“turtle” indicates the module name where we are importing from turtle library.
- pen.color(‘coral’)
=Setting the pen color.
- pen.penup()
=Lift the pen up before moving it.
- pen.shape(‘square’)
=Draw a square shape.
- pen.turtlesize(4,12)
=Length and width of the square, therefore, changing it into rectangle shape which
will be the body of the car.
30
7) #Pen1 (wheel 1)
pen1 = turtle.Turtle()
pen1.color(‘gray’)
pen1.penup()
pen1.shape(‘circle’)
pen1.turtlesize(2)
- pen1 = turtle.Turtle()
=Setting the name and stating it is an object with capital “Turtle()”. If initially we did
not put “from turtle import Turtle” then it would be “turtle.Turtle()” where lowercase
“turtle” indicates the module name where we are importing from turtle library.
- pen1.color(‘gray’)
=Set the colour of the pen.
- pen1.penup()
=Lift the pen up before moving it.
- pen1.shape(‘circle’)
=Draw the shape circle.
- pen1.turtlesize(2)
=Set the size of the shape.
8) #Pen2 (wheel 2)
pen2 = turtle.Turtle()
pen2.color(‘gray’)
pen2.penup()
pen2.shape(‘circle’)
pen2.turtlesize(2)
-Same as wheel 1.
9) #Pen3 (Floor)
pen3 = turtle.Turtle()
pen3.hideturtle()
pen3.up()
pen3.goto(-460,-95)
pen3.down()
pen3.color(‘green’)
pen3.begin_fill()
for j in range (2):
pen3.fd(900)
pen3.left(90)
pen3.fd(15)
pen3.left(90)
pen3.end_fill()
31
- pen3.up()
= Pull the pen up – no drawing when moving.
- pen3.goto(-460,-95)
= Go to the position (-460,-95)
- pen3.down()
= Ready to draw.
- pen3.color(‘green’)
= Set the pen colour to green.
- pen3.begin_fill()
= Start to fill the shape with colour.
- for j in range (2):
= Repeat the code twice.
- pen3.fd(900)
pen3.left(90)
pen3.fd(15)
pen3.left(90)
= Draw the rectangle.
- pen3.end_fill()
= End filling the shape with colour.
-while True:
= Will repeat the codes forever.
- i=i+1
= With each loop, add 1 to it.
- (x-coordinates + 5*i)
= New x-coordinates
- 0 and -60
= y-coordinates
-time.sleep(0.02)
= pause for 0.02 sec
- if pen.xcor()>350:
i=-1
= if x-coordinates is more than 350 then change ‘i’ back to -1 so the car will start at
the beginning back.
32
33
PROJECT 2: LET THEM RACE!
1) #LET THEM RACE
-Always write the title first. ‘#’ symbol is use to comment during our programming.
The computer will not process this line of codes; therefore, it is useful when we want
to write notes or title for the group of codes.
2) import time
-Import the time library so that we can use its function to freeze our game when we
want to.
3) import turtle
-As we are using turtle library to draw out our game.
6)#WINDOW SETUP
-Write the title for the next group of codes. Always after importing the necessary
modules then set up the window.
7) wn = turtle.Screen()
-To let the computer knows that we are setting up the window. Take note that for
screen we are using capital “S”.
9) turtle.bgcolor(‘green’)
-To change the background colour of the window. Notice the spelling of is ‘color’ and
not ‘colour’.
34
10) turtle.color(‘white’)
-To determine the colour of the turtle on the screen.
11) turtle.speed(0)
-Set the turtle to its fastest speed.
12) turtle.penup()
-As we want to move the turtle to a different position, so before moving it we need to
lift the pen if not there with be a line drawn.
35
14) turtle.write(‘LET THEM RACE!', font = (‘Arial', 30, ‘bold'))
-We want it to write the title on the background.
-‘Arial’ =font type
-30 = font size
15) turtle.penup()
-Lift the pen up again for ease of movement later.
16) #GROUND
-New title.
18) turtle.color(‘SandyBrown’)
-Lift the pen up again for ease of movement later.
36
19) turtle.begin_fill()
-This will fill the turtle with the above SandyBrown colour.
20) turtle.pendown()
-As the program gets ready to draw.
21) turtle.forward(800)
-The turtle will move forward to the right.
22) turtle.right(90)
-Turn clockwise to the right by 90◦.
23) turtle.forward(300)
-The turtle will move forward by 300.
24) turtle.right(90)
-Turn clockwise to the right by 90◦.
25) turtle.forward(800)
-The turtle will move forward by 800.
26) turtle.right(90)
-Turn clockwise to the right by 90◦.
27) turtle.forward(300)
-The turtle will move forward by 300.
28) turtle.end_fill()
-To tell the turtle the shape has finished the fill up process.
37
29) #FINISH LINE
-New title.
30) stamp_size = 20
-Create a variable name ‘stamp_size’ to store the size of the stamp.
31) square_size = 15
-Create a variable name ‘square_size’ to store the size of the square.
34) turtle.color(‘black’)
-Set the finish line color to black.
35) turtle.shape(‘square’)
-The finish line will be in checker square shape.
36) turtle.shapesize(square_size/stamp_size)
- Means 15/20 the size of the turtle also is the size of the square checker stamp.
37) turtle.penup()
-Lift the pen up before moving it.
38
38) for i in range(10):
turtle.setpos(finish_line,(150-(i*square_size*2)))
turtle.stamp()
- “for i in range(10)”
= will draw 10 squares
- turtle.setpos(finish_line,(150-(i*square_size*2)))
= To set position
x= finish_line (which is 200)
y= 150- (i*square_size*2)
- turtle.stamp()
=Activate the stamp
x position y position
200 150 - (0*15*2) = 150-0 = 150
200 150 - (1*15*2) = 150-30 = 120
200 150 - (2*15*2) = 150-60 = 90
200 150 - (3*15*2) = 150-90 = 60
200 150 - (4*15*2) = 150-120 = 30
200 150 - (5*15*2) = 150-150 = 0
200 150 - (6*15*2) = 150-180 = -30
200 150 - (7*15*2) = 150-210 = -60
200 150 - (8*15*2) = 150-240 = -90
200 150 - (9*15*2) = 150-270 = -120
39
39) for j in range(10):
turtle.setpos(finish_line+square_size,((150-square_size)-
(j*square_size*2)))
turtle.stamp()
- “for j in range(10)”
= will draw 10 squares
- turtle.setpos(finish_line+square_size,((150-square_size)-
(j*square_size*2)))
= To set position
x= finish_line+square_size (which is 200+ 15 so the new line is on the right as x is
larger than the previous line)
y= (150-square_size)- (j*square_size*2) (The 150-square_size will put the line one
box below compare to previous line)
- turtle.stamp()
=Activate the stamp
x position y position
200+15 = 215 (150-15) - (0*15*2) = 135-0 = 135
200+15 = 215 (150-15) - (1*15*2) = 135-30 = 105
200+15 = 215 (150-15) - (2*15*2) = 135-60 = 75
200+15 = 215 (150-15) - (3*15*2) = 135-90 = 45
200+15 = 215 (150-15) - (4*15*2) = 135-120 = 15
200+15 = 215 (150-15) - (5*15*2) = 135-150 = -15
200+15 = 215 (150-15) - (6*15*2) = 135-180 = -45
200+15 = 215 (150-15) - (7*15*2) = 135-210 = -75
200+15 = 215 (150-15) - (8*15*2) = 135-240 = -105
200+15 = 215 (150-15) - (9*15*2) = 135-270 = -135
40
40) turtle.hideturtle()
-Hide the turtle.
41) #TURTLE 1
-New title.
43) turtle1.speed(0)
-Set the turtle to its fastest speed.
44) turtle1.color(‘black’)
-Set the color.
45) turtle1.shape(‘turtle’)
-Set the shape. There are several shapes available. Please refer to the Turtle
Cheatsheet for the list of shapes available.
46) turtle1.penup()
-Lift the pen up before moving to a new position.
48) turtle1.pendown()
-Put the pen down and get ready to draw.
41
49) Repeat step 37-43 for TURTLE2, 3 and 4 but change the turtle number, colour
and position of the turtle.
42
50) time.sleep(1)
-Pause the game for 1 second before starting the race.
-The turtles will move in total 0-144 pixels. Each turtle will move at random (1-4 pixel)
per movement.
43
53) turtle.exitonclick()
-When the game ends, you can exit the game by clicking on the screen.
44
45
PROJECT 3: ALIENS WAR!
1) #ALIENS WAR!
-Always write the title first. ‘#’ symbol is use to comment during our programming.
The computer will not process this line of codes; therefore, it is useful when we want
to write notes or title for the group of codes.
2) import turtle
-As we are using turtle library to draw out our game.
3)#WINDOW SETUP
-Write the title for the next group of codes. Always after importing the necessary
modules then set up the window.
4) wn = turtle.Screen()
-To let the computer knows that we are setting up the window. Take note that for
screen we are using capital “S”.
5) wn.title(‘ALIENS WAR!’)
-The top title at the window.
6) wn.bgcolor(‘black’)
-To change the background colour of the window. Notice the spelling of is ‘color’ and
not ‘colour’.
7) wn.setup(width=700, height=700)
-Set the size of the window.
46
8)#BORDER
-New title.
9) border = turtle.Turtle()
-Setting the name and stating it is an object with capital “Turtle()”. If initially we did
not put “from turtle import Turtle” then it would be “turtle.Turtle()” where lowercase
“turtle” indicates the module name where we are importing from turtle library.
10) border.speed(0)
-Set the turtle to its fastest speed.
11) border.color(‘white’)
-Set the colour of the pen to ‘white’.
12) border.penup()
-Lift the pen up before moving it.
13) border.setposition(-300,-300)
-Set the pen to a new position as previously at centre.
14) border.pendown()
-Set the pen down to prepare to draw.
15) border.pensize(3)
-Set the thickness of the pen.
17) border.hideturtle()
-Hide the pen.
20) player.color(‘blue’)
-Setting the color of the Turtle.
21) player.shape(‘triangle’)
-Setting the shape of the pen to triangle.
47
22) player.penup()
-Lift the pen up before moving it.
23) player.speed(0)
-Set the turtle to its fastest speed.
25) player.setheading(90)
-Change the facing of the turtle to make it face upwards as the Aliens will come from
top.
48
26) playerspeed = 15
-Create a new variable and store the speed of the player.
30) turtle.listen()
-Ask the program to be on alert whether any key is pressed.
49
-if x > 280:
x=280
=To keep the player inside the border.
- player.setx(x)
=Set the x to the new x which is after adding the playerspeed.
36) enemy.color(‘red’)
-Setting the colour of the Turtle.
37) enemy.shape(‘circle’)
-Setting the shape of the pen to circle.
38) enemy.penup()
-Lift the pen up before moving it.
39) enemy.speed(0)
-Set the turtle to its fastest speed.
41) enemyspeed = 3
-Create a new variable and store the speed of the enemy.
50
42) #MAIN GAME LOOP
-New title.
#MOVE ENEMY
x = enemy.xcor()
x += enemyspeed
enemy.setx(x)
-while True:
=To repeat the code forever.
-#MOVE ENEMY
=New title.
-x = enemy.xcor()
=To return the x-coordinates as x-coordinates always change.
- x += enemyspeed
=It will add x by enemyspeed, which is 3, forever.
- enemy.setx(x)
=Set the x to the new x which is after adding the enemyspeed.
if enemy.xcor()< -280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)
51
45) #CREATE THE PLAYER'S BULLET
-Below the #CREATE ENEMY section, add this new section.
47) bullet.color(‘yellow’)
-Setting the colour of the Turtle.
48) bullet.shape(‘triangle’)
-Setting the shape of the pen to triangle.
49) bullet.penup()
-Lift the pen up before moving it.
50) bullet.speed(0)
-Set the turtle to its fastest speed.
51) bullet.setheading(90)
-Change the facing of the turtle to make it face upwards as the Aliens will come from
top.
52) bullet.shapesize(0.5,0.5)
-Set the shape of the object by adjusting the length and width (x, y). The 0.5
indicates half of its original size (20 pixels).
53) bullet.hideturtle()
-Hide the turtle.
54) bulletspeed = 20
-Create a new variable and store the speed of the bullet.
52
=Changing the state of the variable ‘bulletstate’ from local variable to a global
variable so that any changes in the define section is reflected at the ‘bulletstate’
which is under #DEFINE BULLET STATE. Note that the variables created outside a
function is already a global variable itself.
53
62) #CHECK IF THE BULLET GONE TO THE TOP
if bullet.ycor()> 280:
bullet.hideturtle()
bulletstate = ‘ready’
- #CHECK IF THE BULLET GONE TO THE TOP
=Go to the ‘#MAIN GAME LOOP’ and create this new section.
- if bullet.ycor()> 280:
=When the y-coordinates is more than 280 then the below code will run.
- bullet.hideturtle()
=When it is more than 280, then hide the bullet.
- bulletstate = ‘ready’
=Change the state back to ‘ready’ so it can be run by the define function.
54
65) #CHECK FOR COLLISION BETWEEN BULLET AND ENEMY
if isCollision(bullet, enemy):
55
= this will break us out from the ‘while True’ loop under the ‘#MAIN GAME LOOP’
section.
-for i in range(number_of_enemies):
= Create meaning it will repeat 0-4 times as number_ of_enemies = 5
-enemies.append(turtle.Turtle())
= Add the 5 times to the list.
- for enemy in enemies:
= For each enemy created in the list it will have the color, shapes, speed and etc as
stated.
56
72) for enemy in enemies:
enemy.color(‘red’)
enemy.shape(‘circle’)
enemy.penup()
enemy.speed(0)
x = random.randint(-200, 200)
Amend this at
y = random.randint(100, 250)
‘#CREATE ENEMIES’
enemy.setposition( x, y)
-x = random.randint(-200, 200)
=x is randomly chosen between -200 and 200. ‘randint’ choose only integers figure.
-y = random.randint(100, 250)
=y is randomly chosen between 100 and 250. ‘randint’ choose only integers figure.
-enemy.setposition( x, y)
=The position of the enemy will follow the random figure generated by x and y.
if enemy.xcor()< -280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)
57
#Reset the enemy
Amend this so that
x = random.randint(-200, 200)
the enemy when hit
y = random.randint(100, 250) can start back at
enemy.setposition( x, y) random position.
if isCollision(player, enemy):
player.hideturtle()
enemy.hideturtle()
print (‘Game Over’)
break
- for e in enemies:
=The codes is repeated for each enemy.
-enemyspeed *= -1
=Out of the loop as we only need to change the speed once.
#DRAW SCORE
score_pen = turtle.Turtle()
58
score_pen.speed(0)
score_pen.color(‘white’)
score_pen.penup()
score_pen.setposition(-290, 260)
scorestring = ‘Score: %s’%score
score_pen.write(scorestring, False, align=‘left’, font = (‘Arial’,
14, ‘normal’))
score_pen.hideturtle()
- #SET SCORE
=Create new section below ‘#BORDER’.
- score = 0
=Create a variable name score and initial value set to 0.
-scorestring = ‘Score: %s’%score
= Will display ‘Score:’ and the value display will be obtained from the variable ‘score’.
-score_pen.write(scorestring, False, align=‘left’, font = (‘Arial’,
14, ‘normal’))
= The score written will be obtained from ‘scorestring’.
= False (meaning it will not move to the bottom-right corner of the text. Only ‘True’
will. By default, we always use False)
77) wn.bgpic(‘space_invaders_background.gif’)
-Go to ‘#WINDOW SETUP’ for this code. This code is for inserting image into
background.
59
#CREATE ENEMY
enemy.shape(‘invader.gif’)
-Replace the previous shape with the image.
if isCollision(player, enemy):
winsound.PlaySound(‘explosion.wav’, winsound.SND_ASYNC)
-Import sound. Put it under ‘#CHECK FOR COLLISION BETWEEN BULLET AND
ENEMY’.
83) screen.delay(1)
-Approximately the time interval between two consecutive canvas updates. The
longer the delay the slower the animation. Put at the end of the codes.
60
61
62
Make the
code go
over 2 lines
63
64
“Whether you want to uncover the secrets
of the universe, or you just want to pursue a
career in the 21st century, basic computer
programming is an essential skill to learn.”
- Stephen Hawking
Theoretical Physicist, Cosmologist & Author.