0% found this document useful (0 votes)
2 views

Python 2024

This document serves as an introductory guide to Python programming, covering fundamental concepts such as variables, data types, loops, and lists. It includes practical activities and examples to reinforce learning, particularly focusing on the Turtle module for drawing graphics. The content is structured with a table of contents, making it easy to navigate through various programming topics.

Uploaded by

Nurul Afiqah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python 2024

This document serves as an introductory guide to Python programming, covering fundamental concepts such as variables, data types, loops, and lists. It includes practical activities and examples to reinforce learning, particularly focusing on the Turtle module for drawing graphics. The content is structured with a table of contents, making it easy to navigate through various programming topics.

Uploaded by

Nurul Afiqah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

python

NAME :________________________

CLASS :________________________

Content by:

www.aimsity.com Aimsity
TABLE OF CONTENT

No. Descriptions Page


number
1 Introduction 3
2 Flow of a program 3
3 Variables 4-5
4 Data Types 5-12
5 Loops 13-14
6 Lists 15-17
7 Functions 17

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.

Python contains many libraries where pre-programmed code is available making it


easier to write complex programs.

Flow of a program
A program it’s like our human brain where we take in information (input) and process
it into output.

When we see an Our brain processes Output is we know


image. Input is our the image we see. the person is feeling
“eyes” and the Process is the “happy”.
“image” we see. “brain”.

INPUT PROCESS OUTPUT

For computer:- For computer:- For computer:-


● Keyboard ● Variables ● Screen
● Mouse ● Maths ● Graphics
● Loops
● Functions

Activity 1
1)Can you give an example of a situation involving input→process→output?

2)Type the below code what is your output?

3
Notes
● To comment on the use “# or ‘ ”

The program print “Hey


there!” instead of “Hello
World!” as “Hello World!” is
a comment.

● If comment is more than one line “#” 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

1)What is the output of print(Math)?

2)What is the output of print(Math, c)

3)What will happen if we type print(math)?

4)What is the difference between print(Math)and print(‘Math’)?

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)

2)What is the correct way?

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.

Write out your code to solve the below problems.

i)What is the total cookies she has?

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.

>>>Ava_age = input (‘How old is Ava?’)


>>>Aim_age = input (‘How old is Aim?’)

>>>Ava_age = int (Ava_age)


>>>Aim_age = int (Aim_age)

>>>print( Ava_age+Aim_age)
How old is Ava? 2
How old is Aim? 3
5

If we want the answer to appear in another line, we need to add ‘\n’.

>>>Ava_age = input (‘How old is Ava?\n’)


>>>Aim_age = input (‘How old is Aim?\n’)

>>>Ava_age = int (Ava_age)


>>>Aim_age = int (Aim_age)

>>>print( ‘Ava_age+Aim_age = ’ Ava_age+Aim_age)


How old is Ava?
2
How old is Aim?
3
Ava_age+Aim_age = 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’

To extract out a certain charcter


>>> print( a[5])
‘T’
(Note that the position number 5 is called an “index”)

Slicing the string


>>> print(a[2:4])
‘MS’
(Note that the last position number is NOT INCLUDED and the colon defines the
range of the slice)

Extract from start and end


>>> print(a[:3]) Want the first 3
‘AIM’
>>> print(a[3:]) Want after the first 3
‘SITY’

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.

Logical operators can be use to compare variables, number or strings.

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

Check if ‘software_engineers’ is not equal to 4


>>> print(software_engineers != 4)

Or

>>> print(not software_engineers == 4)


True

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

iii) Not attack is equal to ‘Ka Boom’

iv) Is attack equals to ‘Ka boom ’

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,

>>> for i in range (5): Meaning that it will repeat it


>>> print(‘Red is my favourite colour’) for 5 times. This is also
Red is my favourite colour known as a simple loop.
Red is my favourite colour
Red is my favourite colour
Red is my favourite colour
Red is my favourite colour

>>> for i in range (1,5):


