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

Python-2 - Unit-6,7,8 - Game Development

The document discusses event driven programming and some key concepts: 1) Events like button clicks, key presses, mouse movements are handled by event handlers which are inserted into an event queue. Only one event handler can execute at a time from this queue. 2) Timers can be created and controlled to call timer handler functions at regular intervals. 3) Frames provide a canvas to draw on and methods to control aspects like background color. Buttons, labels, inputs can be added to frames. 4) Common drawing functions allow drawing text, circles, handling mouse/keyboard events on the canvas. Examples demonstrate changing colors, sizes via buttons. So in summary, the document covers the basic building

Uploaded by

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

Python-2 - Unit-6,7,8 - Game Development

The document discusses event driven programming and some key concepts: 1) Events like button clicks, key presses, mouse movements are handled by event handlers which are inserted into an event queue. Only one event handler can execute at a time from this queue. 2) Timers can be created and controlled to call timer handler functions at regular intervals. 3) Frames provide a canvas to draw on and methods to control aspects like background color. Buttons, labels, inputs can be added to frames. 4) Common drawing functions allow drawing text, circles, handling mouse/keyboard events on the canvas. Examples demonstrate changing colors, sizes via buttons. So in summary, the document covers the basic building

Uploaded by

Palak Rathore
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Event Driven Programming

Input

Button
Text Box

Keyboard

key down
key up

Mouse

Click
Drag

Timer

The Event Queue


What happens if you press a key and click the mouse at exactly the same time?

One of the event handlers executes and the other waits in the event queue until the first handler finishes.

You can’t control the order that the system inserts events into the event queue and only one event handler
executes at a time.
In [ ]:

1 !pip install SimpleGUICS2Pygame

In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame

Timers

Create Timer -> simplegui.create_timer()


Start Timer -> timer.start()
Stop Timer -> timer.stop()
Check if Timer is running -> timer.is_running()
In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def timer_handler():
3 print('Tick')
4
5 timer=simplegui.create_timer(1000,timer_handler)
6 timer.start()

Tick
Tick
Tick
Tick
Tick
In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 t=0
3 def timer_handler():
4 global t
5 while t<5:
6 print('Tick')
7 t+=1
8 timer.stop()
9
10 timer=simplegui.create_timer(500,timer_handler)
11 timer.start()

Tick
Tick
Tick
Tick
Tick

In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 t=0
3 def timer_handler():
4 global t
5 t+=1
6 if t==5:
7 timer.stop()
8 print('tick')
9
10 timer=simplegui.create_timer(500,timer_handler)
11 timer.start()

tick
tick
tick
tick
tick
In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 t=0
3 def timer_handler():
4 pass
5
6 timer=simplegui.create_timer(100,timer_handler)
7 print(timer.is_running())
8 timer.start()
9 print(timer.is_running())
10 timer.stop()
11 print(timer.is_running())

False
True
False

Frames
Create Frame-> simplegui.create_frame()
BG Color -> frame.set_canvas_background()
Frame Start -> frame.start()
Frame Text Width -> frame.get_canvas_textwidth()
In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 frame=simplegui.create_frame('Testing',400,400) #simplegui.create_frame(title,canv
3 frame.set_canvas_background('Red')
4 frame.start()

Draw Text on Canvas


1 canvas.draw_text(text,point,font_size,font_color,*font_face)

Given a text string, a font size, and a font face, this returns the width of the text in pixels. It does not draw
the text. This is useful in computing the position to draw text when you want it centered or right justified in
some region.

The supported font faces are the default "serif", "sans-serif", and "monospace".

In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 def draw_handler(canvas):
4 canvas.draw_text('A',(20,20),12,'Red')
5 canvas.draw_text('B',[30,50],20,'Blue')
6 canvas.draw_text('C',(80,50),20,'Gray','sans-serif')
7 frame.set_canvas_background('Cyan')
8
9 frame=simplegui.create_frame('Testing',400,400)
10 frame.set_draw_handler(draw_handler)
11 frame.start()
Change in background
In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 t=0
3 color=['violet','indigo','Blue','green','yellow','orange','red']
4 def timer_handler():
5 global t
6 t+=1
7 if t==7:
8 timer.stop()
9
10 def draw_handler(canvas):
11 global color
12 if t<7:
13 frame.set_canvas_background(color[t])
14
15 frame=simplegui.create_frame('Testing',400,400)
16 timer=simplegui.create_timer(1000,timer_handler)
17 frame.set_draw_handler(draw_handler)
18 timer.start()
19 frame.start()
20

