As usual, create a directory to hold today's files. All programs that you write today should be stored in this directory.
$ cd ~/cs120/labs $ mkdir lab14 $ cd lab14
Write the function minimum(number_1, number_2)
that
returns the minimum of the two parameters, number_1
and number_2
. The function should not use the
built-in min
function.
Write the function clamp(number, minimum, maximum)
that
returns the result of clamping the specified number into the range
\([minimum, maximum]\). That is, if number
is below
minimum
, it returns minimum
,
if number
is above
maximum
, it returns maximum
, and otherwise
it returns number
. The function should not use the
built-in functions min
and max
.
One of the benefits of conditional statements is the ability to
change what code executes based on how the user reacts. Using the
graphics module, you can use the key_down()
function to
tell which key on the keyboard the user has pressed. Allowing the
user the change how the program behaves is the first step to creating
games within Python.
Download the graphics.py module, and store it in your directory for today's lab. Create a new file called keyboard_control.py, which will create a graphics window. Refer to the lecture today to setup a window for the graphics module.
The rest of your program should allow the user to press the Left and Right arrow keys on the keyboard to move a drawn circle left and right on the string.
$ python3 keyboard_control.py
key_pressed
function returns a boolean value depending on whether a key is
currently being pressed.
key_pressed
function has one parameter, a
string, that represents a keyboard key. The strings for left
and right are "Left" and "Right" respectively.
Add additional code to your program which will allow for the ball to move in any arbitrary direction.
With for loops and conditionals, we can now create complex looking behaviors. One such program, which you have likely seen on every DVD player since the 1990's, is a logo which continually bounces around the string. Today, using the graphics module and conditional statements, you will replicate a very simple form of this screen saver.
Create a file called bouncing_ball.py. In this file, you should draw a circle in the center of the graphics window. You should animate the circle moving towards the right edge of the screen. Once it reaches the right edge of the screen, the circle should "bounce" and move towards the left edge of the screen. This should continue until the end of your animation loop.
$ python3 bouncing_ball.py
Right now, half of your circle will leave the window before it bounces. Alter your code so that it does not leave the screen.