>>> print(‘Red is my favourite colour’) The loop will run for 4
times as it excludes the
Red is my favourite colour
last digit. The line ‘Red is
Red is my favourite colour my favourite colour’ that is
Red is my favourite colour repeated is call the loop
Red is my favourite colour body.

>>> for i in range (5): Python always start count


>>> print(i, end= ‘ ’) with ‘0’.
0 1 2 3 4
To make it print at the
>>> for i in range (1, 5): same line.
>>> print(i, end= ‘ ’)
1 2 3 4 To start from 1. Remember
the loop will exclude the
>>> for i in range (3, 16, 3): last number.
>>> print(i, end= ‘ ’)
The third value in the
3 6 9 12 15
range, number 3, will make
the program counts in 3.
>>> for i in range (5, 0, -1): The loop will stop at 15,
>>> print(i, end= ‘ ’) excluding the last number.
5 4 3 2 1
-1 will make the program
counts backwards until it
reaches 1.

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,

>>> party = ‘y’


>>> while party == ‘y’:
>>> print(‘Yay!’)
>>> party = input (‘Are we having a party? (y/n)’)
>>> print(‘ Can we have one, pleaseeeee?’)
Yay!
Are we having a party? (y/n) y
Yay!
If answer is ‘y’ then it
Are we having a party? (y/n) y
will keep looping.
Yay!
Are we having a party? (y/n) y
Yay!
Are we having a party? (y/n) n
Can we have one, pleaseeeee?

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 vs. List

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]

>>> a = 100 >>> ListA[1] = [100]


>>> print (‘a=’, a, ‘b=’, b) >>> print (‘ListA=’, ListA,
a= 100 b= 1 ‘ListB=’, ListB)
ListA= [1, 100, 3] ListB= [1, 100,
3]
(Will not affect the value of ‘b’ as we did not
(Python counts from 0. Where we specify [1], we
redefine the value.)
are telling the program to change the number at
the position 1, which in this case is the number
2]

(For list, if you change a value of one list it will


affect the value of another list as list share the
same link.)

Sorting the list

For example,

#Sort from smallest to largest value


>>> list1 = [3, 2, 6, 12, 711, 333, 555, 32, 77]
>>> list1.sort()
>>> print(list1)
[2, 3, 6, 12, 32, 77, 333, 555, 711]

#Finding the smallest and largest number


>>> list2 = [45, 36, 2, 8, 67, 33, 121, 543, 98]
>>> a = min(list2)
>>> b = max(list2)

>>> print(list2)
>>> print(‘Smallest value =’, a)
>>> print(‘Largest value =’, b)

15
Smallest value = 2
Largest value = 543

#Arrange the list in alphabetical order


>>> list3 = [‘b’, ‘f’, ‘h’, ‘e’, ‘m’, ‘j’]
>>> list3.sort()
>>> print(list3)
['b', 'e', 'f', 'h', 'j', 'm']

#Adding an item to the end of a list


>>> list4=[]
>>> list5=[]
>>> list6=[]

>>> for i in range (10):


>>> list4.append(i)
>>> list5.append(i*i)
>>> list6.append(i**3)

>>> print(‘list4 =’, list4)


>>> print(‘list5 =’, list5)
>>> print(‘list6 =’, list6)

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]

#From string to list


>>> string = ‘I am happy’
>>> print(string.split(‘ ’))
[‘I', ‘am', ‘happy']

#From list to string


>>> list1 = [‘I’, ‘am’, ‘happy’]
>>> print( ‘ ’.join(list1))
I am happy

#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,

>>> def name():


>>> print(‘My name is Sarah.’)
>>> name()
My name is Sarah.

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.

2)Straight line with heading

90◦

We can use headings


180◦ 0◦ to set the orientation
of the turtle.

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

Colour them up!


In previous lessons, we had learnt to draw using Python turtle now it’s time to fill
them up.

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.

10)#MAIN GAME LOOP


i=-1
while True:
i=i+1
pen.goto(-400+5*i,0)
pen1.goto(-460+5*i,-60)
pen2.goto(-340+5*i,-60)
time.sleep(0.02)
if pen.xcor()>350:
i=-1