Adding Button

In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def button_handler():
3 pass
4 frame=simplegui.create_frame('Testing',400,400)
5 button1=frame.add_button('Label 1',button_handler)
6 button2=frame.add_button('Label 2',button_handler,100)
7 frame.start()
In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def button_handler1():
3 timer.start()
4 def button_handler2():
5 timer.stop()
6 frame=simplegui.create_frame('Testing',400,400)
7 timer=simplegui.create_timer(1000,timer_handler)
8 button1=frame.add_button('Label 1',button_handler1)
9 button2=frame.add_button('Label 2',button_handler2,100)
10 frame.start()

Background Color change with buttons


In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 t=0
3 color=['DeepPink','Red','DarkOrange','Yellow','Lime','Aqua','Magenta']
4 def timer_handler():
5 global t
6 t+=1
7 if t==7:
8 t=0
9
10 def draw_handler(canvas):
11 global color
12 frame.set_canvas_background(color[t])
13 def button_handler1():
14 timer.start()
15 def button_handler2():
16 timer.stop()
17
18 frame=simplegui.create_frame('Testing',400,400)
19 timer=simplegui.create_timer(1000,timer_handler)
20 frame.set_draw_handler(draw_handler)
21 button1=frame.add_button('Start',button_handler1,100)
22 button2=frame.add_button('Stop',button_handler2,100)
23 frame.start()
24
Change in text and background via button
In [ ]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 def draw_handler1(canvas):
4 frame.set_canvas_background('white')
5 canvas.draw_text('Welcome',(40,40),20,'Red')
6
7 def draw_handler2(canvas):
8 frame.set_canvas_background('Black')
9 canvas.draw_text('Good Job',(40,40),20,'Red')
10
11 def button_handler1():
12 frame.set_draw_handler(draw_handler2)
13
14
15 frame=simplegui.create_frame('Testing',400,400)
16 frame.set_draw_handler(draw_handler1)
17 button1=frame.add_button('Start',button_handler1,100)
18 frame.start()
19
Add label

In [3]:

1 from SimpleGUICS2Pygame import simpleguics2pygame as simplegui


2 frame=simplegui.create_frame('Testing',400,400)
3 label1=frame.add_label('My First Label')
4 label2=frame.add_label('My Second Label', 200)
5 label3=frame.add_label('My Third Label', 100)
6 frame.start()

Add Input ¶

In [4]:

1 from SimpleGUICS2Pygame import simpleguics2pygame as simplegui


2 def input_handler(text_input):
3 pass
4 frame=simplegui.create_frame('Testing',400,400)
5 inp=frame.add_input('My label',input_handler, 150)
6 frame.start()
Background Change via Input

In [4]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 color='Pink'
3
4 def input_handler(text_input):
5 global color
6 color=text_input
7 def draw_handler(canvas):
8 frame.set_canvas_background(color)
9
10
11 frame=simplegui.create_frame('Testing',400,400)
12 frame.set_draw_handler(draw_handler)
13 text_input=frame.add_input('Enter your color',input_handler, 50)
14 frame.start()
15

In [5]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_text('X',(0,30),48,'Red')
4 frame.set_canvas_background('Cyan')
5
6 frame=simplegui.create_frame('Event Driven',96,96)
7 frame.set_draw_handler(draw_handler)
8 frame.start()
Calculator
In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 #globals
4 n1 = 0
5 n2 = 0
6 ans = 0
7
8 #event handlers
9 def input_handler1(num):
10 global n1
11 n1 = int(num)
12
13 def input_handler2(num):
14 global n2
15 n2 = int(num)
16
17 def draw(canvas):
18 canvas.draw_text(str(ans), [150,150], 50, 'white')
19
20 def add1():
21 global ans
22 ans = int(n1) + int(n2)
23
24 def subtract():
25 global ans
26 ans = n1 - n2
27
28 def multiply():
29 global ans
30 ans = n1 * n2
31
32 def divide():
33 global ans
34 ans = n1 / n2
35
36 def clear():
37 global ans
38 ans=''
39
40 #create frame
41 frame = simplegui.create_frame('Calculator', 300, 300)
42
43 #register handlers
44 frame.set_draw_handler(draw)
45 frame.add_input('Number 1: ', input_handler1, 100)
46 frame.add_input('Number 2: ', input_handler2, 100)
47 frame.add_button('Add', add1)
48 frame.add_button('Subtract', subtract)
49 frame.add_button('Multiply', multiply)
50 frame.add_button('Divide', divide)
51 frame.add_button('Clear', clear)
52
53 frame.set_draw_handler(draw)
54 #start
55 frame.start()
CIRCLE

