Source

pygame / examples / aliens.py

ahvezda 99d32cc 


















































































































































































































































































































































































































  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
#! /usr/bin/env python


import whrandom, os.path, sys
import pygame, pygame.image
from pygame.locals import *
try:
    import pygame.mixer
    import pygame.music
    pygame.mixer.pre_init(11025)
except ImportError:
    pygame.mixer = pygame.music = None

#see if we can get some font lovin'
try: import pygame.font as font
except ImportError: font = None


#constants
FRAMES_PER_SEC = 45
PLAYER_SPEED   = 5
MAX_SHOTS      = 2
SHOT_SPEED     = 6
BOMB_SPEED     = 6
MAX_ALIENS     = 30
ALIEN_SPEED    = 6
ALIEN_ODDS     = 36
ALIEN_RELOAD   = 12
EXPLODE_TIME   = 40
MAX_EXPLOSIONS = 4
SCREENRECT     = rect(0, 0, 640, 480)
ANIMCYCLE      = 18
PLODECYCLE     = 7
BULLET_OFFSET  = 11
BOUNCEWIDTH    = PLAYER_SPEED * 4
DIFFICULTY     = 14
BOMB_ODDS      = 150
DANGER         = 10
SORRYSCORE     = 20
GOODSCORE      = 60

#some globals for friendly access
dirtyrects = [] # list of update_rects
next_tick = 0   # used for timing
class Img: pass # container for images
class Snd: pass # container for sounds




#first, we define some utility functions

class dummysound:
    def play(self): pass

    
def load_image(file, transparent):
    "loads an image, prepares it for play"
    file = os.path.join('data', file)
    try:
        surface = pygame.image.load(file)
    except pygame.error:
        raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
    if transparent:
        corner = surface.get_at((0, 0))
        surface.set_colorkey(corner, RLEACCEL)
    return surface.convert()



def load_sound(file):
    if not pygame.mixer: return dummysound()
    file = os.path.join('data', file)
    try:
        sound = pygame.mixer.load(file)
        return sound
    except pygame.error:
        print 'Warning, unable to load,', file
    return dummysound()
    



def wait_frame():
    "wait for the correct fps time to expire"
    global next_tick
    this_tick = pygame.time.get_ticks()
    if this_tick < next_tick:
        pygame.time.delay(next_tick - this_tick)
    next_tick = this_tick + (1000/FRAMES_PER_SEC)



# The logic for all the different sprite types

class Actor:
    "An enhanced sort of sprite class"
    def __init__(self, image):
        self.image = image
        self.rect = rect((0, 0), image.get_size())
        self.clearrect = self.rect
        
    def update(self):
        "update the sprite state for this frame"
        pass
    
    def draw(self, screen):
        "draws the sprite into the screen"
        r = screen.blit(self.image, self.rect.topleft)
        dirtyrects.append(r.union(self.clearrect))
        
    def erase(self, screen, background):
        "gets the sprite off of the screen"
        pos = self.rect.topleft
        r = screen.blit(background, pos, pos, self.rect.size)
        self.clearrect = r


class Player(Actor):
    "Cheer for our hero"
    def __init__(self):
        Actor.__init__(self, Img.player[0])
        self.alive = 1
        self.reloading = 0
        self.rect.centerx = SCREENRECT.centerx
        self.rect.bottom = SCREENRECT.bottom - 1
        self.origtop = self.rect.top

    def move(self, direction):
        self.rect = self.rect.move(direction*PLAYER_SPEED, 0).clamp(SCREENRECT)
        if direction < 0:
            self.image = Img.player[0]
        elif direction > 0:
            self.image = Img.player[1]
        self.rect.top = self.origtop - (self.rect.left/BOUNCEWIDTH%2)