-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.

4) from turtle import Turtle


-Importing every member from the namespace(Turtle).

5) from random import randint


-Importing the random function so whenever we start the game the program will
randomly choose the speed of the turtle contestant.

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”.

8) wn.title(‘LET THEM RACE!’)


-The top title at the window.

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.

13) turtle.setpos(-170, 200)


-Move the turtle to upper left where x=-170 and y=200.

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.

17) turtle.setpos(-400, -180)


-Position the pen at the bottom left.

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.

32) finish_line = 200


-Create a variable name ‘finish_line’ to store the length of the line.

33) finish_line = 200


-Create a variable name ‘finish_line’ to store the length of the line.

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.

42) turtle1 = 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.

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.

47) turtle1.goto(-250, 100)


-Go to a new position x=-250, y=100.

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.

TURTLE COLOUR POSITION


2 Cyan (-250, 50)
3 Magenta (-250, 0)
4 Yellow (-250, -50)

42
50) time.sleep(1)
-Pause the game for 1 second before starting the race.

51) #MOVE THE TURTLES


-New title.

52) for i in range(145):


turtle1.forward(randint(1,5))
turtle2.forward(randint(1,5))
turtle3.forward(randint(1,5))
turtle4.forward(randint(1,5))

-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.

16) for side in range(4):


border.forward(600)
border.left(90)
-It will repeat for 4 times. Each time it will draw a line with 600 pixels in length and
turn 90◦.

17) border.hideturtle()
-Hide the pen.

18) #CREATE THE PLAYER


-New title.

19) player = turtle.Turtle()


-Setting the name and stating it is an object

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.

24) player.setposition(0, -250)


-Set the turtle position to the bottom of the screen.

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.

27) #MOVE THE PLAYER


-New title.

28) def move_left():


x = player.xcor()
x -= playerspeed
if x < -280:
x=-280
player.setx(x)
- def move_left():
=Create a new function ‘move_left’
-x = player.xcor()
=To return the x-coodinates as x-coordinates always change.
-x -= playerspeed
=Each time when left key is press it will substract x by playerspeed which is 15.
-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 subtracting playerspeed.

29) #KEYBOARD BINDINGS


-New title.

30) turtle.listen()
-Ask the program to be on alert whether any key is pressed.

31) turtle.onkeypress (move_left, ‘Left’)


-When left arrow is pressed it will do whatever that is defined in ‘move_left’.

32) def move_right():


x = player.xcor()
x += playerspeed
if x > 280:
x=280
player.setx(x)
- def move_right():
=Create a new function ‘move_right’
-x = player.xcor()
=To return the x-coordinates as x-coordinates always change.
-x += playerspeed
=Each time when left key is press it will add x by playerspeed which is 15.

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.

33) turtle.onkeypress (move_right, ‘Right’)


-When right arrow is pressed it will do whatever that is defined in ‘move_right’.

34) #CREATE ENEMY


-Above the title ‘MOVE PLAYER’, create this new title. Now we will create our
enemy.

35) enemy = turtle.Turtle()


-Setting the name and stating it is an object.

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.

40) enemy.setposition(-200, 250)


-Set the turtle position to the top of the screen.

41) enemyspeed = 3
-Create a new variable and store the speed of the enemy.

50
42) #MAIN GAME LOOP
-New title.

43) while True:

#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.

44) #MOVE ENEMY BACK AND DOWN


if enemy.xcor()> 280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)

if enemy.xcor()< -280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)

-if enemy.xcor()> 280:


=Set the x of enemy is more than 280 then the below code will run.
- y = enemy.ycor()
=To return the y-coordinates as y-coordinates always change.
- y -= 40
=With each loop it will subtract 40 from the previous number. This will move the
enemy down when it reach the border.
- enemyspeed *= -1
=When the enemy reach the border, we will multiply the its current x value by -1 in
order to move it backwards.
- enemy.sety(y)
=Set the y to the new y which is after subtracting the 40.

51
45) #CREATE THE PLAYER'S BULLET
-Below the #CREATE ENEMY section, add this new section.