In [8]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_circle((30,30),20,12,'Green')
4 # draw_circle(center_point,radius,linewidth,linecolor,fillcolor)
5 canvas.draw_circle([50,30],30,12,'Red')
6 canvas.draw_circle((150,50),20,5,'Blue','White')
7 canvas.draw_circle((200,200),30,10,'Yellow','Orange')
8
9 frame=simplegui.create_frame('CANVAS',400,400)
10 frame.set_draw_handler(draw_handler)
11 frame.start()

In [6]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 radius=60
3 def draw_handler(canvas):
4 global radius
5 canvas.draw_circle((200,200),radius,12,'Green','Blue')
6 def button_handler1():
7 global radius
8 if radius>0:
9 radius+=3
10 def button_handler2():
11 global radius
12 if radius>10:
13 radius-=3
14 else:
15 radius=10
16
17 frame=simplegui.create_frame('CANVAS',400,400)
18 button1=frame.add_button('Increase Radius',button_handler1)
19 button2=frame.add_button('Decrease Radius',button_handler2)
20 frame.set_draw_handler(draw_handler)
21 frame.start()
Number Guessing

In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import random
3 no=random.randint(1,100)
4 n=0
5 chances=7
6 result=''
7 def draw_handler(canvas):
8 global chances
9 canvas.draw_text(('Chances left: '),(30,30),48,'Red')
10 canvas.draw_text((str(chances)),(290,30),48,'Red')
11 canvas.draw_text((result),(30,100),48,'Red')
12 def input_handler(text_input):
13 global n
14 global result
15 global chances
16 n=text_input
17 if chances>0:
18 if int(n)==no:
19 result="Perfect Guess"
20 elif int(n)<no:
21 result="Lower"
22 elif int(n)>no:
23 result="Higher"
24 chances-=1
25 if chances==0:
26 result='You Lose, number was:' + str(no)
27
28 frame=simplegui.create_frame('GAME',1000,400)
29 text_input=frame.add_input('Enter the Number',input_handler, 200)
30 frame.set_draw_handler(draw_handler)
31 frame.start()
Number Guessing 1-100 and 1-1000
In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import random
3 num_range=100
4 no=0
5 n=0
6 chances=7
7 result=''
8 def new_game():
9 global num_range, chances, no, result
10 no=random.randint(1,num_range)
11 result=""
12 def draw_handler(canvas):
13 global chances
14 canvas.draw_text(('Chances left: '),(30,30),48,'Red')
15 canvas.draw_text((str(chances)),(290,30),48,'Red')
16 canvas.draw_text((result),(30,100),48,'Red')
17 def input_handler(text_input):
18 global n
19 global result
20 global chances
21 n=text_input
22 if chances>0:
23 if int(n)==no:
24 result="Perfect Guess"
25 elif int(n)<no:
26 result="Lower"
27 elif int(n)>no:
28 result="Higher"
29 chances-=1
30 if chances==0:
31 result='You Lose, number was:' + str(no)
32 def button_handler1():
33 global num_range, chances, no
34 num_range=100
35 chances=7
36 new_game()
37 def button_handler2():
38 global num_range, chances, no
39 num_range=1000
40 chances=15
41 new_game()
42 frame=simplegui.create_frame('GAME',1000,400)
43 button1=frame.add_button('1-100',button_handler1)
44 button2=frame.add_button('1-1000',button_handler2)
45 text_input=frame.add_input('Enter the Number',input_handler, 200)
46 frame.set_draw_handler(draw_handler)
47 frame.start()
Increasing Circle
In [7]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 radius=20
3 t=0
4 def draw_handler(canvas):
5 global radius
6 canvas.draw_circle((200,200),radius,12,'Green','Blue')
7 def timer_handler():
8 global radius,t
9 if radius>0 and radius<200:
10 radius+=1
11 t+=1
12 else:
13 radius=20
14
15 frame=simplegui.create_frame('CANVAS',400,400)
16 timer=simplegui.create_timer(50,timer_handler)
17 frame.set_draw_handler(draw_handler)
18 timer.start()
19 frame.start()
ScreenSaver
In [3]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import random
3
4 # Global state
5 message = "Python is Fun!"
6 position = [50, 50]
7 width = 500
8 height = 500
9 interval = 2000
10
11 # Handler for text box
12 def update(text):
13 global message
14 message = text
15
16 # Handler for timer
17 def tick():
18 x = random.randrange(0, width)
19 y = random.randrange(0, height)
20 position[0] = x
21 position[1] = y
22
23 # Handler to draw on canvas
24 def draw(canvas):
25 canvas.draw_text(message, position, 36, "Red")
26
27 # Create a frame
28 frame = simplegui.create_frame("Home", width, height)
29
30 # Register event handlers
31 text = frame.add_input("Message:", update, 150)
32 frame.set_draw_handler(draw)
33 timer = simplegui.create_timer(interval, tick)
34
35 # Start the frame animation
36
37 timer.start()
38 frame.start()
In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import random
3 msg="Hello"
4 coord=[50,50]
5 color=['DeepPink','Red','DarkOrange','Yellow','Lime','Aqua','Magenta']
6 t=0
7 def draw_handler(canvas):
8 global msg,coord
9 canvas.draw_text(msg,coord,48,'White')
10 frame.set_canvas_background(color[t])
11
12 def timer_handler():
13 global coord
14 coord1=random.randint(100,300)
15 coord2=random.randint(100,300)
16 coord=[coord1,coord2]
17 global t
18 t+=1
19 if t==7:
20 t=0
21 def input_handler(text_input):
22 global msg
23 msg=text_input
24
25 frame=simplegui.create_frame('SCREENSAVER',400,400)
26 text_input=frame.add_input('Enter the Text',input_handler, 200)
27 timer=simplegui.create_timer(1000,timer_handler)
28 frame.set_draw_handler(draw_handler)
29 timer.start()
30 frame.start()
Reaction Game
In [4]:

