WDWD 1 W 11111111 Aa 1111111 Wwa

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Lesson # 2

Creating the Game


“Bomb”

CONTENTS
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Scope in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Local Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Global Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Nonlocal Scope. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Creating the Game “Bomb” . . . . . . . . . . . . . . . . . . . . . . . . 14

Lesson materials are attached to this PDF file.


In order to get access to the materials, open the lesson in
Adobe Acrobat Reader.
Creating the Game “Bomb”

Introduction
Clicker games stand out among the variety of
video game genres.
The objective of such a game is to click as fast as you
can on a certain object. At that, the faster the player
clicks, the more points he gets.
The mobile game CivCrafter is among popular clicker
games. Here the player mines resources and hires workers
(Figure 1).

Figure 1

3
Lesson # 2

In addition, an exciting postapocalyptic clicker game


Doomsday Clicker was developed for smartphones. Here
the player creates people and turns them into mutants
(Figure 2).

Figure 2

Before you begin to develop your clicker game, you


should learn about global and local variables in Python
because this is what we are going to work with!

4
Creating the Game “Bomb”

Scope in Python
To begin with, let's learn the concept of scope often used
in programming.
This topic is very important because if you do not
know this, your code will be full of errors (Figure 3)!

Figure 3

Scope in programming defines when and where we


can use variables or functions. For an interpreter—software
that analyzes code line-by-line—the scope specifies when
the value is visible.
In Python, the scope can be local, global, or nonlocal.
The concept of a nonlocal variable was introduced in the
third version of Python, which we use in our projects (Figure
4).

5
Lesson # 2

Figure 4

Before we move on to the new topic, let's remember some


important concepts encountered in almost any program:
variables and functions.
Variables in a programming language are a named mem-
ory location that stores a value and its changes as the pro-
gram runs. In Python, you do not have to specify a variable's
data type to create it. All you should do is set its name and
assign a value to the variable (Figure 5):
bool_var = True

6
Creating the Game “Bomb”

Figure 5

A function in programming is a block of code used


multiple times that performs certain actions. The function is
declared after the def  keyword:
def func():
pass

As we already know, we should assign a value to a variable


to create it. Notice that the place of declaration influences the
scope that the variable belongs to.

7
Lesson # 2

Local Scope
The local scope is defined inside the function.
Let's create a function that will output names of space
shuttles. Set its name space_shuttle() and declare two
variables inside it. When the first function is called, these
names must be output to the console:
def space_shuttle():
# local
name1, name2, name3 = 'Atlantis',
' Challenger', 'Columbia'
print(name1, name2, name3)

space_shuttle()

Because the variables were created inside the function,


they exist only in it, and you cannot access them in the
program. Moreover, when the function is executed, these
variables will be deleted from the memory.

8
Creating the Game “Bomb”

Global Scope
Variables created outside a function are global. More-
over, they can be accessed even inside a function.
Let's create variables in which aircraft numbers will be
stored and call such a variable inside the function space_
shuttle():
def space_shuttle():
# local
name1, name2, name3 = 'Atlantis',
'Challenger', 'Columbia'
print('Name: ', name1, name2, name3,
'\nOrbiter Vehicle: ', ov1, ov2, ov3)

# global
ov1, ov2, ov3 = 'OV-104', 'OV-099', 'OV-102'

space_shuttle()

The result will be output to the console:


Name: Atlantis Challenger Columbia
Orbiter Vehicle: OV-104 OV-099 OV-102
This code results in space shuttle names and aircraft
numbers output to the console (Figure 6). Note the global
variables ov1, ov2, ov3 created before the function calls. If
we did this vice versa, an error would be thrown.

9
Lesson # 2

Figure 6

Let's consider the case when we want to change the


value of a global variable inside a function. The global
instruction followed by a variable name should be used for
this.
Set the space mission name and try to change it inside
the function:
def space_mission():
global mission
mission = 'Galileo'
print('Mission: ', mission,
'\nID: ', id(mission))

10
Creating the Game “Bomb”

# global
mission = 'Humans in Space'

space_mission()
print('\nMission: ', mission,
'\nID: ', id(mission))

The result is as follows:


