-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_object_oriented_example.py
87 lines (68 loc) · 2.31 KB
/
python_object_oriented_example.py
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
# Add an selection method for Tile class
#################################################
# Student adds code where appropriate
import simplegui
# define globals
TILE_WIDTH = 50
TILE_HEIGHT = 100
# definition of a Tile class
class Tile:
# definition of intializer
def __init__(self, num, exp, loc):
self.number = num
self.exposed = exp
self.location = loc
# definition of getter for number
def get_number(self):
return self.number
# check whether tile is exposed
def is_exposed(self):
return self.exposed
# expose the tile
def expose_tile(self):
self.exposed = True
# hide the tile
def hide_tile(self):
self.exposed = False
# string method for tiles
def __str__(self):
return "Number is " + str(self.number) + ", exposed is " + str(self.exposed)
# draw method for tiles
def draw_tile(self, canvas):
loc = self.location
if self.exposed:
text_location = [loc[0] + 0.2 * TILE_WIDTH, loc[1] - 0.3 * TILE_HEIGHT]
canvas.draw_text(str(self.number), text_location, TILE_WIDTH, "White")
else:
tile_corners = (loc, [loc[0] + TILE_WIDTH, loc[1]], [loc[0] + TILE_WIDTH, loc[1] - TILE_HEIGHT], [loc[0], loc[1] - TILE_HEIGHT])
canvas.draw_polygon(tile_corners, 1, "Red", "Green")
# selection method for tiles
def is_selected(self, pos):
position = list(pos)
index = pos[0] / TILE_WIDTH
print index
if index >= 1:
return True
if index < 1:
return True
# define event handlers
def mouseclick(pos):
if tile1.is_selected(pos):
tile1.hide_tile()
if tile2.is_selected(pos):
tile2.expose_tile()
# draw handler
def draw(canvas):
tile1.draw_tile(canvas)
tile2.draw_tile(canvas)
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 2 * TILE_WIDTH, TILE_HEIGHT)
frame.set_draw_handler(draw)
frame.set_mouseclick_handler(mouseclick)
# create two tiles
tile1 = Tile(3, True, [0, TILE_HEIGHT])
tile2 = Tile(5, False, [TILE_WIDTH, TILE_HEIGHT])
# get things rolling
frame.start()
###################################################
# Clicking on tile should flip them once