1 #Reaction time test


2 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
3 rt=0
4 message=''
5
6 def draw_handler(canvas):
7 canvas.draw_text(message,(100,150),50,'Magenta')
8
9 def stop_button():
10 global message
11 reaction_display_timer.stop()
12 message="Your reaction time " + str(rt)
13
14 def restart_button():
15 global rt,message
16 rt=0
17 message=''
18 reaction_display_timer.start()
19
20 def reaction_display_timer_handler():
21 global rt,message
22 rt=rt+1
23 message=str(rt)
24
25 frame=simplegui.create_frame('Testing',800,500)
26 frame.set_draw_handler(draw_handler)
27
28 reaction_display_timer=simplegui.create_timer(1,reaction_display_timer_handler)
29
30 button1=frame.add_button('stop',stop_button,150)
31 button2=frame.add_button('restart',restart_button,150)
32
33 reaction_display_timer.start()
34
35 frame.start()
Draw Line

In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_line((10,20),(60,70),12,"red")
4 frame=simplegui.create_frame('test',200,200)
5 frame.set_draw_handler(draw_handler)
6 frame.start()

Drawing a Polygon on Canvas


Draws a sequence of line segments between each adjacent pair of points in the non-empty list, plus a line
segment between the first and last points.

It is an error for the list of points to be empty.

Each point is a 2-element tuple or list of screen coordinates. The line's width is given in pixels, and must be
positive.

The fill color defaults to None. If the fill color is specified, then the interior of the polygon is colored.

Drawing Connected Lines on Canvas


Draws a sequence of line segments between each adjacent pair of points in the non-empty list.

It is an error for the list of points to be empty.

Each point is a 2-element tuple or list of screen coordinates.


The line's width is given in pixels and must be positive