Mission: Galileo
ID: 1873479449264
Mission: Galileo
ID: 1873479449264
In the given code, we accessed the global mission,
variable, and after this it was overridden. Look at the unique
identifier of the variable id(mission) to make sure that
everything is done correctly.
Try to comment the line # global mission and run
your code. You get a completely different result:
Mission: Galileo
ID: 1254851787440
Mission: Humans in Space
ID: 1254851818672
In this case, a local variable with the same name will be
created if you try to override the global mission variable
inside the function.

11
Lesson # 2

As you can see, the identifiers of global and local vari-


ables are different. The reason is that the mission  variable
became local as soon as it was assigned a new value inside
the function ('Humans in Space'). This is why you
should be careful when accessing variables.

12
Creating the Game “Bomb”

Nonlocal Scope
Sometimes, you should create one more function
inside another function and override a variable inside
the former. The nonlocal keyword was added for cases
exactly like this.
Let's create a function and a variable with the comet
name in it. Create one more function inside it and override
this name.
def comet_name1():
name = "Halley's Comet"

def comet_name2():
nonlocal name
name = '81P/Wild'
comet_name2()
return name

print('Name: ', comet_name1())

After you run the code, the following is displayed in the


console:
Name: 81P/Wild
If you comment the line # nonlocal name and run
the code, the interpreter will not see our variable or be able to
override it. The alert Shadows name 'name' from outer
scope will appear instead.

13
Lesson # 2

Creating the Game “Bomb”


Let's start developing your own clicker game.
In our game, a bomb fuse will lit, and the countdown
will begin. As soon as the time runs out, the bomb explodes.
The player must hold out as long as possible, which
means that she must click pretty quickly (Figures 7 and 8).

Figure 7

14
Creating the Game “Bomb”

Figure 8

We will begin to work on our projects with adding more


modules. The game needs a window, so import the tkinter
library:
from tkinter import *

Declare variables at the beginning of the game. The start-


ing point for the countdown is 100 and for the player 0:
bomb = 100
score = 0

15
Lesson # 2

The game begins after the Enter key is pressed. Add a


boolean variable to store True or False in it and manage the
game process:
press_return = True

Then create several functions.


First, declare them in the program and, after we create
the main window in tkinter, go back to them and fill them
out:
def start(event):

def update_display():

def update_bomb():

def update_point():

def click():

def is_alive():

16
Creating the Game “Bomb”

Create the main window of the game. Set its name and
size:
root = Tk()
root.title('Bang Bang')
root.geometry('500x550')

Create a label in the upper part of the window and offer


the user to press Enter to start the game (Figure 9):
label = Label(root, text='Press [enter] to
start the game', font=('Comic Sans MS', 12))
label.pack()

Figure 9

Now display two more Label widgets. The first of them


will display the time left before the explosion, that is 100. The
second Label widget will display the player's speed (Figure
10):
fuse_label = Label(root, text='Fuse: ' +
str(bomb), font=('Comic Sans MS', 14))
fuse_label.pack()

score_label = Label(root, text='Score: ' +


str(score), font=('Comic Sans MS', 14))
score_label.pack()

17
Lesson # 2

Figure 10

Great!
To design the game, we need an image of a bomb. There is
a PhotoImage()  class in the tkinter module, and it displays
images. This class can read only .gif, .pgm, or .ppm image
formats.
Create an img folder in the project folder and add three
images in it (Figure 11):

Figure 11

Add code that will access these images:


no_photo = PhotoImage(file='img/bomb_no.gif')
normal_photo = PhotoImage(file='img/bomb_normal.gif')
bang_photo = PhotoImage(file='img/pow.gif')

18
Creating the Game “Bomb”

When the game begins, the player sees an image of the


bomb and a fuse. Display this image in the window (Figure
12):
bomb_label = Label(root, image=normal_photo)
bomb_label.pack()

Figure 12

A button will be below the image. When the player clicks


on it, he adds values to the bomb variable thus preventing
the bomb from explosion.

19
Lesson # 2

The click() function must be called when the button


is clicked (Figure 13):
click_button = Button(root, text='Click me',
bg='#000000', fg='#ffffff', width=15,
font=('Comic Sans MS', 14),command=click)

click_button.pack()

Figure 13

You can bind the widget and a certain event using the
bind() method. The event in our game is pressing the Enter
key because the game begins after it is pressed.

20
Creating the Game “Bomb”

And call the start() function at the beginning of the


