This repository has been archived by the owner on May 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
engine.py
258 lines (219 loc) · 9.07 KB
/
engine.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
import json
import math
import world as wd
import random
import pygame
# import ipdb
import pprint
LOCAL = True
network_settings = json.load(open('network_settings.json'))
json_data = open('master_settings.json')
config = json.load(json_data)
BEZEL_SIZE = 120
GRAVITY_VELOCITY = 2
FPS = pygame.time.Clock()
X_FRICTION_CONSTANT = 2
EDGES = (
int(config['display_size'][0]) * (int(config['grid_space'][0]) + 1) +
(BEZEL_SIZE * int(config['grid_space'][0]) + 1),
int(config['display_size'][1]) * (int(config['grid_space'][1]) + 1) +
(BEZEL_SIZE * int(config['grid_space'][1]) + 1))
WRAP_EDGES = (2000, 2400)
pygame.font.init()
FONT = pygame.font.SysFont('Arial', 100, 100)
class Colors(object):
"""simple abstraction to have convenient color constants."""
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
LRED = (128, 0, 0)
GREEN = (0, 255, 0)
LGREEN = (0, 128, 0)
BLUE = (0, 0, 255)
LBLUE = (0, 0, 128)
AQUA = (0, 255, 255)
class Vector(object):
def __init__(self, x, y):
super(Vector, self).__init__()
self.x = x
self.y = y
def add(self, vector):
self.x += vector.x
self.y += vector.y
def subtract(self, vector):
self.x -= vector.x
self.y -= vector.y
def to_tuple(self):
return self.x, self.y
def copy(self):
return Vector(self.x, self.y)
def distance(self, vector2):
return math.sqrt((self.x - vector2.x) ** 2 + (self.y - vector2.y) ** 2)
def distance(rect1, rect2):
return math.sqrt((rect1.centerx - rect2.centerx) ** 2 + (rect1.centery - rect2.centery) ** 2)
def distance_cart(cart1, cart2):
return math.sqrt((cart1[0] - cart2[0]) ** 2 + (cart1[1] - cart2[1]) ** 2)
class Engine(object):
"""A game engine that handles managing physics and game related"""
def __init__(self):
super(Engine, self).__init__()
def parse_json(self, file):
json_data = open(file)
data = json.load(json_data)
return data
def loop_over_game_dict(self, game_objects, func, *args):
"""loop over nested (i.e game_objects[type] = list) game dictionary and apply function, with the game_obj as
the first argument, followed by the other arguments with the arguments to
all objects"""
for obj_type, obj_list in game_objects.items():
for game_obj in obj_list:
func(game_obj, *args)
def map_attribute_flat(self, game_objects, func_string, *args):
"""Maps the attribute (calls the attribute on each value) to list of GameObjects, with the
given arguments"""
for game_obj in game_objects:
func = getattr(game_obj, func_string)
func(*args)
def loop_over_game_dict_att(self, game_objects, func_string, *args):
"""Loops over a game dictionary and calls the passed in function on the game object.
The function must be an attribute of the game objects"""
for obj_type, obj_list in game_objects.items():
self.map_attribute_flat(obj_list, func_string, *args)
def slide_animation(self, game_obj, end_location):
return
def physics_simulation(self, objects, static_objects):
"""The worlds most bestest physics simulation. Updates objects with
there velocities and checks if there is an collision with the static_objects
objects.
:param objects: list of game objects that could be in motion
:type objects: list of objects with a pygame rect and velocity
:param static_objects: list of game objects that don't move. Things like Scenery
:type static_objects: list of objects with a pygame rect and velocity
"""
# simulate
# TODO: a neat (and possibly needed) optimization would be to track which objects are players
# and to create a near objects list that the player will check when doing interactions3
for game_object in objects:
# if isinstance(game_object, wd.Player):
# ipdb.set_trace()
skip = False
if not game_object.physics:
continue
for static_object in static_objects:
if isinstance(game_object, static_object):
skip = True
if skip:
continue
self.simulate_friction(game_object)
game_object.rect.x += game_object.velocity.x
for other_object in objects:
if game_object == other_object:
continue # don't do things with itself
if not other_object.collision: # don't interact with things out of the simulation
continue
if game_object.rect.colliderect(other_object.rect):
game_object.respond_to_collision(other_object, 'x')
game_object.velocity.y += GRAVITY_VELOCITY
game_object.rect.y += game_object.velocity.y
# Check to make sure the object didn't move off the screen
if game_object.rect.left < 0:
if WRAP_EDGES[0] < game_object.rect.y < WRAP_EDGES[1]:
if game_object.rect.right < 0:
game_object.rect.right = EDGES[0]
else:
game_object.rect.left = 0
elif game_object.rect.right > EDGES[0]:
if WRAP_EDGES[0] < game_object.rect.y < WRAP_EDGES[1]:
if game_object.rect.left > EDGES[0]:
game_object.rect.left = 0
else:
game_object.rect.right = EDGES[0]
if game_object.rect.top < 0:
game_object.rect.top = 0
elif game_object.rect.bottom > EDGES[1]:
game_object.rect.bottom = EDGES[1]
for other_object in objects:
if game_object == other_object:
continue # don't do things with itself
if not other_object.collision:
continue
if game_object.rect.colliderect(other_object.rect):
game_object.respond_to_collision(other_object, 'y')
def simulate_friction(self, game_object):
if game_object.velocity.x != 0:
# simulate some drag
if game_object.velocity.x > 0:
# traveling right
game_object.velocity.x -= X_FRICTION_CONSTANT
if game_object.velocity.x < 0:
# Can't friction backwards
game_object.velocity.x = 0
else:
game_object.velocity.x += X_FRICTION_CONSTANT
if game_object.velocity.x > 0:
# Can't friction backwards
game_object.velocity.x = 0
def load_animation(self, game_objects, background, window):
"""breaks the game objects into pieces and has them fly into their spots
:param game_objects: a list of game objects too apply the loading animation too
:type game_objects: list of GameObjects
:param background: the background used to fill the screen
:type background: pygame image
:param window: the window to draw the game_objects on
:type window: pygame.surface
"""
# TODO: Add some randomness
game_pieces = {}
for game_obj in game_objects:
game_pieces[game_obj] = self.split_sprite(game_obj, 2, 2)
# move every object on screen out
step_dict = {}
steps_total = 45
# step_overlap = 5
stage_dict = {}
stages = 4
for i in range(0, stages):
stage_dict[i] = {}
random.seed()
for obj, list_pieces in game_pieces.items():
step_dict[obj] = {}
for i, (rect, area) in enumerate(list_pieces):
start_pointx, start_pointy = random.randint(-500, 1200), random.randint(0, 500)
dx, dy = (rect.x - start_pointx, rect.y - start_pointy)
step_sizex, step_sizey = (dx / float(steps_total), dy / float(steps_total))
step_dict[obj][i] = []
for x in range(1, steps_total + 1):
step_dict[obj][i].append((start_pointx + step_sizex * x, start_pointy + step_sizey * x))
rect.x, rect.y = (start_pointx, start_pointy)
for i in range(steps_total):
# draw objects
for game_obj, inner_step_dict in step_dict.items():
for idx, (rect, area) in enumerate(game_pieces[game_obj]):
window.blit(background, (rect.x, rect.y), rect)
rect.x, rect.y = inner_step_dict[idx].pop(0) # grab the new place
window.blit(game_obj.sprite_sheets[game_obj.current_animation], rect, area=area)
pygame.display.flip()
FPS.tick(30)
# A final clear before starting
for game_obj, inner_step_dict in step_dict.items():
for idx, (rect, area) in enumerate(game_pieces[game_obj]):
window.blit(background, (rect.x, rect.y), rect)
def split_sprite(self, game_obj, des_width_peices, des_height_peices):
"""split the sprite into various pieces
:param game_obj: the game object that is going to be split
:type game_obj: GameObject
:param des_width_peices: the number of horizontal pieces
:type des_width_peices: int
:param des_height_peices: the number of vertical pieces
:type des_height_peices: int
:return split_peices: a list of rect area tuples
:rtype: list of (pygame.Rect, pygame.Rect)"""
width = int(math.ceil(game_obj.rect.width / des_width_peices))
height = int(math.ceil(game_obj.rect.height / des_height_peices))
split_peices = []
for x in range(0, game_obj.rect.width, width):
for y in range(0, game_obj.rect.height, height):
rect = pygame.Rect(game_obj.rect.x + x, game_obj.rect.y + y, width, height)
area = pygame.Rect(game_obj.current_frame.x + x, game_obj.current_frame.y + y, width, height)
split_peices.append((rect, area))
return split_peices