0% found this document useful (0 votes)
53 views46 pages

T3 - QB - Chapter 7 - QB - Solution

This program creates a simple stopwatch game with timers. It contains start, stop, and reset buttons. Global variables track the elapsed time in tenths of a second (t), a formatted time string (t_str), a flag for the timer status, and counts for stops and wins. A timer callback increments t by 0.1 seconds. Button callbacks start/stop the timer and reset values. The draw handler displays the time string and win/stop counts.

Uploaded by

Palak Rathore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views46 pages

T3 - QB - Chapter 7 - QB - Solution

This program creates a simple stopwatch game with timers. It contains start, stop, and reset buttons. Global variables track the elapsed time in tenths of a second (t), a formatted time string (t_str), a flag for the timer status, and counts for stops and wins. A timer callback increments t by 0.1 seconds. Button callbacks start/stop the timer and reset values. The draw handler displays the time string and win/stop counts.

Uploaded by

Palak Rathore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Q. 25.

Create a canvas of size 96×96, and draw the letter "X" with
font size 48 in the upper left portion of the canvas. Review the
syntax for the SimpleGUI method draw_text and the layout of
canvas coordinates.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
def draw_3(canvas):
canvas.draw_text('X', [0,30], 48, 'white')

# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("Draw X", 96, 96)
frame.set_draw_handler(draw_3)

# Start the frame animation
frame.start()

image.png

Q. 26. Prepare the program and add two buttons that control the
radius of a white ball centered in the middle of the canvas. Clicking
the “Increase radius” button should increase the radius of the ball.
Clicking the “Decrease radius” button should decrease the radius
of the ball, except that the ball radius should always be positive.
In [ ]: # Define globals - Constants are capitalized in Python
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
HEIGHT = 400
WIDTH = 400
RADIUS_INCREMENT = 5
ball_radius = 20

# Draw handler
def draw_4(canvas):
canvas.draw_circle([WIDTH/2, HEIGHT/2], ball_radius, 1, "white")

# Event handlers for buttons
def increase_radius():
global ball_radius
ball_radius = ball_radius + RADIUS_INCREMENT

def decrease_radius():
global ball_radius
ball_radius = ball_radius - RADIUS_INCREMENT

# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("Ball control", WIDTH, HEIGHT)
frame.set_draw_handler(draw_4)
frame.add_button("Increase radius", increase_radius)
frame.add_button("Decrease radius", decrease_radius)

# Start the frame animation
frame.start()

After running
image.png

After clicking on increase radius button radius increases


image-2.png

After clicking on decrease radius button radius decreases


image-3.png
Q. 27. The following program should count upward from zero. Print
the counter values 0, 1, 2, … to the console. Add two lines of
Python to make this program work. Hint: Add a global variable to a
timer callback, and start a timer. Given the solution from the
following problem, we again want a counter printed to the console.
Add three buttons that start, stop and reset the counter,
respectively.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

counter = 0
running = False

def start_timer():
global running
running = True

def stop_timer():
global running
running = False

def reset_timer():
global counter
counter = 0
if not running:
update_display()

def update_timer():
global counter
if running:
counter += 1
update_display()

def update_display(canvas):
canvas.draw_text(str(counter), (50, 100), 40, "White")

frame = simplegui.create_frame("Counter", 200, 200)
frame.add_button("Start", start_timer)
frame.add_button("Stop", stop_timer)
frame.add_button("Reset", reset_timer)
frame.set_draw_handler(update_display)

timer = simplegui.create_timer(1000, update_timer)

frame.start()
timer.start()

Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Users\Abhi\anaconda3\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Abhi\anaconda3\Lib\threading.py", line 1394, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\Abhi\anaconda3\Lib\site-packages\SimpleGUICS2Pygame\simpleguics2pygame\timer.py", line 13
3, in repeat_handler
timer_handler()
File "C:\Users\Abhi\AppData\Local\Temp\ipykernel_8704\3122476128.py", line 24, in update_timer
TypeError: update_display() missing 1 required positional argument: 'canvas'
Exception in thread Thread-7:
Traceback (most recent call last):
File "C:\Users\Abhi\anaconda3\Lib\threading.py", line 1038, in _bootstrap_inner
self.run()
File "C:\Users\Abhi\anaconda3\Lib\threading.py", line 1394, in run
self.function(*self.args, **self.kwargs)
File "C:\Users\Abhi\anaconda3\Lib\site-packages\SimpleGUICS2Pygame\simpleguics2pygame\timer.py", line 13
3, in repeat_handler
ti h dl ()
image.png

