/
levels.py
284 lines (227 loc) · 8.1 KB
/
levels.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
import Box2D as b2d
import objects
import math
import utils
import time
import random
from controls import Controls, CBInfo, TOGEvent, CTRL, ControlsCapsule
import time
import gravity_changers
import pickle
class ContactType:
add = 0
persist = 1
remove = 2
# Box2D contact listener
class ContactListener(b2d.b2ContactListener):
def __init__(self, level):
super(ContactListener, self).__init__()
self.level = level
def Add(self, point):
self.level.contactCallbacks(ContactType.add, point)
def Persist(self, point):
self.level.contactCallbacks(ContactType.persist, point)
def Remove(self, point):
self.level.contactCallbacks(ContactType.remove, point)
# global function scheduler
# maybe there's a better place for it then the module namespace
G_FS = utils.FunsctionScheduler()
class Level(object):
world = None
worldEndsAt = None
W = 180
H = 180
size = (W, H)
character = None
gorilla_hut = None
world_angle = None
original_gravity = b2d.b2Vec2(0, -30)
contactCallbackList = None
actors = {}
controls = None
actor_id_generator = (i for i in xrange(10**9))
score = None
toRemove = None
def increaseScore(self):
self.score+=1
def timeLeft(self):
return round(max(0,self.worldEndsAt - time.time()), 1)
def getCenter(self):
return b2d.b2Vec2(self.W, self.H)/2.
def getCameraPosition(self):
return self.getCenter()
def getOriginalVec(self, *args):
vec = b2d.b2Vec2(*args)
return utils.rotate(vec, self.world_angle.get())
def getOriginalHorAngle(self):
a = b2d.b2Vec2(0,1)
b = self.getOriginalVec(a)
return -utils.angle_between(a,b)
def changeGravityChanger(self, newChanger):
if self.world_angle: self.world_angle.controls.unsubscribe()
self.world_angle = newChanger
self.world_angle.createControls()
def __init__(self, settings):
self.toRemove = []
self.settings = settings
self.score = 0
self.worldEndsAt = time.time() + settings.time
self.contactCallbackList = {
ContactType.add: [],
ContactType.remove: [],
ContactType.persist: [],
}
self.subscribeToContacts(ContactType.add, self.clash)
self.changeGravityChanger(gravity_changers.ConstantGravity())
def addActor(self, actor):
actor.id = 0
while actor.id in self.actors.keys():
actor.id = self.actor_id_generator.next()
self.actors[actor.id] = actor
return actor.id
def removeActor(self, actor):
self.actors.pop(actor.id)
self.toRemove.append(actor)
# returns an arbitrary actor that contains the given point
def pickActor(self, pos):
aabb = b2d.b2AABB()
x,y = pos
eps = 1e-5
aabb.lowerBound = (x-eps, y-eps)
aabb.upperBound = (x+eps, y+eps)
num, shapes = self.world.Query(aabb, 10)
if num == 0: return
for shape in shapes:
actor = shape.GetBody().userData
if actor.isPointInside(pos): return actor
def pickClosestCandy(self, pos, radius):
aabb = b2d.b2AABB()
x,y = pos
aabb.lowerBound = (x-radius, y-radius)
aabb.upperBound = (x+radius, y+radius)
num, shapes = self.world.Query(aabb, 20)
if num == 0: return
res = None
res_dist = 10e20
for shape in shapes:
actor = shape.GetBody().userData
if not isinstance(actor, objects.Candy): continue
dist = (actor.body.position - pos).Length()
if res_dist > dist:
res = actor
res_dist = dist
return res
def createControls(self):
self.controls = ControlsCapsule()
def physicsStep_(self):
gravity = utils.rotate(self.original_gravity, self.world_angle.get())
self.world.SetGravity(gravity)
self.world.Step(
self.settings.time_step,
self.settings.vel_iters,
self.settings.pos_iters)
def updateWorld(self):
if self.timeLeft() <= 0:
return
G_FS.work()
self.world_angle.step()
self.physicsStep_()
#print self.world_angle.get()
for actor in self.toRemove:
actor.cleanUp()
del self.toRemove[:]
def subscribeToContacts(self, ctype, cb):
self.contactCallbackList[ctype].append(cb)
def contactCallbacks(self, ctype, point):
for cb in self.contactCallbackList[ctype]:
cb(point)
def constructFrame(self):
frame = [
objects.Box(
size = (self.W/2,1),
position = (self.W/2, 0),
static=True,
restitution = 0),
objects.Box(
size = (self.W/2,1),
position = (self.W/2, self.H),
static=True,
restitution = 0),
objects.Box(
size = (1,self.H/2),
position = (0, self.H/2),
static=True,
restitution = 0),
objects.Box(
size = (1,self.H/2),
position = (self.W, self.H/2),
static=True,
restitution = 0),
]
for x in frame:
x.create(self)
self.addActor(x)
def constructWorld(self):
doSleep = False
worldAABB=b2d.b2AABB()
worldAABB.lowerBound = (-20, -20)
worldAABB.upperBound = (self.size[0]+20, self.size[1]+20)
self.world = b2d.b2World(worldAABB, self.original_gravity, doSleep)
self.contactListener = ContactListener(self)
self.world.SetContactListener(self.contactListener)
def putStaticActor(self, actor, removeAfter = 0.5):
self.addActor(actor)
G_FS.addAction(
fun = lambda: self.removeActor(actor),
delay = removeAfter)
# displays "POW!" actor when the main character collides with an obstacle
def clash(self, point):
o1 = point.shape1.GetBody().userData
o2 = point.shape2.GetBody().userData
pos = point.position.copy()
if o1.clashWith(o2, pos): return
if o2.clashWith(o1, pos): return
if point.velocity.Length()<10: return
actor = random.choice((objects.Pow1, objects.Pow2))(pos)
self.putStaticActor(actor, 0.2)
# pickling
def loadPickledData(self, filename = 'pickle.data'):
print 'LOAD'
with open(filename, 'rb') as f:
self.actors = pickle.load(f)
for actor in self.actors.values():
print actor
actor.create(self)
if isinstance(actor, objects.Gorilla):
self.character = actor
if isinstance(actor, objects.GorillaHut):
self.gorilla_hut = actor
def dumpPickledData(self, filename = 'pickle.data'):
print 'DUMP'
with open(filename, 'w') as f:
# we don't want to pickle the whole b2 world
for actor in self.actors.values():
actor.destroy()
try:
pickle.dump(self.actors, f)
except Exception, s:
print 'Pickling failed: ', s
return
for actor in self.actors.values():
actor.create(self)
class PickledLevel(Level):
filename = None
def __init__(self, filename, *args, **kwargs):
super(PickledLevel, self).__init__(*args, **kwargs)
self.filename = filename
wa = gravity_changers.GravityChanger()
#wa = gravity_changers.ContinuousGravityChanger()
self.changeGravityChanger(wa)
def constructWorld(self):
super(PickledLevel, self).constructWorld()
self.loadPickledData(self.filename)
def createControls(self):
super(PickledLevel, self).createControls()
self.character.createControls()
def getCameraPosition(self):
return self.character.body.position