Exercises: Geometry
Apr 232018Before attempting these exercises, you should read the posts on points and vectors, simple shapes and polygons.
You will need to download the following files:
- geometry.py — includes the
Vector
,Rectangle
andCircle
classes defined previously. - graphics.py — a simple graphics library for drawing points and shapes.(1)
You should read the code of the geometry.py library carefully, to understand what functions, classes and methods you can make use of. It is not necessary to read the graphics.py library.
To make use of these libraries, place them in the same directory as your Python scripts, which must begin with the line from geometry import *
.
This will open a window in which points and shapes can be drawn.
The window’s dimensions are given by window.width
and window.height
.
Run your scripts in IDLE’s interactive mode, so that the window stays open.(2)
Exercises
- Create a script called
q1.py
.- Create a list of 10
Vector
objects with randomx
andy
coordinates. Use a loop to draw the vectors as points. - Find the minimum bounding rectangle of the list of vectors.
You should use the “best so far” plan to find the minimum and maximum
x
andy
coordinates, and create aRectangle
object. - Draw the minimum bounding rectangle before drawing the points.
The result should look like this:
- Create a list of 10
- Create another script called
q2.py
.- Create a list of shapes, and use a loop to draw the image below:
- Using a linear search, write a function to find which shape in this list contains a given point.
If no shape contains the point, your function should return
None
. - Complete the following code using your search function to find which shape is clicked on:
Test your script by clicking on the shapes and the window background.while True: mouse = get_mouse() shape = # ... if shape is None: print('No shape clicked') else: print(repr(shape))
Footnotes
- The graphics.py library was written by John Zelle, and released under the GNU General Public License.
- If you are not using IDLE, the window will close when your program terminates.
Write
get_mouse()
at the end of your script to wait for a mouse click before terminating.
There are no published comments.