46) bullet = turtle.Turtle()


-Setting the name and stating it is an object.

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.

55) #DEFINE BULLET STATE


#READY- READY TO FIRE
#FIRE- BULLET IS FIRING
-New title. Under #DEFINE BULLET STATE has 2 sections-# READY- READY TO
FIRE and #FIRE- BULLET IS FIRING.

56) bulletstate = ‘ready’


-Create a variable name ‘bulletstate’ and store the string ‘ready’.

57) def fire_bullet():


#Declare bulletstate as a global variable
global bulletstate
- def fire_bullet():
=Under the #MOVE THE PLAYER, make a new function ‘fire_bullet’
- global bulletstate

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.

58) #Move the bullet to just above the player


x = player.xcor()
y = player.ycor()+10
bullet.setposition(x, y)
bullet.showturtle()

- #Move the bullet to just above the player


=Under ‘#Declare bulletstate as a global variable’, create a new title.
- x = player.xcor()
= x is the player’s current x-position.
- y = player.ycor()+10
= y is the player’s current y-position add 10 as we want the position of the bullet to
be slightly above the current position of the player.
- bullet.setposition(x, y)
=Set the bullet position to the above define (x, y) position.
- bullet.showturtle()
=Show the bullet.

59) turtle.onkeypress (fire_bullet, ‘space’)


-Go to ‘#KEYBOARD BINDINGS’, to bind the above function. Notice ‘s’ is in a
lowercase.

60) #MOVE THE BULLET


y = bullet.ycor()
y += bulletspeed
bullet.sety(y)
- #MOVE THE BULLET
=Under the # MAIN GAME LOOP, create this new section.
- y = bullet.ycor()
=y is the current y-coordinates of the bullet.
- y += bulletspeed
=Then at the ‘bulletspeed’ which we previously set as 20.
- bullet.sety(y)
=Set the y to the current new value which is after adding 20.

61) if bulletstate == ‘ready’:


bulletstate = ‘fire’
-Go to ‘#Declare bulletstate as a global variable’ and under ‘global bulletstate’ key in
this. If the bulletstate is ‘ready’ then it will change the bulletstate to ‘fire’.

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.

63) import math


-Import math module to use it to calculate distance between the enemy and player.

64) def isCollision (t1, t2):


distance = math.sqrt(math.pow(t1.xcor()-
t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 15:
return True
else:
return False
-def isCollision (t1, t2):
=t1 will be bullet, t2 will be enemy
- distance = math.sqrt(math.pow(t1.xcor()-
t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))

=math.sqrt (we are using the squareroot function)


=math.pow(function returns the value of x to the power of y (x^y))
= t1.xcor()-t2.xcor() (difference between the value)
=, 2(square- meaning to the power of 2)
- if distance < 15:
=if the distance outcome is less than 15, then the below code will run.
- return True
=means there is a collision.
- return False
=means no collision.

54
65) #CHECK FOR COLLISION BETWEEN BULLET AND ENEMY
if isCollision(bullet, enemy):

#Reset the bullet


bullet.hideturtle()
bulletstate = ‘ready’
bullet.setposition(0, -400)

-#CHECK FOR COLLISION BETWEEN BULLET AND ENEMY


=Go to ‘#MAIN GAME LOOP’, under ‘#MOVE ENEMY BACK AND DOWN’, create
this new section.
-if isCollision(bullet, enemy):
=when isCollision is True, the below codes will run.
-#Reset the bullet
=New title.
-bullet.hideturtle()
=If collide, then hide the bullet.
- bulletstate = ‘ready’
=Re-state the status back to ‘ready’.
- bullet.setposition(0, -400)
=Move the bullet to (0,-400) -out of the border so that it will not collides with other
enemies.

66) #Reset the enemy


enemy.setposition(-200, 250)

-#Reset the enemy


= under ‘#CHECK FOR COLLISION BETWEEN BULLET AND ENEMY, create this
new section.
- enemy.setposition(-200, 250)
= Re-set it to (-200,250).