In [3]:

1 #Drawing polygon with polyline to connect last and first point by just connecting
2 #last and first
3 #Drawing connected lines on canvas
4 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
5 def draw_handler(canvas):
6 canvas.draw_polyline([(10, 20), (30, 20), (90, 70),(10,20)], 5, 'Red')
7 canvas.draw_polyline([[40, 20], [80, 40], [30, 90],[40,20]], 6, 'Blue')
8 #It can pass tuple or list
9 frame = simplegui.create_frame('Testing', 400, 400)
10 frame.set_draw_handler(draw_handler)
11 frame.start()
In [7]:

1 # example of drawing operations in simplegui


2 # standard HMTL color such as "Red" and "Green"
3 # note later drawing operations overwrite earlier drawing operations
4
5 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
6
7
8 # Handler to draw on canvas
9 def draw(canvas):
10 canvas.draw_circle([100, 100], 50, 2, "Red", "Pink")
11 canvas.draw_circle([300, 300], 50, 2, "Red", "Pink")
12 canvas.draw_line([100, 100],[300, 300], 2, "Black")
13 canvas.draw_circle([100, 300], 50, 2, "Green", "Lime")
14 canvas.draw_circle([300, 100], 50, 2, "Green", "Lime")
15 canvas.draw_line([100, 300],[300, 100], 2, "Black")
16 canvas.draw_polygon([[150, 150], [250, 150], [250, 250], [150, 250]], 2,
17 "Blue", "Aqua")
18 canvas.draw_text("An example of drawing", [60, 385], 24, "Black")
19
20
21 # Create a frame and assign callbacks to event handlers
22 frame = simplegui.create_frame("Home", 400, 400)
23 frame.set_draw_handler(draw)
24 frame.set_canvas_background("Yellow")
25
26
27 # Start the frame animation
28 frame.start()
29
Mouse Event

Moving Ball using Mouse Click

In [23]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import math
3
4 #initalize globals
5 WIDTH=400
6 HEIGHT=400
7 ball_pos=[WIDTH/2,HEIGHT/2]
8 ball_radius=40
9 ball_color='Red'
10
11 #helper function
12 def distance(p,q):
13 return math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)
14
15 #define event handler for mouse click, draw
16 def click(pos):
17 global ball_pos, ball_color
18 if distance(pos, ball_pos) < ball_radius:
19 ball_color='Green'
20 else:
21 ball_pos = list(pos)
22 ball_color = 'Red'
23
24 def draw(canvas):
25 canvas.draw_circle(ball_pos, ball_radius, 1, 'Black', ball_color)
26
27 #create frame
28 frame=simplegui.create_frame('Mouse Selection', WIDTH, HEIGHT)
29 frame.set_canvas_background('black')
30
31
32 #register event handler
33 frame.set_mouseclick_handler(click)
34 frame.set_draw_handler(draw)
35
36 #start frame
37 frame.start()
Moving Ball using Mouse Drag

In [22]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 import math
3
4 #initalize globals
5 WIDTH=400
6 HEIGHT=400
7 ball_pos=[WIDTH/2,HEIGHT/2]
8 ball_radius=40
9 ball_color='Red'
10
11 #helper function
12 def distance(p,q):
13 return math.sqrt((p[0]-q[0])**2 + (p[1]-q[1])**2)
14
15 #define event handler for mouse click, draw
16 def click(pos):
17 global ball_pos, ball_color
18 if distance(pos, ball_pos) < ball_radius:
19 ball_color='Red'
20 else:
21 ball_pos = list(pos)
22 ball_color = 'Red'
23
24 def draw(canvas):
25 canvas.draw_circle(ball_pos, ball_radius, 1, 'Black', ball_color)
26
27 #create frame
28 frame=simplegui.create_frame('Mouse Selection', WIDTH, HEIGHT)
29 frame.set_canvas_background('Black')
30
31 #register event handler
32 frame.set_mousedrag_handler(click)
33 frame.set_draw_handler(draw)
34
35 #start frame
36 frame.start()
Click lines

