-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgameObjects.py
462 lines (392 loc) · 13.7 KB
/
gameObjects.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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
from config import *
import AI
import math_utils
from utils import *
class Animation(object):
# order of enum is counter-clockwise (right hand rule)
left = 0
down = 1
right = 2
up = 3
face_dict = {'left': left, 'down': down, 'right': right, 'up': up}
def __init__(self):
self.animationIndex = 0
self.face = 0
self.time_elapsed = 0.0
self.indices = {i: np.array([0]) for i in range(4) } # default is index 0 for all four faces
# params
self.passive = False
self.update_rate = 0.05
def register_indices(self, face, indices):
# face := Animation.face
# indices := list
self.indices[face] = np.array(indices)
def update(self, seconds, dx, dy):
if self.passive:
self.update_passive(seconds)
else:
self.update_active(seconds, dx, dy)
def update_passive(self, seconds):
# used for idle animation, which includes weapon animation
self.time_elapsed += seconds
if self.time_elapsed > self.update_rate:
self.time_elapsed -= self.update_rate
self.animationIndex += 1
self.animationIndex %= self.indices[self.face].shape[0]
def update_active(self, seconds, dx, dy):
# check if elapsed time surpasses update rate
self.time_elapsed += seconds
if self.time_elapsed > self.update_rate:
self.time_elapsed -= self.update_rate
# increment animation index for each update frame
if dx > 0:
if self.face != Animation.right: #face: 0-left, 1-down, 2-right, 3-up
self.face = Animation.right
self.animationIndex += 1
elif dx < 0:
if self.face!=Animation.left:
self.face=Animation.left
self.animationIndex += 1
elif dy > 0:
if self.face != Animation.down:
self.face = Animation.down
self.animationIndex += 1
elif dy < 0:
if self.face != Animation.up:
self.face = Animation.up
self.animationIndex += 1
elif dx == 0 and dy == 0:
self.animationIndex = 0
# self.animationIndex += 1
self.animationIndex %= self.indices[self.face].shape[0]
def getSpriteIndex(self):
idx = self.indices[self.face][self.animationIndex]
# if self.passive:
# print("sprite idx: {}".format(idx))
return idx
class StaticGameObject(object):
id = -1
def __init__(self, **kwargs):
GameObject.id += 1
self.id = GameObject.id
self.type = "static_object"
self.objectType = "" # for art purposes
#-------------- default values --------------
# hitbox
self.drawHitBox = False
self.x = 0.0
self.y = 0.0
self.dx = 0.0
self.dy = 0.0
self.dx_actual = 0.0
self.dy_actual = 0.0
self.width = 0.0
self.height = 0.0
self.heading = 0.0 # from 0 to 2pi
self.patch_rect = self.make_patch_rect()
self.pygame_rect = self.patch_rect.convert_to_pygame_rect()
self.pygame_screen_rect = self.patch_rect.convert_to_screen_rect([0, 0]).convert_to_pygame_rect()
# visuals
self.visible = False
self.has_sprite = False #False --> rect
self.rgb = (0, 200, 0)
self.drawn = False
self.spriteID = 0
self.animation = None
self.artWidth = 0.0
self.artHeight = 0.0
self.artXOffset = 0.0
self.artYOffset = 0.0
# instantiate from rect
if "rect" in kwargs:
rect = kwargs.pop("rect")
kwargs["x"] = rect.x
kwargs["y"] = rect.y
kwargs["width"] = rect.width
kwargs["height"] = rect.height
#------------------------------------------
# over-ride default values
self.__dict__.update(kwargs)
def setSpriteStatus(self, visible, has_sprite=False):
if visible:
self.visible = True
if has_sprite:
self.has_sprite = True
self.animation = Animation()
else:
self.visible = False
del self.animation; self.animation = None
def gen_art_frame(self):
""" generate the art-frame using the offsets
"""
pos = m2d.Vector([self.artXOffset, self.artYOffset])
orient = m2d.Orientation(0.0)
tf = m2d.Transform(pos, orient)
def getArtPosition_tiles(self):
""" get the art-frame in map-frame. Unit: tiles
ex:
artWidth = 1.5
width = 1.0
offset = 0.5
artX = x - 0.5
"""
artXOffset = self.artWidth - self.width
artYOffset = self.artHeight - self.height
artX = self.x - artXOffset
artY = self.y - artYOffset
return artX, artY
def getArtPosition_pixels(self):
artX, artY = self.getArtPosition_tiles()
pixelX = int(artX*pixelsPerTileWidth)
pixelY = int(artY*pixelsPerTileHeight)
return (pixelX, pixelY)
def update_heading(self, dy, dx):
self.heading = np.arctan2(dy, dx)
def reset_pos(self, new_pos):
self.x = new_pos[0]
self.y = new_pos[1]
def get_position(self):
return np.array([self.x, self.y])
position = property(get_position)
def get_center(self):
return np.array([self.x + 0.5 * self.width, self.y + 0.5 * self.height])
def get_center_tf(self):
pos = self.get_center()
tf = m2d.Transform(self.heading, pos)
return tf
def get_heading_orient(self):
return m2d.Orientation(self.heading)
def get_heading_unit_direction(self):
""" returns numpy array """
return (self.get_heading_orient() * m2d.Vector.e0).array
def get_reach_rect(self):
# the rect surrounding the game object that they can reach
lt = [self.x - self.reach, self.y - self.reach]
wh = [self.width + 2.0 * self.reach, self.height + 2.0 * self.reach]
return make_rect(lt, wh)
reach_rect = property(get_reach_rect)
def make_patch_rect(self):
lt = [self.x, self.y]
wh = [self.width, self.height]
return make_rect(lt, wh)
def update_rect(self):
self.patch_rect.x = self.x
self.patch_rect.y = self.y
self.patch_rect.width = self.width
self.patch_rect.height = self.height
def get_rect(self):
""" get pygame Rect of the object's footprint. i.e. the portion that can be collided with.
"""
#rect = pygame.Rect(lt, wh) # Rect(left, top, width, height) -> Rect
return self.patch_rect
def update_pygame_rect(self):
""" get pygame Rect of the object's footprint. i.e. the portion that can be collided with.
"""
#rect = pygame.Rect(lt, wh) # Rect(left, top, width, height) -> Rect
self.pygame_rect.x = self.x
self.pygame_rect.y = self.y
self.pygame_rect.width = self.width
self.pygame_rect.height = self.height
def update_pygame_screen(self, screen_location):
""" get pygame Rect of the object's footprint. i.e. the portion that can be collided with.
"""
self.pygame_screen_rect.x = (self.x - screen_location[0]) * pixel_factor[0]
self.pygame_screen_rect.y = (self.y - screen_location[1]) * pixel_factor[1]
self.pygame_screen_rect.width = self.width * pixel_factor[0]
self.pygame_screen_rect.height = self.height * pixel_factor[1]
def get_pygame_rect(self):
self.update_pygame_rect()
return self.pygame_rect
def get_rect_art(self):
""" get pygame Rect of the object's art. i.e. the portion that can be collided with.
"""
lt = self.getArtPosition_tiles()
wh = [self.artWidth, self.artHeight]
return make_rect(lt, wh)
rect = property(get_rect)
rect_art = property(get_rect_art)
def calc_pygame_rect(self):
self.pygame_rect = self.rect.convert_to_pygame_rect()
return self.pygame_rect
class GameObject(StaticGameObject):
# class for any objects found in the game,
# basically if it has a hitbox, it's a game object
id = -1
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.type = "game_object"
# physics
self.moveable = True # if the object can be moved
self.collideable = True # if the object can be collided with
self.can_transfer_momentum = True # if the object can transfer momentum to objects it interacts with
self.mass = 70.0
self.friction = 0.01
self.reach = 2.0 # tile reach for interactions
#------------------------------------------
# intelligence
self.AI = AI.Basic(self)
self.team_id = 0
self.callbacks = {}
#------------------------------------------
# over-ride default values
self.__dict__.update(kwargs)
self.old_x = self.x
self.old_y = self.y
def reset_pos(self, new_pos):
self.x = new_pos[0]
self.y = new_pos[1]
# save values
self.old_x = self.x
self.old_y = self.y
def update(self, seconds):
# update actual movement
self.dx_actual = self.x - self.old_x
self.dy_actual = self.y - self.old_y
# dead-band
if abs(self.dx_actual) < 1e-2: self.dx_actual = 0.0
if abs(self.dy_actual) < 1e-2: self.dy_actual = 0.0
# save values
self.old_x = self.x
self.old_y = self.y
if self.dx_actual != 0.0 or self.dy_actual != 0.0:
self.update_heading(self.dy_actual, self.dx_actual)
if self.has_sprite:
self.animation.update(seconds, self.dx_actual, self.dy_actual)
@property
def projectile_heading(self):
if self.objectType == "Player":
# take from mouse direction
mouse_pos = get_mouse_pos("tiles") + get_screen_location() # from utils
origin = self.get_center()
vec = mouse_pos - origin
dx, dy = vec
return np.arctan2(dy, dx)
else:
return self.heading
# # # @profile
def get_overlap_tiles(self):
""" get all tile indices which overlap in the form out = [[idx_x1, idx_y1], ..., [idx_xn, idx_yn]]
"""
rect = self.rect
xmin = int(np.floor(rect.left))
xmax = int(np.ceil(rect.right) + 1)
ymin = int(np.floor(rect.top))
ymax = int(np.ceil(rect.bottom) + 1)
# try:
# X, Y = np.mgrid[xmin:xmax:1, ymin:ymax:1]
# except:
# pdb.set_trace()
# indices = np.vstack([X.ravel(), Y.ravel()]).T
length = (xmax - xmin) * (ymax - ymin)
indices2 = np.zeros([length, 2], dtype=int)
# using loops
for Y in range(ymin, ymax):
for X in range(xmin, xmax):
x = X - xmin
y = Y - ymin
idx = (xmax - xmin) * (y) + x
indices2[idx][0] = X
indices2[idx][1] = Y
return indices2
def get_rect_total_movement(self):
""" get pygame Rect of the object between last position and this position
"""
# TODO: finish fcn
lt = [self.x, self.y]
wh = [self.width, self.height]
#rect = pygame.Rect(lt, wh) # Rect(left, top, width, height) -> Rect
return utils.make_rect(lt, wh)
def intersect(self, other, art=False):
""" intersect with other, other can be an object which contains rect, or a Patch directly
"""
if art and self.has_sprite:
if isinstance(other, PatchExt): out = self.rect_art.intersect(other)
else: out = self.rect_art.intersect(other.rect_art)
else:
if isinstance(other, PatchExt): out = self.rect.intersect(other)
else: out = self.rect.intersect(other.rect)
return out
def collide(self, other, art=False):
""" intersect with other, other can be an object which contains rect, or a Patch directly
"""
if art and self.has_sprite:
if isinstance(other, PatchExt): out = self.rect_art.collide(other)
else: out = self.rect_art.collide(other.rect_art)
else:
if isinstance(other, PatchExt): out = self.rect.collide(other)
else: out = self.rect.collide(other.rect)
# call callback
if out: self.collide_callback(other)
return out
def collide_callback(self, other, *args):
# function which gets called when the other object collides with this one
pass
def get_velocity(self):
out = np.array([self.dx_actual, self.dy_actual])
return out
velocity = property(get_velocity)
def get_velocity_mag(self):
vv = np.linalg.norm(self.velocity)
return vv
velocity_mag = property(get_velocity_mag)
def get_unit_velocity(self):
out = math_utils.divide_vector(np.array(self.velocity), self.velocity_mag)
return out
unit_velocity = property(get_unit_velocity)
def get_momentum(self):
out = self.mass * self.velocity_mag
return out
momentum = property(get_momentum)
def get_center_of_mass(self):
out = self.rect.center
return out
center_of_mass = property(get_center_of_mass)
def com_vector(self, other):
""" get vector from my center of mass to 'other's center of mass
"""
# final - initial == 'to' - 'from'
out = np.array(other.center_of_mass) - np.array(self.center_of_mass)
return out
def dist_to_other(self, other):
com_vector = self.com_vector(other)
dist = np.linalg.norm(com_vector)
return dist
class Portal(GameObject):
def __init__(self, source, source_id, target, target_id):
self.target = np.array(target) # center of cell
self.source_id = source_id
self.target_id = target_id
self.active = True
self.inter_world = False
self.active_cooldown = 1.0 # seconds
#
x = source[0] + 0.25 # make half-tile sized portal centered on tile
y = source[1] + 0.25 # make half-tile sized portal centered on tile
#
super().__init__(drawHitBox = False,
x = x,
y = y,
width = 0.5,
height = 0.5,
moveable = False,
rgb = ((10 + 20*source_id)%250, 0, 0)
)
def activate(self, go, portals):
# @param go: GameObject class object
if self.active:
if self.inter_world:
else:
go.reset_pos(self.target)
self.active_cooldowner()
# deactivate the target portal too
portals[self.target_id].active = False
portals[self.target_id].active_cooldowner()
def active_cooldowner(self):
""" spool up a thread """
self.active = False
daemon_timer(self.active_cooldown, self.reset_active)
def reset_active(self):
self.active = True
class HealthBar(StaticGameObject):
def __init__(self):
pass