DS&A

Data Structures and Algorithms

Exercises: Geometry

Apr 232018

Before 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 and Circle 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

  1. Create a script called q1.py.
    • Create a list of 10 Vector objects with random x and y 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 and y coordinates, and create a Rectangle object.
    • Draw the minimum bounding rectangle before drawing the points. The result should look like this:
  2. 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:
      while True:
          mouse = get_mouse()
          shape = # ...
          if shape is None:
              print('No shape clicked')
          else:
              print(repr(shape))
      Test your script by clicking on the shapes and the window background.

Footnotes

  1. The graphics.py library was written by John Zelle, and released under the GNU General Public License.
  2. 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.

New comment

Your comment will not appear until a moderator approves it.

Atom

hosted on werp.site