Q. 28. Use a timer to toggle the canvas background back and forth
between red and blue every 3 seconds. To locate the appropriate
call to change the background color of the canvas.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui




# Global variables
canvas_width = 400
canvas_height = 200
background_color = "red"

def toggle_background():
global background_color
if background_color == "red":
background_color = "blue"
else:
background_color = "red"

def draw_handler(canvas):
canvas.draw_text("Canvas Background", (30, 100), 36, "White")
canvas.draw_polygon([(0, 0), (canvas_width, 0), (canvas_width, canvas_height), (0, canvas_height)], 1, "Wh

# Create a frame
frame = simplegui.create_frame("Toggle Background", canvas_width, canvas_height)

# Register the draw handler
frame.set_draw_handler(draw_handler)

# Create a timer that calls toggle_background() every 3000 milliseconds (3 seconds)
timer = simplegui.create_timer(3000, toggle_background)

# Start the timer
timer.start()

# Start the frame
frame.start()

First this red


image.png

And then blue


image-2.png

Q. 29. Create a circle in the center of the canvas. Use a timer to


increase its radius one pixel every tenth of a second.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
WIDTH = 200
HEIGHT = 200
radius = 1

# Timer handler
def tick_4():
global radius
radius += 1

# Draw handler
def draw_6(canvas):
canvas.draw_circle([100,100], radius, 1, "white")

# Create frame and timer
frame = simplegui.create_frame("Cool Frame", 200, 200)
timer = simplegui.create_timer(10, tick_4)

frame.set_draw_handler(draw_6)

# Start timer
frame.start()
timer.start()

image.png

Q. 30. Use a timer to measure how fast you can press a button
twice. Create a button that starts a timer that ticks every hundredth
of a second. The first button press starts the measurement. The
second button press ends the measurement. Print to the console
the time elapsed between button presses. The next two button
presses should repeat this process, making a new measurement.
Hint: We suggest that you keep track of whether the program is on
the first or second button press using a global Boolean variable
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
total_ticks = 0
first_click = True


# Timer handler
def tick_5():
global total_ticks
total_ticks += 1

# Button handler
def click_6():
global first_click
global total_ticks

if first_click == True:
timer.start()
print('Timer started!')

# set first_click to the opposite boolean
first_click = not first_click
else:
timer.stop()
print('Timer stopped!')

print('Total ticks: ' + str(total_ticks))

# reset the game state
total_ticks = 0
first_click = True

print('Game state reset. Click to play again.')

# Create frame and timer
frame = simplegui.create_frame("Counter with buttons", 200, 200)
frame.add_button("Click me", click_6, 200)
timer = simplegui.create_timer(10, tick_5)

# Start timer
frame.start()

Timer started!
Timer stopped!
Total ticks: 112
Game state reset. Click to play again.
Timer started!
Timer stopped!
Total ticks: 220
Game state reset. Click to play again.

image.png

Q. 31. Create a Stopwatch:The Game with timers to build a simple


digital stopwatch that keeps track of the time in tenths of a second.
The stopwatch should contain "Start", "Stop" and "Reset"
buttons.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# define global variables
t = 0
t_str = "0:00.0"

position = [60, 100]
width = 200
height = 200
interval = 100

flag = False
stop_num = 0
win_num = 0
score_str = str(win_num) + "/" + str(stop_num)

# define helper function format that converts time
# in tenths of seconds into formatted string A:BC.D
def format(t):
tens_second = t % 10
t = t // 10
second = t % 60
minute = t // 60
second_str = str(second)
if second < 10:
second_str = "0" + str(second)
format_t = str(minute) + ":" + second_str + "." + str(tens_second)
return format_t

def update_score():
global stop_num
global win_num
global score_str
global flag

if not timer.is_running():
if flag:
flag = False
stop_num += 1
if t % 10 == 0:
win_num += 1
else:
flag = True
score_str = str(win_num) + "/" + str(stop_num)

def reset_score():
global flag
global stop_num
global win_num
global score_str

flag = False
stop_num = 0
win_num = 0
score_str = str(win_num) + "/" + str(stop_num)

# define event handlers for buttons; "Start", "Stop", "Reset"
def start_handler():
timer.start()

def stop_handler():
timer.stop()

def reset_handler():
timer.stop()
global t
global t_str

reset_score()

# define event handler for timer with 0.1 sec interval
def timer_handler():
global t
global t_str
t = t + 1
t_str = format(t)

def timer_score_handler():
update_score()


# define draw handler
def draw_handler(canvas):
canvas.draw_text(t_str, position, 36, "White")
canvas.draw_text(score_str, [160, 20], 16, "green")

# create frame
frame = simplegui.create_frame("Stopwatch", width, height)

# register event handlers
frame.add_button("Start", start_handler)
frame.add_button("Stop", stop_handler)
frame.add_button("Reset", reset_handler)
frame.set_draw_handler(draw_handler)
timer = simplegui.create_timer(interval, timer_handler)
timer_score = simplegui.create_timer(interval, timer_score_handler)
# start frame
frame.start()
timer_score.start()

After pressing start button


image.png

After pressing stop button


image-2.png

After pressing reset button


image-3.png

Q.32. Create a Python Program that echo the message "Pressed up


arrow" or "Pressed down arrow" whenever the appropriate key is
pressed.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

message = "Welcome!"

# Handler for keydown
def keydown(key):
global message
####### Add KEY_MAP to translate to key codes
if key == simplegui.KEY_MAP["up"]:
message = "Up arrow"
elif key == simplegui.KEY_MAP["down"]:
message = "Down arrow"

# Handler to draw on canvas
def draw(canvas):
canvas.draw_text(message, [50,112], 48, "Red")

# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 300, 200)
#### register the kedown handler
frame.set_keydown_handler(keydown)
frame.set_draw_handler(draw)

# Start the frame animation
frame.start()

After running then screen also looks like


image.png

By pressing key up
image-2.png

By pressing key down


image-3.png

Q. 33. Create a Python Program such that each press of the up


arrow increases the radius of the white ball centered in the middle
of the canvas by a small fixed amount and each press of the down
arrow key decreases the radius of the ball by the same amount.
Your added code should be placed in the keydown handler. (Note
that draw_circle will throw an error if the radius of the circle is
decreased to zero or less.)
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

WIDTH = 300
HEIGHT = 200
ball_radius = 50
BALL_RADIUS_INC = 3

# Handler for keydown
def keydown(key):
global ball_radius
if key == simplegui.KEY_MAP["up"]:
ball_radius += BALL_RADIUS_INC
if ball_radius > WIDTH / 2: # <--- Stop increment
ball_radius = WIDTH / 2
# Add code here to control ball_radius
elif key == simplegui.KEY_MAP["down"]:
ball_radius -= BALL_RADIUS_INC
if ball_radius < 1: # <--- Stop decrement
ball_radius = 1

# Handler to draw on canvas
def draw(canvas):
# note that CodeSkulptor throws an error if radius is not positive
canvas.draw_circle([WIDTH / 2, HEIGHT / 2], ball_radius, 1, "White", "White")

# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 300, 200)
frame.set_keydown_handler(keydown)
frame.set_draw_handler(draw)

# Start the frame animation
frame.start()

By pressing up key
image.png
By pressing down down
image-2.png

Q. 34. "Design the program displays ""Space bar down"" on the


canvas while the space bar is held down and ""Space bar up""
while the space bar is up. You will need to add code to both the
keydown and keyup handlers. "
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
message = "Space bar up"

# Handlers for keydown and keyup
def keydown(key):
global message
if key == simplegui.KEY_MAP["space"]:
message = "Space bar down"

def keyup(key):
global message
if key == simplegui.KEY_MAP["space"]:
message = "Space bar up"

# Handler to draw on canvas
def draw(canvas):
canvas.draw_text(message, [25, 112], 42, "Red")

# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 300, 200)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.set_draw_handler(draw)

# Start the frame animation
frame.start()

By default
image.png
By pressing space bar
image-2.png

Q. 35. Design a python program so that holding down the up arrow


key increases the radius of the white ball centered in the middle of
the canvas by a small fixed amount each frame. Releasing the up
arrow key causes that growth to cease. You will need to add code
to the keydown and keyup handlers as well as the draw handler.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
WIDTH = 300
HEIGHT = 200
ball_radius = 10
ball_growth = 0
BALL_GROWTH_INC = .2

# Handlers for keydown and keyup
def keydown(key):
global ball_growth
if key == simplegui.KEY_MAP["up"]:
ball_growth += BALL_GROWTH_INC
elif key == simplegui.KEY_MAP["down"]:
ball_growth -= BALL_GROWTH_INC

def keyup(key):
global ball_growth
if (key == simplegui.KEY_MAP["up"]) or (key == simplegui.KEY_MAP["down"]):
ball_growth = 0

# Handler to draw on canvas
def draw(canvas):
global ball_radius
ball_radius += ball_growth
if ball_radius < 2:
ball_radius = 2
canvas.draw_circle([WIDTH / 2, HEIGHT / 2], ball_radius, 2, "Red", "White")

# Create a frame and assign callbacks to event handlers
frame = simplegui.create_frame("Home", 300, 200)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.set_draw_handler(draw)

# Start the frame animation
frame.start()

For keyup
image.png

For keydown
image-2 png

Q. 35. Design a pong game using simplegui and interactive


environment using simplegui (EXtra)
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random

# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
side = True

# initialize ball_pos and ball_vel for new bal in middle of table
# if direction is RIGHT, the ball's velocity is upper right, else upper left
def spawn_ball(RIGHT):
global ball_pos, ball_vel # these are vectors stored as lists
global score1,score2
ball_pos=[WIDTH/2,HEIGHT/2]
if RIGHT==True:
ball_vel=[random.randrange(2,4),-random.randrange(1,3)]
else:
ball_vel=[-random.randrange(2,4),-random.randrange(1,3)]


# define event handlers
def new_game():
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel # these are numbers
global score1, score2,side # these are ints

paddle1_pos, paddle2_pos = (HEIGHT - PAD_HEIGHT)/2, (HEIGHT - PAD_HEIGHT)/2
score1 , score2 = 0, 0
paddle1_vel = paddle2_vel = 0
side=not side
spawn_ball(side)




def draw(canvas):
global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
global paddle1_pos, paddle2_pos, paddle1_vel, paddle2_vel

# draw mid line and gutters
canvas.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
canvas.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
canvas.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")

# update paddle's vertical position, keep paddle on the screen
if 0 <= (paddle1_pos + paddle1_vel) <= HEIGHT - PAD_HEIGHT:
paddle1_pos += paddle1_vel
if 0 <= (paddle2_pos + paddle2_vel) <= HEIGHT - PAD_HEIGHT:
paddle2_pos += paddle2_vel

# draw paddles
canvas.draw_line([PAD_WIDTH/2, paddle1_pos],[PAD_WIDTH/2, paddle1_pos+PAD_HEIGHT], PAD_WIDTH, "White")
canvas.draw_line([WIDTH - PAD_WIDTH/2, paddle2_pos],[WIDTH- PAD_WIDTH/2, paddle2_pos+PAD_HEIGHT], PAD_WIDT

# determine whether paddle and ball collide
if ball_pos[0]<=BALL_RADIUS+PAD_WIDTH:
if paddle1_pos<=ball_pos[1]<=(paddle1_pos+PAD_HEIGHT):
ball_vel[0]=-1.1*ball_vel[0]
else:
spawn_ball(True)
score2+=1

elif ball_pos[0]>=WIDTH-BALL_RADIUS-PAD_WIDTH:
if paddle2_pos<=ball_pos[1]<=paddle2_pos+PAD_HEIGHT:
ball_vel[0]=-1.1*ball_vel[0]
else:
spawn_ball(False)
score1+=1
if ball_pos[1]<=BALL_RADIUS:
ball_vel[1]=-ball_vel[1]
if ball_pos[1]>=(HEIGHT-BALL_RADIUS):
ball_vel[1]=-ball_vel[1]


ball_pos[0]+=ball_vel[0]
ball_pos[1]+=ball_vel[1]

# draw ball
canvas.draw_circle(ball_pos,BALL_RADIUS,3,"White","Green")
# draw scores
canvas.draw_text(str(score1),[20,40],50,"White")
canvas.draw_text(str(score2),[555,40],50,"White")
canvas.draw_text("created by sachin!",[400,390],20,"Red")
def keydown(key):
global paddle1_vel, paddle2_vel
vel=3
if key == simplegui.KEY_MAP["s"]:
paddle1_vel=vel
if key == simplegui.KEY_MAP["w"]:
paddle1_vel=-vel
if key == simplegui.KEY_MAP["up"]:
paddle2_vel=-vel
if key == simplegui.KEY_MAP["down"]:
paddle2_vel=vel
def keyup(key):
global paddle1_vel, paddle2_vel
vel=0
if key == simplegui.KEY_MAP["s"]:
paddle1_vel=0
if key == simplegui.KEY_MAP["w"]:
paddle1_vel=0
if key == simplegui.KEY_MAP["up"]:
paddle2_vel=0
if key == simplegui.KEY_MAP["down"]:
paddle2_vel=0

# create frame
frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("Restart", new_game, 100)

# start frame
new_game()
frame.start()

image.png

Q. 36. Create a GUI based Simple Calculator using


SimpleGUICS2Pygame module which includes simple operations
like addition subtraction multiplication and division
In [ ]: #Task
#Build a simple calculator GUI
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
a=0
b=0
ans=0
def a_input_handler(user_a):
global a
a=int(user_a)
def b_input_handler(user_b):
global b
b=int(user_b)
def add_button_handler():
global ans
ans=a+b
def sub_button_handler():
global ans
ans=a-b
def div_button_handler():
global ans
ans=a/b
def mul_button_handler():
global ans
ans=a*b
def modulo_button_handler():
global ans
ans=a%b
def power_button_handler():
global ans
ans=a**b
def draw_handler(canvas):
canvas.draw_text(str(ans),(100,50),50,'Magenta')
frame=simplegui.create_frame('Testing',500,500,300)
inp=frame.add_input('Enter a:',a_input_handler,50)
inp=frame.add_input('Enter b:',b_input_handler,50)
button1=frame.add_button('add',add_button_handler,150)
button2=frame.add_button('sub',sub_button_handler,150)
button3=frame.add_button('div',div_button_handler,150)
button4=frame.add_button('mul',mul_button_handler,150)
button5=frame.add_button('mod',modulo_button_handler,150)
button6=frame.add_button('power',power_button_handler,150)
frame.set_draw_handler(draw_handler)
frame.start()

After running this

image.png

Adding two numbers the output will be: (Note: while adding numbers one have to add the number and press enter each time) The
output will be:

image-2.png

Do this for all operations

Q. 37. Create a GUI based Number Guessing Game using


SimpleGUICS2Pygame module for range of 1 to 1000 numbers and
also add button which can restart the game.
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
num_range=100
computer_choice=random.randint(1,num_range)
guess=0
chances=0
message=' '
status=False
def new_game():
global num_range,chances,computer_choice
computer_choice=random.randint(1,num_range)
def draw_handler(canvas):
global chances
global message
canvas.draw_text(message,(200,150),50,'Magenta')
canvas.draw_text(str(chances),(200,300),50,'Magenta')
def input_handler(user_guess):
global chances
global message
global status
if status==False:
guess=int(user_guess)
if guess>computer_choice:
message='lower'
elif guess<computer_choice:
message='higher'
elif guess==computer_choice:
status=True
message='You win'
if chances>0:
chances=chances-1
if chances==0:
message='You Loose. The number was' + str(computer_choice)

def range_100():
global chances,num_range,message
num_range=100
chances=7
message=''
new_game()
def range_1000():
global chances,num_range,message
num_range=100
chances=14
message=''
new_game()
frame=simplegui.create_frame('Testing',800,500)
frame.set_draw_handler(draw_handler)
button1=frame.add_button('range from 1 to 100',range_100,150)
button2=frame.add_button('range from 1 to 1000',range_1000,150)
inp=frame.add_input('Enter your guess',input_handler,50)
frame.start()
#timer can be added

image.png

After guessing
image-2.png

Q. 38. Create a GUI which can create a screen saver for the screen
and the text can also be moved in the entire position randomly.
In [ ]: import random
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
message=''
positionx=0
positiony=0
def draw_handler(canvas):
global message,positionx,positiony
canvas.draw_text(message,(positionx,positiony),50,'Magenta')
def timer_handler():
global message,positionx,positiony
positionx=random.randint(0,800)
positiony=random.randint(0,500)
def input_handler(user_message):
global message
message=user_message
frame=simplegui.create_frame('Testing',800,500)
frame.set_draw_handler(draw_handler)

inp=frame.add_input('Enter your message',input_handler,50)
timer=simplegui.create_timer(1000,timer_handler)
timer.start()
frame.start()
#to control within the screen and should not be cut

image.png

Q. 39. Write a Python Program to demonstrate collision and


reflection in a moving ball on the canvas. The ball should move left
on its own from the center of the canvas and upon colliding with
the left edge of the canvas, should start moving in the opposite
directions.
In [ ]: #Collisions and Reflections
#Ball Velocity Control
#Ball Motion
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

#initialize globals
width=600
height=400
ball_radius=20

ball_pos=[width/2,height/2]
vel=[0,0] #pixels per update (1/60 seconds)

#define event handlers
def draw(canvas):
#Update ball position
ball_pos[0]+=vel[0]
ball_pos[1]+=vel[1]
#collision condition
#if in this condition taken 0 instead of ball_radius
#then half ball will go out
if ball_pos[0]<=ball_radius:
vel[0]=-vel[0]
if ball_pos[0]>=width-ball_radius:
vel[0]=-vel[0]
if ball_pos[1]<=ball_radius:
vel[1]=-vel[1]
if ball_pos[1]>=height-ball_radius:
vel[1]=-vel[1]
#Draw ball
canvas.draw_circle(ball_pos,ball_radius,2,"red","white")
def keydown(key):
global vel
acc=1
global position
if key==simplegui.KEY_MAP['down']:
vel[1]+=acc
elif key==simplegui.KEY_MAP['up']:
vel[1]-=acc
elif key==simplegui.KEY_MAP['left']:
vel[0]-=acc
elif key==simplegui.KEY_MAP['right']:
vel[0]+=acc
print(ball_pos)
#create frame
frame=simplegui.create_frame("Motion",width,height)



#Register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
#start
frame.start()

[300.0, 200.0]
[282.0, 200.0]
[252.0, 200.0]
[48.0, 200.0]
[26.0, 200.0]
[108.0, 200.0]
[122.0, 186.0]
[134.0, 162.0]
[145.0, 129.0]
[155.0, 89.0]
[182.0, 84.0]
[196.0, 168.0]
[209.0, 259.0]

image.png

Q. 40. "Create a Brick Breaker using Python SimpleGUiCS2Pygame


module. We will start with a simple Brick breaker game in which
there is a ball that bounces of a platform to break a brick wall and
the player has to keep the ball going by making sure the paddle is
always there to bounce off the ball back. To simplify the logic and
user interface of the game, the following are the type of bricks:
Green brick: Requires three hits to break

Pink bricks: Requires two hits to break


Purple bricks: Requires three hits to break

The game will have three layers of bricks, and each layer of brick will have a different hit capacity, which means some bricks will break
in a single hit, some will require a double hit and some will require three hits.

"
In [ ]: ​
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
# Constants
CANVAS_WIDTH = 600
CANVAS_HEIGHT = 400
PADDLE_WIDTH = 100
PADDLE_HEIGHT = 10
PADDLE_COLOR = "White"
BALL_RADIUS = 10
BALL_COLOR = "Red"
BALL_SPEED = 3

# Bricks
BRICK_WIDTH = 80
BRICK_HEIGHT = 20
BRICK_PADDING = 5
BRICK_COLOR = {"Green": "Green", "Pink": "Pink", "Purple": "Purple"}
BRICK_HIT_CAPACITY = {"Green": 3, "Pink": 2, "Purple": 3}
BRICK_ROWS = 3
BRICK_COLS = 8

# Game variables
paddle_pos = CANVAS_WIDTH // 2
ball_pos = [CANVAS_WIDTH // 2, CANVAS_HEIGHT // 2]
ball_vel = [BALL_SPEED, -BALL_SPEED]
bricks = []

# Initialize bricks
for row in range(BRICK_ROWS):
for col in range(BRICK_COLS):
brick_color = list(BRICK_COLOR.keys())[row]
bricks.append((BRICK_WIDTH * col, BRICK_HEIGHT * row, brick_color))

def draw(canvas):
global ball_pos, ball_vel, paddle_pos

# Update ball position
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]

# Bounce ball off walls
if ball_pos[0] <= BALL_RADIUS or ball_pos[0] >= CANVAS_WIDTH - BALL_RADIUS:
ball_vel[0] = -ball_vel[0]
if ball_pos[1] <= BALL_RADIUS:
ball_vel[1] = -ball_vel[1]

# Check collision with paddle
if ball_pos[1] + BALL_RADIUS >= CANVAS_HEIGHT - PADDLE_HEIGHT and (
paddle_pos <= ball_pos[0] <= paddle_pos + PADDLE_WIDTH
):
ball_vel[1] = -ball_vel[1]

# Check collision with bricks
for brick in bricks:
if (
ball_pos[0] >= brick[0]
and ball_pos[0] <= brick[0] + BRICK_WIDTH
and ball_pos[1] >= brick[1]
and ball_pos[1] <= brick[1] + BRICK_HEIGHT
):
brick_color = brick[2]
if BRICK_HIT_CAPACITY[brick_color] > 1:
BRICK_HIT_CAPACITY[brick_color] -= 1
else:
bricks.remove(brick)
ball_vel[1] = -ball_vel[1]

# Draw bricks
for brick in bricks:
canvas.draw_polygon(
[
[brick[0], brick[1]],
[brick[0] + BRICK_WIDTH, brick[1]],
[brick[0] + BRICK_WIDTH, brick[1] + BRICK_HEIGHT],
[brick[0], brick[1] + BRICK_HEIGHT],
],
1,
"Black",
BRICK_COLOR[brick[2]],
)

# Draw paddle
canvas.draw_polygon(
[
[paddle_pos, CANVAS_HEIGHT - PADDLE_HEIGHT],
[paddle_pos + PADDLE_WIDTH, CANVAS_HEIGHT - PADDLE_HEIGHT],
[paddle_pos + PADDLE_WIDTH, CANVAS_HEIGHT],
[paddle_pos, CANVAS_HEIGHT],
],
1,
"Black",
PADDLE_COLOR,
)

# Draw ball
canvas.draw_circle(ball_pos, BALL_RADIUS, 1, "Black", BALL_COLOR)

def keydown(key):
global paddle_pos
if key == simplegui.KEY_MAP["left"]:
paddle_pos -= 20
elif key == simplegui.KEY_MAP["right"]:
paddle_pos += 20

def keyup(key):
pass

frame = simplegui.create_frame("Brick Breaker", CANVAS_WIDTH, CANVAS_HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.start()

image-2.png

image.png

Q. 41. Create a SimpleGUI that allows the user to convert


temperatures between Celsius and Fahrenheit. The application
should have two input fields, one for Celsius and one for
Fahrenheit. When the user enters a value in one of the fields, the
corresponding temperature in the other field should update
automatically. Create a Python Program using
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def celsius_to_fahrenheit(celsius_temp):
return (celsius_temp * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit_temp):
return (fahrenheit_temp - 32) * 5/9

def on_celsius_change(text):
try:
celsius_temp = float(text)
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
f_input.set_text(str(fahrenheit_temp))
except ValueError:
f_input.set_text("Invalid Input")

def on_fahrenheit_change(text):
try:
fahrenheit_temp = float(text)
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
c_input.set_text(str(celsius_temp))
except ValueError:
c_input.set_text("Invalid Input")

frame = simplegui.create_frame("Temperature Converter", 300, 200)

c_input = frame.add_input("Celsius:", on_celsius_change, 100)
f_input = frame.add_input("Fahrenheit:", on_fahrenheit_change, 100)

frame.start()

image.png

Q. 42. Create a SimpleGUI-based to-do list. The application should


have an input field where the user can enter tasks and a "Add"
button to add them to the list. Display the list of tasks on the
screen. Allow the user to mark tasks as completed and remove
them from the list. Create a Python Program using
SimpleGUICS2Pygame module
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

tasks = []

def add_task(text):
tasks.append(text)
update_list()

def remove_task(index):
tasks.pop(index)
update_list()

def update_list():
list.set_text("\n".join(tasks))

frame = simplegui.create_frame("To-Do List", 200, 200)
task_input = frame.add_input("New Task:", add_task, 150)
list = frame.add_label("", 200)
frame.add_button("Remove Last Task", remove_task, 150)

frame.start()

image.png

Q 43. Create a SimpleGUI that counts the number of key presses


for a specific key (e.g., spacebar or any letter). Display the count on
the screen, and allow the user to reset the count with a button.
Create a Python Program using SimpleGUICS2Pygame module
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

# Global variables
key_to_count = "space"
key_count = 0

def key_down(key):
global key_count
if key == simplegui.KEY_MAP[key_to_count]:
key_count += 1

def reset_count():
global key_count
key_count = 0

def draw(canvas):
canvas.draw_text(f"Press '{key_to_count}' to count:", (20, 40), 20, "Black")
canvas.draw_text(str(key_count), (150, 100), 36, "Black")

frame = simplegui.create_frame("Key Press Counter", 300, 200)
frame.set_draw_handler(draw)
frame.set_keydown_handler(key_down)
frame.add_button("Reset Count", reset_count)

frame.start()

Q. 44. Create a SimpleGUI for sentiment analysis. Allow the user to


enter a sentence or text and analyze its sentiment. Display whether
the sentiment is positive, negative, or neutral based on simple
keyword matching. Sentiment analysis is the process of analyzing
digital text to determine if the emotional tone of the message is
positive, negative, or neutral. Create a Python Program using
SimpleGUICS2Pygame module
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui

def analyze_sentiment(text):
positive_words = ["happy", "good", "awesome", "love"]
negative_words = ["sad", "bad", "terrible", "hate"]

text_lower = text.lower()
num_positive = sum(1 for word in positive_words if word in text_lower)
num_negative = sum(1 for word in negative_words if word in text_lower)

if num_positive > num_negative:
result_output.set_text("Sentiment: Positive")
elif num_positive < num_negative:
result_output.set_text("Sentiment: Negative")
else:
result_output.set_text("Sentiment: Neutral")

frame = simplegui.create_frame("Sentiment Analyzer", 300, 150)
input_text = frame.add_input("Enter your text:", analyze_sentiment, 200)
result_output = frame.add_label("Sentiment: ")

frame.start()

image.png

Q. 45. Create a SimpleGUI for tracking expenses. Allow the user to


input expenses with descriptions and amounts, and display the
total expenses and a list of all entered expenses. Create a Python
Program using SimpleGUICS2Pygame module
In [ ]: import SimpleGUICS2Pygame.simpleguics2pygame as simplegui


# Global variables
total_expenses = 0

def expenses_handler():
global total_expenses,expense
expense = float(input_box.get_text())
total_expenses += expense
update_label()

def update_label():
label.set_text("Total expenses: $" + str(total_expenses))
def input_handler(user_expense):
global expense
expense=user_expense
def draw_handler(canvas):
global total_expenses
canvas.draw_text(str(total_expenses),(50,50),12,"Red")

frame = simplegui.create_frame("Expense Tracker", 200, 200)
frame.set_draw_handler(draw_handler)
input_box = frame.add_input("Enter expense:",input_handler,100)
label = frame.add_label("Total expenses: $0")
button = frame.add_button("Add expense", expenses_handler)
frame.start()

image.png

In [ ]: ​

You might also like