class Alien(Actor):
    "Destroy him or suffer"
    def __init__(self):
        Actor.__init__(self, Img.alien[0])
        self.facing = whrandom.choice((-1,1)) * ALIEN_SPEED
        self.frame = 0
        if self.facing < 0:
            self.rect.right = SCREENRECT.right
            
    def update(self):
        global SCREENRECT
        self.rect[0] += self.facing
        if not SCREENRECT.contains(self.rect):
            self.facing *= -1;
            self.rect.top = self.rect.bottom + 1
            self.rect = self.rect.clamp(SCREENRECT)
        self.frame += 1
        self.image = Img.alien[self.frame/ANIMCYCLE%3]


class Explosion(Actor):
    "Beware the fury"
    def __init__(self, actor, longer=0):
        Snd.explosion.play()
        Actor.__init__(self, Img.explosion[0])
        self.life = EXPLODE_TIME
        self.rect.center = actor.rect.center
        if longer:
            self.life *= 2
        
    def update(self):
        self.life -= 1
        self.image = Img.explosion[self.life/PLODECYCLE%2]


class Shot(Actor):
    "The big payload"
    def __init__(self, player):
        Snd.shot.play()
        Actor.__init__(self, Img.shot)
        self.rect.centerx = player.rect.centerx
        self.rect.top = player.rect.top - 10
        if player.image is Img.player[0]:
            self.rect.left += BULLET_OFFSET
        elif player.image is Img.player[1]:
            self.rect.left -= BULLET_OFFSET

    def update(self):
        self.rect = self.rect.move(0, -SHOT_SPEED)
        
class Bomb(Actor):
    "The big payload"
    def __init__(self, alien):
        Actor.__init__(self, Img.bomb)
        self.rect.centerx = alien.rect.centerx
        self.rect.bottom = alien.rect.bottom + 5

    def update(self):
        self.rect = self.rect.move(0, BOMB_SPEED)

class Danger(Actor):
    "Here comes trouble"
    def __init__(self):
        Actor.__init__(self, Img.danger)
        self.life = 1
        self.tick = 0
        self.rect.center = SCREENRECT.center[0]-30, 30
        self.startleft = self.rect.left
        
    def update(self):
        self.tick += 1
        self.rect.left = self.startleft + (self.tick/25%2)*60


