-
Notifications
You must be signed in to change notification settings - Fork 0
/
decorator.py
190 lines (124 loc) · 3.1 KB
/
decorator.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
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
# -*- coding: utf-8 -*-
class Canvas( object ):
"""
Define a sample canvas for terminal.
"""
def __init__( self, width=15, height=5 ):
"""
Init a params.
"""
self.__data = []
self.__width = width
self.__height = height
self.__setup( width, height )
def __setup( self, width, height ):
"""
Create a data block.
"""
for hi in range( height ):
self.__data.append( [] )
for wi in range( width ):
self.__data[ hi ].append( " " )
def draw( self, content, x, y ):
"""
Draw content to data block.
"""
width = self.__width
for char in content:
if x >= width:
break
self.__data[y][x] = char
x = x + 1
def show( self ):
"""
Print to terminal.
"""
for hi in range( self.__height ):
print "".join( self.__data[ hi ] )
class View( object ):
"""
Define a sample view.
"""
def setY( self, y ):
"""
Set a position of y.
"""
self._y = y
def getY( self ):
"""
Get a position of y.
"""
return self._y
def setX( self, x ):
"""
Set a position of x.
"""
self._x = x
def getX( self ):
"""
Get a position of x.
"""
return self._x
def getWidth( self ):
"""
Get the view width.
"""
return 0
def drawTo( self, canvas, parent = None ):
"""
Draw something to canvas.
"""
pass
class ViewDecorator( object ):
"""
Decorator of View.
"""
def __init__( self, *views ):
self.__views = views
def __call__( self, drawTo ):
views = self.__views;
def draw_chain( base_view, canvas ):
drawTo( base_view, canvas )
for view in views:
view.drawTo( canvas, base_view )
return draw_chain
class Border( View ):
"""
Extend a View.
"""
def drawTo( self, canvas, parent = None ):
"""
Draw a border to canvas by parent position.
"""
if parent:
width = parent.getWidth()
x = parent.getX()
y = parent.getY()
canvas.draw( "[", x - 1 , y )
canvas.draw( "]", width + x , y )
class Text( View ):
"""
Extend a view.
"""
def __init__( self, content ):
"""
Set a text.
"""
self.__content = content
def getWidth( self ):
"""
Get a width of text.
"""
return len( self.__content )
@ViewDecorator( Border() )
def drawTo( self, canvas, parent = None ):
"""
Draw a text to canvas.
"""
canvas.draw( self.__content, self.getX(), self.getY() )
canvas = Canvas()
text = Text( "Sparrow" )
text.setX( 3 )
text.setY( 2 )
text.drawTo( canvas )
canvas.show()