-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjects.py
More file actions
369 lines (308 loc) · 14.6 KB
/
objects.py
File metadata and controls
369 lines (308 loc) · 14.6 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# (C) 2014 by Dominik Jain (djain@gmx.net)
import time
import pygame
from pygame import sprite
import numpy
import objects
import pickle
import threading
import aaline
import logging
log = logging.getLogger(__name__)
def deserialize(s, game): #解包?
d = pickle.loads(s)
return eval("%s(d, game)" % d["class"])
class Alignment(object):
TOP_LEFT, CENTRE, BOTTOM_LEFT = range(3)
class BaseObject(sprite.Sprite):
''' basic sprite object '''
def __init__(self, d, game, persistentMembers = None, isUserObject=False, layer=1, alignment=Alignment.TOP_LEFT):
self.isUserObject = isUserObject # can be overridden below if "isUserObject" is a persistent member
if persistentMembers is None: persistentMembers = [] #初始化
self.persistentMembers = persistentMembers
self.persistentMembers.extend(["rect", "pos", "id"]) #元素
sprite.Sprite.__init__(self)
self.alignment = alignment
self.layer = layer
self.id = time.time()
for member in self.persistentMembers: #
if member in d:
self.__dict__[member] = self._deserializeValue(member, d[member])
if not hasattr(self, "pos"): #具有属性
if hasattr(self, "rect"):
if self.alignment == Alignment.TOP_LEFT:
self.pos = self.rect.topleft
elif self.alignment == Alignment.CENTRE:
self.pos = self.rect.center
elif self.alignment == Alignment.BOTTOM_LEFT:
self.pos = self.rect.bottomleft
else:
raise Exception("unknown alignment: %s" % self.alignment)
else:
self.pos = (0, 0)
class MovementAnimationThread(threading.Thread): #运动动画线程
def __init__(self, obj, pos, duration):
threading.Thread.__init__(self) #初始化
self.obj = obj
self.pos = pos
self.duration = duration
self.animating = True
def run(self): #
startPos = self.obj.pos
translation = numpy.array(self.pos) - startPos #偏移
startTime = time.time() #计时器
while self.animating: #启动动画
passed = min(time.time() - startTime, self.duration) #计算帧
self.obj.pos = startPos + (passed / self.duration) * translation #显示
if passed == self.duration:
break
time.sleep(0.010)
def animateMovement(self, pos, duration): #开启动画线程
if hasattr(self, "movementAnimationThread"):
self.movementAnimationThread.animating = False
self.movementAnimationThread = BaseObject.MovementAnimationThread(self, pos, duration)
self.movementAnimationThread.start()
def update(self, game): #更新
# update the sprite's drawing position relative to the camera
coord = self.pos - game.camera.pos
if self.alignment == Alignment.TOP_LEFT:
self.rect.topleft = coord
elif self.alignment == Alignment.CENTRE:
self.rect.center = coord
elif self.alignment == Alignment.BOTTOM_LEFT:
self.rect.bottomleft = coord
def collide(self, group, doKill=False, collided=None):
return sprite.spritecollide(self, group, doKill, collided)
def kill(self):
#self.unbindAll()
sprite.Sprite.kill(self)
def offset(self, x, y): #偏移
self.pos += numpy.array([int(x),int(y)])
def toDict(self): #打包
d = {
"class": "%s.%s" % (self.__class__.__module__, self.__class__.__name__)
}
for member in self.persistentMembers:
if hasattr(self, member):
d[member] = self._serializeMember(member)
return d
def _serializeMember(self, name):
return self._serializeValue(name, self.__dict__[name])
def _deserializeValue(self, name, value): #打包解码
evalTag = "_EVAL_:"
if type(value) == str and value[:len(evalTag)] == evalTag:
value = eval(value[len(evalTag):])
return value
def _stringToEval(self, s):
return "_EVAL_:" + s
def _serializeValue(self, name, value): #打包编码
if name == "rect":
return self._stringToEval("pygame.Rect(%d, %d, %d, %d)" % (self.rect.left, self.rect.top, self.rect.width, self.rect.height))
if name == "pos":
return self._stringToEval("numpy.array([%s, %s])" % (str(self.pos[0]), str(self.pos[1])))
return value
def serialize(self):
return pickle.dumps(self.toDict())
def absRect(self): #绝对值矩阵
''' returns a rectangle reflecting the abolute extents of the object '''
return pygame.Rect(self.pos[0], self.pos[1], self.rect.width, self.rect.height)
class Rectangle(BaseObject): #画板矩形类
def __init__(self, d, game, **kwargs):
if not "isUserObject" in kwargs: kwargs["isUserObject"] = True
BaseObject.__init__(self, d, game, persistentMembers=["colour"], **kwargs)
self.setSize(self.rect.width, self.rect.height)
def setSize(self, width, height): #矩形形状属性
width, height = max(1, width), max(1, height)
alpha = len(self.colour) == 4
surface = pygame.Surface((width, height), flags=pygame.SRCALPHA if alpha else 0)
#直接使用surface作为矩形
surface.fill(self.colour)
self.image = surface.convert() if not alpha else surface.convert_alpha()
self.rect.width = width
self.rect.height = height
class Image(BaseObject): #图片(保存的临时文件?)类
def __init__(self, d, game, persistentMembers = None, **kwargs):
if persistentMembers is None: persistentMembers = []
BaseObject.__init__(self, d, game, persistentMembers=persistentMembers+["isUserObject", "image"], **kwargs)
def setSurface(self, surface, ppAlpha = False):
self.image = surface.convert() if not ppAlpha else surface.convert_alpha()
self.rect = self.image.get_rect()
def _serializeValue(self, name, value): #传输编码
if name == "image":
format = "RGBA"
s = pygame.image.tostring(self.image, format)
cs = s
print ("compression: %d -> %d" % (len(s), len(cs)))
return (cs, self.image.get_size(), format)
return super(Image, self)._serializeValue(name, value)
def _deserializeValue(self, name, value): #接受解码
if name == "image" and type(value) == tuple:
dim = value[1:][0]
if dim[0] == 0 or dim[1] == 0:
return pygame.Surface((10,10)).convert()
return pygame.image.frombuffer(value[0], *value[1:])
return super(Image, self)._deserializeValue(name, value)
class ImageFromResource(Image): #导入图片
def __init__(self, filename, game, ppAlpha=False, **kwargs):
Image.__init__(self, {}, game, **kwargs)
surface = pygame.image.load(filename)
self.setSurface(surface, ppAlpha=ppAlpha)
class ScribbleRenderer(object): #涂鸦渲染
def __init__(self, scribble):
self.antialiasing = False
self.margin = 2*scribble.lineWidth
self.colour = scribble.colour
self.lineWidth = scribble.lineWidth
surface = pygame.Surface((self.margin, self.margin), flags=pygame.SRCALPHA if self.antialiasing else 0) # TODO: aaline does not work with SRCALPHA!
self.backgroundColour = (255, 0, 255) if not self.antialiasing else (255, 255, 255, 0)
surface.fill(self.backgroundColour)
if not self.antialiasing:
surface.set_colorkey(self.backgroundColour)
self.surface = surface
self.isFirstPoint = True
self.obj = scribble
self.inputBuffer = []
def addPoint(self, x, y, draw=True): #绘图点
if self.isFirstPoint:
self.lineStartPos = numpy.array([x, y])
self.translateOrigin = numpy.array([-x, -y])
self.minX = self.maxX = x
self.minY = self.maxY = y
self.isFirstPoint = False
self.inputBuffer.append((x, y))
if draw:
self._processInputs()
def addPoints(self, points):
for point in points:
self.addPoint(*point, draw=False)
self._processInputs()
def _processInputs(self):
padLeft = 0
padTop = 0
oldWidth = self.surface.get_width()
oldHeight = self.surface.get_height()
newWidth = oldWidth
newHeight = oldHeight
# determine growth 框扩展?
for x, y in self.inputBuffer:
#print "\nminX=%d maxX=%d" % (self.minX, self.maxX)
#print "x=%d y=%d" % (x,y)
growRight = x - self.maxX if x > self.maxX else 0
growLeft = self.minX - x if x < self.minX else 0
growBottom = y - self.maxY if y > self.maxY else 0
growTop = self.minY - y if y < self.minY else 0
padLeft += growLeft
padTop += growTop
#print "grow: right=%d left=%d top=%d bottom=%d" % (growRight, growLeft, growTop, growBottom)
self.maxX = max(self.maxX, x)
self.maxY = max(self.maxY, y)
self.minX = min(self.minX, x)
self.minY = min(self.minY, y)
#print "new: minX=%d maxX=%d" % (self.minX, self.maxX)
newWidth += growLeft + growRight
newHeight += growBottom + growTop
# create new larger surface and copy old surface content
#创建新的大框
if newWidth > oldWidth or newHeight > oldHeight:
#print "newDim: (%d, %d)" % (newWidth, newHeight)
surface = pygame.Surface((newWidth, newHeight), pygame.SRCALPHA if self.antialiasing else 0)
surface.fill(self.backgroundColour)
if not self.antialiasing:
surface.set_colorkey(self.backgroundColour)
surface.blit(self.surface, (padLeft, padTop))
self.surface = surface
# translate pos
self.obj.offset(-padLeft, -padTop)
# draw new lines
for x, y in self.inputBuffer:
self._drawLineTo(x, y)
# apply new surface
self.obj.setSurface(self.surface, ppAlpha=self.antialiasing)
# reset input buffer
self.inputBuffer = []
def _drawLineTo(self, x, y):
# draw line
margin = self.margin
self.translateOrigin = -self.obj.pos + numpy.array([-margin, -margin])
#print "translateOrigin=%s" % str(self.translateOrigin)
marginTranslate = numpy.array([margin, margin])
pos1 = self.lineStartPos + self.translateOrigin + marginTranslate
pos2 = numpy.array([x, y]) + self.translateOrigin + marginTranslate
#print "drawing from %s to %s" % (str(pos1), str(pos2))
if not self.antialiasing:
pygame.draw.line(self.surface, self.colour, pos1, pos2, self.lineWidth)
else:
aaline.aaline(self.surface, self.colour, pos1, pos2, self.lineWidth)
self.lineStartPos = numpy.array([x, y])
def end(self):
self._processInputs()
class Scribble(Image): #画线高级封装?
''' an image-based scribble sprite '''
def __init__(self, d, game, startPoint=None, persistentMembers=None):
if startPoint is not None:
if "lineWidth" not in d: raise Exception("construction with startPoint requires lineWidth")
margin = 2 * d["lineWidth"]
d["rect"] = pygame.Rect(startPoint[0] - margin/2, startPoint[1] - margin/2, margin, margin)
if "pos" in d: del d["pos"] # will be set from rect
if persistentMembers is None: persistentMembers = []
Image.__init__(self, d, game, isUserObject=True, persistentMembers=persistentMembers+["lineWidth", "colour"])
def addPoints(self, points): #添加落点
if not hasattr(self, "scribbleRenderer"):
self.scribbleRenderer = ScribbleRenderer(self)
self.scribbleRenderer.addPoints(points)
def endDrawing(self): #停止绘画
self.scribbleRenderer.end()
del self.scribbleRenderer
class PointBasedScribble(Scribble): #画线再次封装?
''' a point-based scribble sprite, which, when persisted, is reconstructed from the individual points '''
def __init__(self, d, game, startPoint=None):
pos = None
if "pos" in d:
pos = self._deserializeValue("pos", d["pos"])
if startPoint is None:
if "points" in d and len(d["points"]) > 0:
startPoint = d["points"][0]
else:
raise Exception('construction requires either startPoint or non-empty d["points"]"')
else:
if "points" in d: raise Exception('cannot provide both startPoint and d["points"]')
Scribble.__init__(self, d, game, persistentMembers=["points"], startPoint=startPoint)
self.persistentMembers.remove("image")
self.persistentMembers.remove("rect")
if not hasattr(self, "points"):
self.points = []
else:
Scribble.addPoints(self, self.points)
if pos is not None:
self.pos = pos
def addPoints(self, points):
self.points.extend(points)
Scribble.addPoints(self, points)
#log.debug("relative points: %s", map(list, [numpy.array(p)-self.pos for p in self.points]))
class Text(Image): #文字
def __init__(self, d, game):
Image.__init__(self, d, game, persistentMembers=["text", "colour", "fontSize", "fontName"], isUserObject=True)
self.font = pygame.font.SysFont(self.fontName, self.fontSize)
self.setText(self.text)
def setText(self, text): #编辑文字
#font = pygame.freetype.get_default_font()
#self.image = font.render(self.text, fgcolor=self.colour, size=10)
self.text = text
lines = text.split("\n")
width = 0
height = 0
for l in lines:
w, h = self.font.size(l)
width = max(w, width)
height += h
surface = pygame.Surface((width, height))
surface.fill((255, 255, 255))
y = 0
for l in lines:
s = self.font.render(l, True, self.colour, (255,255,255))
surface.blit(s, (0, y))
y += s.get_height()
self.setSurface(surface)
def boundingRect(objects): #画图框边界?
r = objects[0].absRect()
return r.unionall([o.absRect() for o in objects[1:]])