game:
root.bind('<Return>', start)

root.mainloop()

Excellent! All elements are added to the window. We


have designed the game and placed all the required ele-
ments.

It is time to program the game.


Let's go back to the functions created earlier. Find out
the result of the boolean variable press_return at the
beginning of the game, and if it is True, do not hesitate to
start the game! Clear the label text and call a number of
functions:
def start(event):
global press_return
global bomb
global score
if not press_return:
pass
else:
bomb = 100
score = 0
label.config(text='')
update_bomb()

21
Lesson # 2

update_score()
update_display()
press_return = False

Refresh the window content. Call the global variables


bomb  and score and refresh the window content every 100
milliseconds, that is change the values next to Fuse and
Score.
The countdown begins with 100. While this number is
greater than 50, the window displays the image of the bomb
with the full fuse. When the value of the bomb variable is less
than or equal to 50 and greater than 0, the player sees the
image of the bomb with the burnt out fuse. If the fuse value
is less than 0, the bomb explodes:
def update_display():
global bomb
global score
if bomb > 50:
bomb_label.config(image=normal_photo)
elif 0 < bomb <= 50:
bomb_label.config(image=no_photo)
else:
bomb_label.config(image=bang_photo)
fuse_label.config(text='Fuse: ' + str(bomb))
score_label.config(text='Score: ' +
str(score))
fuse_label.after(100, update_display)

22
Creating the Game “Bomb”

Every 400 milliseconds, 5 points are deducted from the


bomb variable. We picked 5 just to make the game more
fun and the victory not so easy. If you deduct 1 every 1000
milliseconds, the loss probability will be too small which
takes away half the excitement:
def update_bomb():
global bomb
bomb -= 5
if is_alive():
fuse_label.after(400, update_bomb)

The player will get 1 point every 3000 milliseconds (3


seconds). The later the bomb explodes, the more points the
player can score:
def update_score():
global score
score += 1
if is_alive():
score_label.after(3000, update_score)

As you remember, after the Click  me button is pressed,


the command=click executes, where click is a function.
Every button click must increase the value of the bomb
variable by a certain value (Figure 14).

23
Lesson # 2

We get to decide on this value, let it be 1:


def click():
global bomb
if is_alive():
bomb += 1

Figure 14

Let's write the last function.


Here we ask whether the bomb exploded. It explodes if
the bomb variable is less than or equal to 0. If the answer is
yes, the image of an exploded bomb is displayed. And the
press_return variable becomes True in this case. As
you remember, if press_return = True, the player can
restart the game.
def is_alive():
global bomb
global press_return
if bomb <= 0:
label.config(text='Bang! Bang! Bang!')
press_return = True
return False
else:
return True

24
Creating the Game “Bomb”

After the time is up, you can press Enter again and replay
the game.

Based on our game, you can develop a completely


different clicker game by expanding its functionality.
You can be guided by the mobile game Juggernaut
Champions. This game is extremely easy to manage and has
engaging gameplay and impressive graphics (Figure 15).

Figure 15

Or you can take example by one of the popular clicker


games on Steam, Clicker Heroes (Figure 16).
The objective of the game is to destroy giant bosses using
various skills. The player can collect coins from defeated
enemies to level up characters.

25
Lesson # 2

Figure 16

26
Lesson # 2
Creating the Game “Bomb”

© STEP IT Academy
www.itstep.org

All rights to protected pictures, audio, and video belong to their authors or legal owners.
Fragments of works are used exclusively in illustration purposes to the extent justified by
the purpose as part of an educational process and for educational purposes in accordance
with Article 1273 Sec. 4 of the Civil Code of the Russian Federation and Articles 21 and 23
of the Law of Ukraine “On Copyright and Related Rights”. The extent and method of cited
works are in conformity with the standards, do not conflict with a normal exploitation of
the work, and do not prejudice the legitimate interests of the authors and rightholders.
Cited fragments of works can be replaced with alternative, non-protected analogs, and
as such correspond the criteria of fair use.
All rights reserved. Any reproduction, in whole or in part, is prohibited. Agreement of the
use of works and their fragments is carried out with the authors and other right owners.
Materials from this document can be used only with resource link.
Liability for unauthorized copying and commercial use of materials is defined according
to the current legislation of Ukraine.

You might also like