Programming 1, Winter 2021-2
Week 11: Exercises

1. Files

Write a program whose command-line arguments are filenames. The program should print the contents of all the files to standard output in the order in which they appear on the command line. If any file does not exist, print ' == MISSING: <filename> == ' in its place. Use an exception handler to handle missing files.

2. Twice

Write a function twice(f) that takes a function f(x) of a single variable, and returns a function g(x) such that g(x) = f(f(x)).

3. Power of a Function

Write a function fpower(f, n) that takes a function f(x) of a single variable, and return a function g(x) such that g(x) = f(f(...(f(x)))), where f is applied n times.

4. Donuts

a) Write a program that initially displays a blank window. Each time the user clicks, a new donut should appear at the current mouse position. Use this image:

b) Modify the program so that each donut moves at a rate of 50 pixels/second in a random direction until it leaves the window.

5. Bouncing Ball

Write a program that displays a bouncing ball. Each time it hits the ground, it should rebound with a slightly smaller velocity, so that it eventually comes to a stop.

6. Solar System

Write a program that displays an animation of the inner Solar System, with the Sun at the center. Assume that planets' orbits are circular. Mark each planet's orbit with a gray circle.

Draw the orbits at a scale of 500,000 km/pixel. At that scale the planets would hardly be visible, so draw the planets at 1000x their actual size, and the sun at 25x its actual size. In your simulation, let one second represent 10 days of actual time.

body

diameter (km)

color (R,G,B)

dist from Sun (x 10km)

orbital period (days)

Sun

1,393,000

(254, 143, 54)

0

n/a

Mercury

4,879

(191, 144, 114)

57.9

88.0

Venus

12,104

(244, 190, 190)

108.2

224.7

Earth

12,756

(94, 192, 227)

149.6

365.2

Mars

3,933

(222, 70, 49)

227.9

687.0

7. Tic Tac Toe

Write a graphical program that lets two players play tic tac toe. A mouse click should place a mark (X or O) for the current player. If any player wins, highlight the winning squares. Use a model-view architecture.

8. Rotating Triangle

Write a program that displays an equilateral triangle at the center of the window. The user should be able to rotate the triangle by holding down the left or right arrow keys.

9. Spaceship

Extend the previous program to display a spaceship in the form of an elongated triangle. The arrow keys should rotate the ship, and the A key should thrust it forward. Draw a random starfield in the background.