Processing math: 100%

CPSC120A
Fundamentals of Computer Science I

Lab 14

Selection

Practice Problem 1

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.


Practice Problem 2

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.


Keyboard Control

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.

Details

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.

Example

  $ python3 keyboard_control.py

Hint

Challenge

Add additional code to your program which will allow for the ball to move in any arbitrary direction.

Bouncing Ball

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.

Details

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.

Example

  $ python3 bouncing_ball.py

Hint

Challenge

Right now, half of your circle will leave the window before it bounces. Alter your code so that it does not leave the screen.

Submission

Please show your source code and run your programs for the instructor or lab assistant. Only a programs that have perfect style and flawless functionality will be accepted as complete.