-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshapes.py
More file actions
343 lines (271 loc) · 10.7 KB
/
shapes.py
File metadata and controls
343 lines (271 loc) · 10.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# This code requires Python 3 and tkinter (which is usually installed by default)
# This code will NOT work on trinket.io as the tkinter module is not supported
# Raspberry Pi Foundation 2020
# CC-BY-SA 4.0
try:
from tkinter import Tk, Canvas, BOTH
except ImportError:
raise Exception("tkinter did not import successfully - check you are running Python 3 and that tkinter is available.")
import random
class Paper():
# the tk object which will be used by the shapes
tk = None
def __init__(self, width=600, height=600):
"""
Create a Paper object which is required to draw shapes onto.
It is only possible to create 1 Paper object.
Args:
width (int): The width of the display. Defaults to 600.
height (int): The height of the display. Defaults to 600.
Returns:
Paper: A Paper object
"""
if Paper.tk is not None:
raise Exception("Error: Paper has already been created, there can be only one.")
try:
Paper.tk = Tk()
except ValueError:
raise Exception("Error: could not instantiate tkinter object")
# Set some attributes
Paper.tk.title("Drawing shapes")
Paper.tk.geometry(str(width)+"x"+str(height))
Paper.tk.paper_width = width
Paper.tk.paper_height = height
# Create a tkinter canvas object to draw on
Paper.tk.canvas = Canvas(Paper.tk)
Paper.tk.canvas.pack(fill=BOTH, expand=1)
def display(self):
"""
Displays the paper
"""
Paper.tk.mainloop()
class Shape():
# Constructor for Shape
def __init__(self, width=50, height=50, x=None, y=None, color="black"):
"""
Creates a generic 'shape' which contains properties common to all
shapes such as height, width, x y coordinates and colour.
Args:
width (int): The width of the shape. Defaults to 50.
height (int): The height of the shape. Defaults to 50.
x (int): The x position of the shape. If None, the x position will be the middle of the screen. Defaults to None.
y (int): The y position of the shape. If None, the y position will be the middle of the screen. Defaults to None.
color (string): The color of the shape. Defaults to "black"
"""
if Paper.tk is None:
raise Exception("A Paper object has not been created. There is nothing to draw on.")
# Set some attributes
self.height = height
self.width = width
self.color = color
# Put the shape in the centre if no xy coords were given
if x is None:
self.x = (Paper.tk.paper_width/2) - (self.width/2)
else:
self.x = x
if y is None:
self.y = (Paper.tk.paper_height/2) - (self.height/2)
else:
self.y = y
# This is an internal method not meant to be called by users
# (It has a _ before the method name to show this)
def _location(self):
"""
Internal method used by the class to get the location
of the shape. This shouldn't be called by users, hence why its
name begins with an underscore.
"""
x1 = self.x
y1 = self.y
x2 = self.x + self.width
y2 = self.y + self.height
return [x1, y1, x2, y2]
# Randomly generate what the shape looks like
def randomize(self, smallest=20, largest=200):
"""
Randomly generates width, height, position and colour for a shape. You can specify
the smallest and largest random size that will be generated. If not specified, the
generated shape will default to a random size between 20 and 200.
Args:
smallest (int): The smallest the shape can be. Defaults to 20
largest (int): The largest the the shape can be. Defaults to 200.
"""
self.width = random.randint(smallest, largest)
self.height = random.randint(smallest, largest)
self.x = random.randint(0, Paper.tk.paper_width-self.width)
self.y = random.randint(0, Paper.tk.paper_height-self.height)
self.color = random.choice(["red", "yellow", "blue", "green", "gray", "white", "black", "cyan", "pink", "purple"])
# Getters and setters for Shape attributes
def set_width(self, width):
"""
Sets the width of the shape.
Args:
width (int): The width of the shape
"""
self.width = width
def set_height(self,height):
"""
Sets the height of the shape.
Args:
height (int): The height of the shape.
"""
self.height = height
def set_x(self, x):
"""
Sets the x position of the shape
Args:
x (int): The x position for the shape.
"""
self.x = x
def set_y(self, y):
"""
Sets the y position of the shape
Args:
y (int): The y position for the shape.
"""
self.y = y
def set_color(self, color):
"""
Sets the colour of the shape
Args:
color (string): The color of the shape.
"""
self.color = color
def get_color(self):
"""
Returns the colour of the shape
Returns:
color (string): The color of the shape
"""
return self.color
# Rectangle class is a subclass of Shape
class Rectangle(Shape):
# This is how to draw a rectangle
def draw(self):
"""
Draws a rectangle on the canvas. The properties of the rectangle
can be set using the getter and setter methods in Shape
"""
x1, y1, x2, y2 = self._location()
# Draw the rectangle
Paper.tk.canvas.create_rectangle(x1, y1, x2, y2, fill=self.color)
class Oval(Shape):
def draw(self):
"""
Draws an oval on the canvas. The properties of the oval
can be set using the getter and setter methods in Shape
"""
x1, y1, x2, y2 = self._location()
# Draw the oval
Paper.tk.canvas.create_oval(x1, y1, x2, y2, fill=self.color)
class Triangle(Shape):
# Every constructor parameter has a default setting
# e.g. color defaults to "black" but you can override this
def __init__(self, x1=0, y1=0, x2=20, y2=0, x3=20, y3=20, color="black"):
"""
Overrides the Shape constructor because triangles require three
coordinate points to be drawn, unlike rectangles and ovals.
Args:
x1 (int): The x position of the coordinate 1. Defaults to 0.
y1 (int): The y position of the coordinate 1. Defaults to 0.
x2 (int): The x position of the coordinate 2. Defaults to 20.
y2 (int): The y position of the coordinate 2. Defaults to 0.
x3 (int): The x position of the coordinate 3. Defaults to 20.
y3 (int): The y position of the coordinate 3. Defaults to 20.
color (string): The color of the shape. Defaults to "black"
"""
# call the Shape constructor
super().__init__(color=color)
# Remove height and width attributes which make no sense for a triangle
# (triangles are drawn via 3 xy coordinates)
del self.height
del self.width
# Instead add three coordinate attributes
self.x = x1
self.y = y1
self.x2 = x2
self.y2 = y2
self.x3 = x3
self.y3 = y3
def _location(self):
"""
Internal method used by the class to get the location
of the triangle. This shouldn't be called by users, hence why its
name begins with an underscore.
"""
return [self.x, self.y, self.x2, self.y2, self.x3, self.y3]
def draw(self):
"""
Draws a triangle on the canvas. The properties of the triangle
can be set using the getter and setter methods in Shape
"""
x1, y1, x2, y2, x3, y3 = self._location()
# Draw a triangle
Paper.tk.canvas.create_polygon(x1, y1, x2, y2, x3, y3, fill=self.color)
def randomize(self):
"""
Randomly chooses the location of all 3 triangle points as well
as the colour of the triangle
"""
# Randomly choose all the points of the triangle
self.x = random.randint(0, Paper.tk.paper_width)
self.y = random.randint(0, Paper.tk.paper_height)
self.x2 = random.randint(0, Paper.tk.paper_width)
self.y2 = random.randint(0, Paper.tk.paper_height)
self.x3 = random.randint(0, Paper.tk.paper_width)
self.y3 = random.randint(0, Paper.tk.paper_height)
# Randomly choose a colour of this triangle
self.color = random.choice(["red", "yellow", "blue", "green", "gray", "white", "black", "cyan", "pink", "purple"])
def set_width(self, width):
"""
Sets the width of the shape.
Args:
width (int): The width of the shape
"""
self.width = width
def set_height(self,height):
"""
Sets the height of the shape.
Args:
height (int): The height of the shape.
"""
self.height = height
# Change the behaviour of set_width and set_height methods for a triangle
# because triangles are not drawn in the same way
def set_width(self, width):
"""
Overrides the setter method for width
Args:
width (int): The width of the shape
"""
raise Exception("Width cannot be defined for Triangle objects")
def set_height(self, height):
"""
Overrides the setter method for height
Args:
height (int): The height of the shape
"""
raise Exception("Height cannot be defined for Triangle objects")
# This if statement means
# "if you run this file (rather than importing it), run this demo script"
if __name__ == "__main__":
my_drawing = Paper()
# Random size and location triangle
tri = Triangle()
tri.randomize()
tri.draw()
# Specific size and location rectangle
rect = Rectangle(height=40, width=90, x=110, y=20, color="yellow")
rect.draw()
# Default oval
oval = Oval()
oval.draw()
# Oval with setters
oval2 = Oval()
oval2.set_height(200)
oval2.set_width(100)
oval2.set_color("fuchsia")
oval2.set_x(30)
oval2.set_y(90)
oval2.draw()
my_drawing.display()