Practice Exercises for Keyboard

Contents

Practice Exercises for Keyboard#

1#

The program template contains a program designed to echo the message "Pressed up arrow" or "Pressed down arrow" whenever the appropriate key is pressed. Debug the program template and fix the program. Keyboard debugging templateKeyboard debugging solutionKeyboard debugging (Checker)


# Key board debugging - debug and fix the code below

import simplegui

message = "Welcome!"

# Handler for keydown
def keydown(key):
    global message
    if key == "up":  # <======= KEY_MAP must be used
        message = "Up arrow"
    elif key == "down":  # <======= KEY_MAP must be used
        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)
frame.set_draw_handler(draw)

# Start the frame animation
frame.start()

2#

Complete the program template below so 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.) Ball radius 1 templateBall radius 1 solutionBall radius 1 (Checker)


# Ball radius control - version 1

try:
    import simplegui
except ModuleNotFoundError:
    import simplequi 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
    elif key == simplegui.KEY_MAP['down']:
        ball_radius -= BALL_RADIUS_INC


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

3#

Complete the program template so that 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. Space bar templateSpace bar solutionSpace bar (Checker)

4#

Challenge: Complete the program template below 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. Ball radius 2 templateBall radius 2 solutionBall radius 2 (Checker)