def main(winstyle = 0):
    "Run me for adrenaline"
    global dirtyrects

    # Initialize SDL components
    pygame.init()
    screen = pygame.display.set_mode(SCREENRECT.size, winstyle)

    # Load the Resources
    Img.background = load_image('background.gif', 0)
    Img.shot = load_image('shot.gif', 1)
    Img.bomb = load_image('bomb.gif', 1)
    Img.danger = load_image('danger.gif', 1)
    Img.alien = load_image('alien1.gif', 1), \
                load_image('alien2.gif', 1), \
                load_image('alien3.gif', 1)
    Img.player = load_image('player1.gif', 1), \
                 load_image('player2.gif', 1)
    Img.explosion = load_image('explosion1.gif', 1), \
                    load_image('explosion2.gif', 1)
    Img.explosion[0].set_alpha(128, RLEACCEL)
    Img.explosion[1].set_alpha(128, RLEACCEL)
    Img.danger.set_alpha(128, RLEACCEL)

    Snd.explosion = load_sound('boom.wav')
    Snd.shot = load_sound('car_door.wav')

    # Create the background
    background = pygame.surface(SCREENRECT.size)
    for x in range(0, SCREENRECT.width, Img.background.get_size()[0]):
        background.blit(Img.background, (x, 0))
    screen.blit(background, (0,0))
    pygame.display.flip()
    pygame.mouse.set_visible(0)

    # Initialize Game Actors
    player = Player()
    aliens = [Alien()]
    shots = []
    bombs = []
    explosions = []
    misc = []
    alienreload = ALIEN_RELOAD
    difficulty = DIFFICULTY
    bomb_odds = BOMB_ODDS
    kills = 0

    # Soundtrack
    if pygame.music:
        music = os.path.join('data', 'house_lo.wav')
        pygame.music.load(music)
        pygame.music.play(-1)

    # Main loop
    while player.alive or explosions:
        wait_frame()

        # Gather Events
        pygame.event.pump()
        keystate = pygame.key.get_pressed()
        if keystate[K_ESCAPE] or pygame.event.peek(QUIT):
            break

        if difficulty:
            difficulty -= 1
        else:
            difficulty = DIFFICULTY
            if bomb_odds > DANGER:
                bomb_odds -= 1
                if bomb_odds == DANGER:
                    misc.append(Danger())

        # Clear screen and update actors
        for actor in [player] + aliens + shots + bombs + explosions + misc:
            actor.erase(screen, background)
            actor.update()
        
        # Clean Dead Explosions and Bullets
        for e in explosions:
            if e.life <= 0:
                dirtyrects.append(e.clearrect)
                explosions.remove(e)
        for s in shots:
            if s.rect.top <= 0:
                dirtyrects.append(s.clearrect)
                shots.remove(s)
        for b in bombs:
            if b.rect.bottom >= 470:
                if player.alive:
                    explosions.append(Explosion(b))
                dirtyrects.append(b.clearrect)
                bombs.remove(b)

        # Move the player
        if player.alive:
            direction = keystate[K_RIGHT] - keystate[K_LEFT]
            player.move(direction)

        # Create new shots
            if not player.reloading and keystate[K_SPACE] and len(shots) < MAX_SHOTS:
                shots.append(Shot(player))
            player.reloading = keystate[K_SPACE]

        # Create new alien
        if alienreload:
            alienreload -= 1
        elif player.alive and not int(whrandom.random() * ALIEN_ODDS):
            aliens.append(Alien())
            alienreload = ALIEN_RELOAD

        # Drop bombs
        if player.alive and aliens and not int(whrandom.random() * bomb_odds):
            bombs.append(Bomb(aliens[-1]))

        # Detect collisions
        alienrects = [a.rect for a in aliens]
        hit = player.rect.collidelist(alienrects)
        if hit != -1:
            alien = aliens[hit]
            explosions.append(Explosion(alien))
            explosions.append(Explosion(player, 1))
            dirtyrects.append(alien.clearrect)
            aliens.remove(alien)
            kills += 1
            player.alive = 0
        for shot in shots:
            hit = shot.rect.collidelist(alienrects)
            if hit != -1:
                alien = aliens[hit]
                explosions.append(Explosion(alien))
                dirtyrects.append(shot.clearrect)
                dirtyrects.append(alien.clearrect)
                shots.remove(shot)
                aliens.remove(alien)
                kills += 1
                break
        bombrects = [b.rect for b in bombs]
        hit = player.rect.collidelist(bombrects)
        if hit != -1:
            bomb = bombs[hit]
            explosions.append(Explosion(bomb))
            explosions.append(Explosion(player, 1))
            dirtyrects.append(bomb.clearrect)
            bombs.remove(bomb)
            player.alive = 0

        #prune the explosion list
        diff = len(explosions) - MAX_EXPLOSIONS
        if diff > 0:
            for x in range(diff):
                dirtyrects.append(explosions[x].clearrect)
            explosions = explosions[diff:]

        # Draw everybody
        for actor in [player] + bombs + aliens + shots + explosions + misc:
            actor.draw(screen)

        pygame.display.update(dirtyrects)
        dirtyrects = []

    if pygame.music:
        pygame.music.fadeout(1200)

    #attempt to show game over (if font installed)
    if font:
        fontname = os.path.join('data', 'billbrdi.ttf')
        f = font.font(fontname, 100)
        text = f.render('Game Over', 1, (200, 200, 200))
        textrect = rect((0, 0), text.get_size())
        textrect.center = SCREENRECT.center
        screen.blit(text, textrect.topleft)
        pygame.display.flip()

    #wait a beat
    if pygame.music:
        while pygame.music.get_busy():
            pygame.time.delay(200)
    else:
        pygame.time.delay(800)


    #scoreboard
    print 'Total Kills =', kills
    if kills <= SORRYSCORE: print 'Sorry!'
    elif kills >= GOODSCORE: print 'Excellent!'
    elif kills >= GOODSCORE-12: print 'Almost Excellent!'

    

#if python says run, let's run!
if __name__ == '__main__':
    main()
    
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.