In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 #Global variables
4 WIDTH=400
5 HEIGHT=400
6 points=[(WIDTH/2,HEIGHT/2)]
7
8 #Event handlers
9 def draw_handler(canvas):
10 canvas.draw_polyline(points,5,'White')
11
12 def click(pos):
13 global points
14 if pos!=points[-1]:
15 points.append(pos)
16 def reset():
17 global points
18 p = points[-1]
19 points=[p]
20
21 #Frame
22 frame=simplegui.create_frame('Click Lines',WIDTH,HEIGHT)
23
24 #Register Event Handlers
25 frame.set_mouseclick_handler(click)
26 frame.set_draw_handler(draw_handler)
27 frame.add_button('Reset',reset)
28 frame.start()
In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 #Global variables
4 WIDTH=400
5 HEIGHT=400
6 points=[(WIDTH/2,HEIGHT/2)]
7
8 #Event handlers
9 def draw_handler(canvas):
10 canvas.draw_polyline(points,5,'White')
11
12 def click(pos):
13 global points
14 if pos!=points[-1]:
15 points.append(pos)
16 def reset():
17 global points
18 p = points[-1]
19 points=[p]
20
21 #Frame
22 frame=simplegui.create_frame('Click Lines',WIDTH,HEIGHT)
23
24 #Register Event Handlers
25 frame.set_mousedrag_handler(click)
26 frame.set_draw_handler(draw_handler)
27 frame.add_button('Reset',reset)
28 frame.start()
Draw Point

In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_point((20,20),'Lime')
4 frame=simplegui.create_frame('Point',50,50)
5
6 #Register Event Handlers
7 frame.set_draw_handler(draw_handler)
8 frame.start()

Draw Image