67) if isCollision(player, enemy):


player.hideturtle()
enemy.hideturtle()
print (‘Game Over’)
break
-if isCollision(player, enemy):
= If player collides with enemy, the below codes will run.
-player.hideturtle()
= hide player
-enemy.hideturtle()
= hide enemy
-print (‘Game Over’)
= show string ‘Game Over’.
-break

55
= this will break us out from the ‘while True’ loop under the ‘#MAIN GAME LOOP’
section.

68) #CHOOSE A NUMBER OF ENEMIES


number_of_enemies = 5
-#CHOOSE A NUMBER OF ENEMIES
= Create a new section above ‘#CREATE ENEMY’.
-number_of_enemies = 5
= Number of enemies to be created = 5

69) #CREATE AN EMPTY LIST OF ENEMIES


enemies = []
-# CREATE AN EMPTY LIST OF ENEMIES
= Create an empty list

70) #ADD ENEMIES TO LIST


for i in range(number_of_enemies):
#CREATE ENEMY
enemies.append(turtle.Turtle())
for enemy in enemies:
enemy.color(‘red’)
enemy.shape(‘circle’)
enemy.penup()
enemy.speed(0)
enemy.setposition( -200, 250)

(Amend the ‘#CREATE ENEMY’ section as above)

-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.

71) import random


-Import random module

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.

73) while True:


for enemy in enemies: Add this at main
#MOVE ENEMY loop
x = enemy.xcor()
x += enemyspeed
enemy.setx(x) Remember to
indent the rest of
#MOVE ENEMY BACK AND DOWN the enemy
if enemy.xcor()> 280: codes.
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)

if enemy.xcor()< -280:
y = enemy.ycor()
y -= 40
enemyspeed *= -1
enemy.sety(y)

#CHECK FOR COLLISION BETWEEN BULLET AND ENEMY


if isCollision(bullet, enemy):

#Reset the bullet


bullet.hideturtle()
bulletstate = ‘ready’
bullet.setposition(0, -400)

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 enemy in enemies:


=It will repeat the codes for each enemy created.

74) #MOVE ENEMY BACK AND DOWN


if enemy.xcor()> 280:
#Move all the enemies down
for e in enemies:
y = e.ycor()
y -= 40
e.sety(y)
#Change enemies direction Make these
enemyspeed *= -1 changes in ‘#MOVE
ENEMY BACK AND
DOWN’
if enemy.xcor()< -280:
for e in enemies:
#Move all the enemies down
y = e.ycor()
y -= 40
e.sety(y)
#Change enemies direction
enemyspeed *= -1

- 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.

75) #SET SCORE


score = 0

#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)

76) #Update score


score += 10
scorestring = ‘Score: %s’%score
score_pen.clear()
score_pen.write(scorestring, False, align=‘left’, font =
(‘Arial’, 14, ‘normal’))
- #Update score
=Create new section below at ‘#MAIN GAME LOOP’ and below ‘#Reset enemy’.
- score += 10
=Each time a bullet hit the enemy, 10 points will be awarded.
- score_pen.clear()
=Clear previous number on screen before displaying new score to avoid overlap.

77) wn.bgpic(‘space_invaders_background.gif’)
-Go to ‘#WINDOW SETUP’ for this code. This code is for inserting image into
background.

78) #REGISTER SHAPES


turtle.register_shape(‘invader.gif’)
turtle.register_shape(‘player.gif’)
-To register the image before use.

79) #CREATE THE PLAYER


player.shape(‘player.gif’)

59
#CREATE ENEMY
enemy.shape(‘invader.gif’)
-Replace the previous shape with the image.

80) import winsound


-Import sound module.

81) if bulletstate == ‘ready’:


winsound.PlaySound(‘laser.wav’, winsound.SND_ASYNC)
-Import sound. Put it under ‘def fire_bullet():→if bulletstate == 'ready' :’

82) if isCollision(bullet, enemy):


winsound.PlaySound(‘explosion.wav’, winsound.SND_ASYNC)

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.

You might also like