File: map.py

package info (click to toggle)
bouncy 0.6.20071104-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,924 kB
  • ctags: 914
  • sloc: python: 4,672; makefile: 2; sh: 2
file content (368 lines) | stat: -rw-r--r-- 12,460 bytes parent folder | download | duplicates (3)
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
import math, csv, sys, time, os
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *

import euclid, collide, objects, pyglyph, fonts
import rabbit, farmer, astar, ui, collide, textures

class excel_colon(csv.excel):
    delimiter = ':'
class Map(ui.UserInterface):
    farmer = None
    def __init__(self, viewport, filename):
        self.viewport = viewport
        self.grid = astar.AStarGrid()

        reader = csv.reader(open(filename), excel_colon)
        self.holes = []
        self.pieces = []
        for name, position, rotation in list(reader)[1:]:
            if name[0] == '#': continue
            position = map(float, position.split(','))
            rotation = float(rotation)

            if name == 'player':
                self.rabbit = rabbit.Rabbit(position, rotation)
            elif name == 'farmer':
                self.farmer = farmer.Farmer(position, rotation)
            else:
                elem = objects.map_elements[name](rotation, position)
                self.pieces.append(elem)
                self.grid.add(elem)

        # add the farmer so it owns its little slice of the universe
        if self.farmer is not None:
            self.grid.addFarmer(self.farmer)

        #print self.grid

    def animate(self, ts):
        pass

    def is_intersecting(self, hitbox):
        l = []
        if isinstance(hitbox, collide.Sphere) and hitbox.c.y < hitbox.r:
            l.append(self)
        elif isinstance(hitbox, collide.AABox) and hitbox.c.y < hitbox.dy/2:
            l.append(self)
        for piece in self.pieces:
            if (piece.hitbox is not None and
                    piece.hitbox.is_intersecting(hitbox)):
                l.append(piece.hitbox)
        return l

    def resolve_collision(self, hitbox):
        # don't fall through the ground
        if isinstance(hitbox, collide.Sphere):
            hitbox.c.y = hitbox.r
            obj.velocity.y = 0
        elif isinstance(hitbox, collide.AABox):
            hitbox.c.y = hitbox.dy/2
        return hitbox.c, euclid.Vector3(1, 0, 1)

    def find_food(self, other):
        c = other.c
        r = other.r
        l = []
        for piece in self.pieces:
            if not piece.is_food: continue
            distance = abs(other.c - piece.hitbox.c) - r - 1 # TODO: 2 is magic
            if distance < 0:
                l.append((distance, piece))
        if not l:
            return None
        l.sort()
        return l[0][1]

    def eat_food(self, food):
        i = self.pieces.index(food)
        next = food.next
        if next is None:
            del self.pieces[i]
        else:
            self.pieces[i] = next(food.rotation, food.position)

    def add_hole(self, position):
        self.holes.append(objects.Hole(0, position))

    def render(self, show_collide=False):
        if show_collide:
            s = float(self.grid.resolution)/2
            glDisable(GL_LIGHTING)
            for x, z in self.grid.m.keys():
                if self.grid.m[(x, z)] is self.grid.IMPASSABLE:
                    glColor(1, 0, 0, .5)
                else:
                    glColor(0, 1, 0, .5)
                glPushMatrix()
                glTranslate(x+s, 0, z+s)
                glBegin(GL_QUADS)
                glVertex3f(-s,0,-s)
                glVertex3f(-s,0,s)
                glVertex3f(s,0,s)
                glVertex3f(s,0,-s)
                glEnd()
                glPopMatrix()

            glColor(1, 1, 0, .5)
            glPushMatrix()
            x, z = self.grid.findClosest(self.rabbit.position.x,
                self.rabbit.position.z)
            glTranslate(x+s, 0, z+s)
            glBegin(GL_QUADS)
            glVertex3f(-s,1,-s)
            glVertex3f(-s,1,s)
            glVertex3f(s,1,s)
            glVertex3f(s,1,-s)
            glEnd()
            glPopMatrix()

            if self.farmer is not None:
                glColor(0, 1, 1, .5)
                glPushMatrix()
                x, z = self.grid.findClosest(self.farmer.position.x,
                    self.farmer.position.z)
                glTranslate(x+s, 0, z+s)
                glBegin(GL_QUADS)
                glVertex3f(-s,1,-s)
                glVertex3f(-s,1,s)
                glVertex3f(s,1,s)
                glVertex3f(s,1,-s)
                glEnd()
                glPopMatrix()
            glEnable(GL_LIGHTING)

        if 1:
            for piece in self.pieces:
                piece.render(show_collide)
            for hole in self.holes:
                hole.render(show_collide)

    def setup_scene(self, overhead=False, clear=(0.32, .48, .27)):
        # set up camera
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        width, height = self.viewport
        gluPerspective(60.0, width/float(height), 1, 100.0)
        p = self.rabbit.position
        if overhead:
            glRotate(90, 1, 0, 0)
            glTranslate(-p.x, -80, -p.z)
        else:
            glRotate(45, 1, 0, 0)
            glTranslate(-p.x, -25, -p.z-15)

        # now draw everything
        glMatrixMode(GL_MODELVIEW)
        clear += (0,)
        glClearColor(*clear)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        glEnable(GL_LIGHTING)
        glEnable(GL_DEPTH_TEST)

    def play(self, difficulty):
        if difficulty == 1:
            self.rabbit.hunger = {'lettuce': 8., 'carrot': 8., 'tomato': 8.}
            self.max_hunger = {'lettuce': 8., 'carrot': 8., 'tomato': 8.}
        elif difficulty == 2:
            self.rabbit.hunger = {'lettuce': 12., 'carrot': 12., 'tomato': 12.}
            self.max_hunger = {'lettuce': 12., 'carrot': 12., 'tomato': 12.}
        else:
            self.rabbit.hunger = {'lettuce': 16., 'carrot': 16., 'tomato': 16.}
            self.max_hunger = {'lettuce': 16., 'carrot': 16., 'tomato': 16.}
        if self.farmer is not None:
            self.farmer.setDifficult(difficulty)

        #glClearColor(0, 0, 0, 0)
        #glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        #self.ok_dialog('Get Ready!')

        rx, ry = (0,0)
        tx, ty = (0,0)
        zpos = 6
        rotate = move = False
        clock = pygame.time.Clock()
        k_right = k_left = k_up = k_down = 0
        move = dig = eat = False
        show_collide = False
        overhead = False
        paused = False
        jpos = [0,0]
        while 1:
            ts = clock.tick(60)
            turn = 0
            for e in pygame.event.get():
                if e.type == QUIT: sys.exit()
                down = e.type == KEYDOWN

                if e.type == JOYAXISMOTION:
                    jpos[e.axis] = e.value
                    k_right = k_left = k_up = k_down = 0
                elif e.type == JOYBUTTONDOWN:
                    if e.button == 1: dig = True
                    elif e.value == 2: eat = True
                    elif e.value == 3: overhead = not overhead
                    elif e.value == 4: paused = not paused
                elif e.type == JOYBUTTONUP:
                    if e.value == 1: dig = False
                    elif e.value == 2: eat = False

                if jpos[0] < -.5: k_left = True
                elif jpos[0] > .5: k_right = True
                if jpos[1] < -.5: k_up = True
                elif jpos[1] > .5: k_down = True

                if not hasattr(e, 'key'): continue
                if e.key == K_ESCAPE: return False
                
                if e.key == K_UP: k_up = down
                if e.key == K_RIGHT: k_right = down
                if e.key == K_LEFT: k_left = down
                if e.key == K_DOWN: k_down = down
                if e.key == K_d: dig = down
                if e.key == K_o and down: overhead = not overhead
                if e.key == K_p and down: paused = not paused
                if e.key == K_e: eat = down
                if down and e.key == K_h: show_collide = not show_collide

            if not paused:
                move = [euclid.Vector3(0, 0, 0)]
                if k_right: move.append(euclid.Vector3(1, 0, 0))
                if k_left: move.append(euclid.Vector3(-1, 0, 0))
                if k_up: move.append(euclid.Vector3(0, 0, -1))
                if k_down: move.append(euclid.Vector3(0, 0, 1))
                if move:
                    if len(move) > 1:
                        m = move[0]
                        for n in move[1:]: m += n
                        self.rabbit.move(m)
                    else:
                        self.rabbit.move(move[0])

                if dig: self.rabbit.dig()
                else: self.rabbit.stop_dig()
                if eat: self.rabbit.eat()
                else: self.rabbit.stop_eat()

                # ANIMATE
                self.animate(ts)
                try:
                    self.rabbit.animate(ts, self)
                except self.rabbit.RabbitFed:
                    return True
                if self.farmer is not None:
                    try:
                        self.farmer.animate(ts, self)
                    except self.farmer.RabbitCaught:
                        self.caught_anim()
                        return False

            # SETUP OGL
            self.setup_scene(overhead)

            # RENDER
            if objects.toon_program is not None:
                objects.shaders.glUseProgramObjectARB(objects.toon_program)
            self.render(show_collide)
            self.rabbit.render(show_collide)
            if self.farmer is not None:
                self.farmer.render(show_collide)
            if objects.toon_program is not None:
                objects.shaders.glUseProgramObjectARB(0)

            self.render_hud(show_collide and clock.get_fps())

            pygame.display.flip()

    def caught_anim(self):
        clock = pygame.time.Clock()
        timeout = 0

        pie = objects.Pie(-90, (0,0,0))
        exiting = False
        while 1:
            ts = clock.tick(60)
            turn = 0
            for e in pygame.event.get():
                if e.type == QUIT: sys.exit()
                if not hasattr(e, 'key'): continue
                if timeout > 1000:
                    exiting = True
                    timeout = 0

            if timeout > 1000 and exiting:
                return

            # RENDER
            if timeout < 1000 and not exiting:
                self.setup_scene()
                self.render()
                self.rabbit.render()
                self.farmer.render()
            else:
                self.rabbit.position = euclid.Point3(0, 0, 0)
                self.setup_scene(clear=(0,0,0))
                glLoadIdentity()
                p = self.rabbit.position
                pie.position = euclid.Vector3(p.x/3., 4, p.z/3.+3)
                glScalef(3, 3, 3)
                glRotate(-15, 1, 0, 0)
                pie.render()
                pie.rotation += 1

            timeout += ts
            if timeout < 1500 or exiting:
                self.fade('out', timeout, 750)
            else:
                self.fade('in', timeout-1500, 1000)

            pygame.display.flip()

    def render_hud(self, fps=None):
        # set up 2d mode
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        x, y = self.viewport
        glOrtho(0, x, 0, y, -20, 20)
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()

        glDisable(GL_LIGHTING)
        glDisable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        glColor4f(.5, .5, .5, .5)
        glBegin(GL_QUADS)
        glVertex3f(0, 0, 5)
        glVertex3f(404, 0, 5)
        glVertex3f(404, 138, 5)
        glVertex3f(0, 138, 5)
        glEnd()

        glPushMatrix()
        glColor4f(1, 1, 1, 1)
        glTranslate(10, 0, 10)
        glScalef(.5, .5, 0)
        for i, (name, value) in enumerate(self.rabbit.hunger.items()):
            target = self.max_hunger[name]
            ratio = value / float(target)
            textures.textures[name].render(1 - ratio)
            glTranslate(256, 0, 0)
        glPopMatrix()

        if fps:
            text = pyglyph.layout_text(str(int(fps)), font=fonts.mono20)
            pyglyph.begin()
            text.draw(pos=(0, y),
                anchor=(pyglyph.Align.top, pyglyph.Align.left))
            pyglyph.end()

        glDisable(GL_BLEND)
        glEnable(GL_LIGHTING)
        glEnable(GL_DEPTH_TEST)