In [11]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_image(image,(949//2,392//2),(949,392),(600,300),(1100,500))
4
5 image = simplegui._load_local_image('cards.png')
6 frame=simplegui.create_frame('Image',1200,600)
7 frame.set_draw_handler(draw_handler)
8 frame.start()
In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def draw_handler(canvas):
3 canvas.draw_image(image,(949//2,392//2),(949,392),(600,300),(1100,500))
4
5 image = simplegui.load_image('https://bit.ly/cards_deck')
6 frame=simplegui.create_frame('Image',1200,600)
7 frame.set_draw_handler(draw_handler)
8 frame.start()

In [ ]:

1 #bit.ly/cards_back

Keyboard Event Handlers


These add keyboard event handlers waiting for keydown, and keyup events, respectively. When any key is
pressed, the keydown handler is called once. When any key is released, the keyup handler is called once.

The handler for each should be defined with one parameter, as in the above example. This parameter will
receive an integer representing a keyboard character.

Keyboard Echo

In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 def key_handler(key):
4 pass
5
6 frame=simplegui.create_frame("Keyboard Event Handler",800,100)
7 frame.set_keydown_handler(key_handler)
8 frame.set_keyup_handler(key_handler)
9 frame.start()
In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 #initialize state (global)
3 current_key=" "
4
5 #event_handlers
6 def keydown(key):
7 global current_key
8 current_key=chr(key)
9 def keyup(key):
10 global current_key
11 current_key=" "
12 def draw(canvas):
13 canvas.draw_text((current_key),[100,200],200,'Red')
14 #Create a frame
15 frame=simplegui.create_frame("Echo",400,400)
16
17 #register event handlers
18 frame.set_keydown_handler(keydown)
19 frame.set_keyup_handler(keyup)
20 frame.set_draw_handler(draw)
21
22 #start frame
23 frame.start()
Ball Position Control

In [3]:

1 # Control ball position with the arrow keys


2
3 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
4
5 # initialize state
6 width = 400
7 height = 400
8 position = [int(width/2), int(height/2)]
9 radius = 40
10 velocity = 5
11
12 # event handlers
13 def keydown(key):
14 if key == simplegui.KEY_MAP['down']:
15 position[1] = position[1] + velocity
16 elif key == simplegui.KEY_MAP['up']:
17 position[1] = position[1] - velocity
18 elif key == simplegui.KEY_MAP['right']:
19 position[0] = position[0] + velocity
20 elif key == simplegui.KEY_MAP['left']:
21 position[0] = position[0] - velocity
22
23 def draw(canvas):
24 canvas.draw_circle(position, radius, 2, "red", "red")
25
26 # create frame
27 frame = simplegui.create_frame("Key Handling", width, height)
28
29 # register event handlers
30 frame.set_keydown_handler(keydown)
31 frame.set_draw_handler(draw)
32
33 # start frame
34 frame.start()
35

In [5]:

1 print(simplegui.KEY_MAP)

{'space': 32, 'left': 37, 'up': 38, 'right': 39, 'down': 40, '0': 48, '1':
49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 5
7, 'A': 65, 'B': 66, 'C': 67, 'D': 68, 'E': 69, 'F': 70, 'G': 71, 'H': 72,
'I': 73, 'J': 74, 'K': 75, 'L': 76, 'M': 77, 'N': 78, 'O': 79, 'P': 80,
'Q': 81, 'R': 82, 'S': 83, 'T': 84, 'U': 85, 'V': 86, 'W': 87, 'X': 88,
'Y': 89, 'Z': 90, 'a': 65, 'b': 66, 'c': 67, 'd': 68, 'e': 69, 'f': 70,
'g': 71, 'h': 72, 'i': 73, 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78,
'o': 79, 'p': 80, 'q': 81, 'r': 82, 's': 83, 't': 84, 'u': 85, 'v': 86,
'w': 87, 'x': 88, 'y': 89, 'z': 90}
Ball Motion

In [4]:

1 # Ball motion with an implicit timer


2
3 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
4
5 # Initialize globals
6 WIDTH = 600
7 HEIGHT = 400
8 BALL_RADIUS = 20
9
10 ball_pos = [WIDTH / 2, HEIGHT / 2]
11 vel = [0, 1] # pixels per update (1/60 seconds)
12
13 # define event handlers
14 def draw(canvas):
15 # Update ball position
16 ball_pos[0] += vel[0]
17 ball_pos[1] += vel[1]
18
19 # Draw ball
20 canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
21
22 # create frame
23 frame = simplegui.create_frame("Motion", WIDTH, HEIGHT)
24
25 # register event handlers
26 frame.set_draw_handler(draw)
27
28 # start frame
29 frame.start()
Ball Velocity Control

In [5]:

1 # control the velocity of a ball using the arrow keys


2
3 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
4
5 # Initialize globals
6 WIDTH = 600
7 HEIGHT = 400
8 BALL_RADIUS = 20
9
10 ball_pos = [WIDTH / 2, HEIGHT / 2]
11 vel = [0, 0]
12
13 # define event handlers
14 def draw(canvas):
15 # Update ball position
16 ball_pos[0] += vel[0]
17 ball_pos[1] += vel[1]
18
19 # Draw ball
20 canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
21
22 def keydown(key):
23 global vel
24 acc = 1
25 if key==simplegui.KEY_MAP["left"]:
26 vel[0] -= acc
27 elif key==simplegui.KEY_MAP["right"]:
28 vel[0] += acc
29 elif key==simplegui.KEY_MAP["down"]:
30 vel[1] += acc
31 elif key==simplegui.KEY_MAP["up"]:
32 vel[1] -= acc
33 else:
34 vel=[0,0]
35
36 #print(ball_pos)
37
38 # create frame
39 frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT)
40
41 # register event handlers
42 frame.set_draw_handler(draw)
43 frame.set_keydown_handler(keydown)
44
45 # start frame
46 frame.start()
47
In [7]:

1 # control the velocity of a ball using the arrow keys


2
3 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
4
5 # Initialize globals
6 WIDTH = 600
7 HEIGHT = 400
8 BALL_RADIUS = 20
9
10 ball_pos = [WIDTH / 2, HEIGHT / 2]
11 vel = [0, 0]
12
13 # define event handlers
14 def draw(canvas):
15 # Update ball position
16 ball_pos[0] += vel[0]
17 ball_pos[1] += vel[1]
18
19 # Draw ball
20 canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
21
22 def keydown(key):
23 global vel
24 acc = 1
25 if key==simplegui.KEY_MAP["left"]:
26 vel[0] -= acc
27 elif key==simplegui.KEY_MAP["right"]:
28 vel[0] += acc
29 elif key==simplegui.KEY_MAP["down"]:
30 vel[1] += acc
31 elif key==simplegui.KEY_MAP["up"]:
32 vel[1] -= acc
33 else:
34 vel=[0,0]
35
36 #print(ball_pos)
37
38 def reset():
39 global ball_pos, vel
40 ball_pos = [WIDTH / 2, HEIGHT / 2]
41 vel=[0,0]
42
43 # create frame
44 frame = simplegui.create_frame("Velocity ball control", WIDTH, HEIGHT)
45
46 # register event handlers
47 frame.set_draw_handler(draw)
48 frame.set_keydown_handler(keydown)
49 frame.add_button('Reset',reset)
50 # start frame
51 frame.start()
52
Collisions and Reflections

In [8]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2
3 # Initialize globals
4 WIDTH = 600
5 HEIGHT = 400
6 BALL_RADIUS = 20
7
8 ball_pos = [WIDTH / 2, HEIGHT / 2]
9 #vel = [-40.0 / 60.0, 5.0 / 60.0]
10 vel = [-1, 0]
11 # define event handlers
12 def draw(canvas):
13 # Update ball position
14 ball_pos[0] += vel[0]
15 ball_pos[1] += vel[1]
16
17 # collide and reflect off of left hand side of canvas
18 if ball_pos[0] <= BALL_RADIUS:
19 vel[0] = - vel[0]
20
21
22 # Draw ball
23 canvas.draw_circle(ball_pos, BALL_RADIUS, 2, "Red", "White")
24
25 # create frame
26 frame = simplegui.create_frame("Ball physics", WIDTH, HEIGHT)
27
28 # register event handlers
29 frame.set_draw_handler(draw)
30
31 # start frame
32 frame.start()
33
In [9]:

1 #Collisions and Reflections


2 #Ball Velocity Control
3 #Ball Motion
4 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
5 #initialize globals
6 width=600
7 height=400
8 ball_radius=20
9 ball_pos=[width/2,height/2]
10 vel=[0,0] #pixels per update (1/60 seconds)
11
12 #define event handlers
13 def draw(canvas):
14 #Update ball position
15 ball_pos[0]+=vel[0]
16 ball_pos[1]+=vel[1]
17 #collision condition
18 #if in this condition taken 0 instead of ball_radius
19 #then half ball will go out
20 if ball_pos[0]<=ball_radius:
21 vel[0]=-vel[0]
22 if ball_pos[0]>=width-ball_radius:
23 vel[0]=-vel[0]
24 if ball_pos[1]<=ball_radius:
25 vel[1]=-vel[1]
26 if ball_pos[1]>=height-ball_radius:
27 vel[1]=-vel[1]
28 #Draw ball
29 canvas.draw_circle(ball_pos,ball_radius,2,"red","white")
30 def keydown(key):
31 global vel
32 acc=1
33 if key==simplegui.KEY_MAP['down']:
34 vel[1]+=acc
35 elif key==simplegui.KEY_MAP['up']:
36 vel[1]-=acc
37 elif key==simplegui.KEY_MAP['left']:
38 vel[0]-=acc
39 elif key==simplegui.KEY_MAP['right']:
40 vel[0]+=acc
41 else:
42 vel=[0,0] # for any other key ball will stop
43 #print(ball_pos)
44 #create frame
45 frame=simplegui.create_frame("Motion",width,height)
46 #Register event handlers
47 frame.set_draw_handler(draw)
48 frame.set_keydown_handler(keydown)
49 #start
50 frame.start()

Sound
sound.play()

sound.pause()
sound.rewind()

sound.set_volume()

In [ ]:

1 #bit.ly/game_sound

In [1]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def play():
3 sound.play()
4 def pause():
5 sound.pause()
6
7
8 sound=simplegui._load_local_sound('FurElise.wav')
9 frame=simplegui.create_frame('Sound',400,400)
10 frame.add_button('Play',play)
11 frame.add_button('Pause',pause)
12 frame.start()

In [2]:

1 import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


2 def play():
3 sound.play()
4 def pause():
5 sound.pause()
6
7
8 sound=simplegui.load_sound('https://www.dropbox.com/scl/fi/5mzpaja5uxu2qgoa3vc7d/Fur
9 frame=simplegui.create_frame('Sound',400,400)
10 frame.add_button('Play',play)
11 frame.add_button('Pause',pause)
12 frame.start()

You might also like