Source

pyroids / entity.py

Full commit
  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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#import os, sys
import pygame
import random
import effect
import settings
from pygame.locals import *
from vector import *

if not pygame.font: print 'Warning, fonts disabled'
if not pygame.mixer: print 'Warning, sound disabled' 

renderTarget = None   
random.seed() 
pygame.mixer.init()
deltaTime = 0    # this is used so we know how much we should update every update

# font
font = None
#def initFont():
#    global font
#    font = pygame.font.Font("freesansbold.ttf", 14)  

def loadSound(path):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or path=="" or path=="None":
        return NoneSound()
    try:
        sound = pygame.mixer.Sound(path)
    except pygame.error, message:
        print 'Cannot load sound:', path
        raise SystemExit, message
    return sound

def loadImage(path):
    try:
        image = pygame.image.load(path)
    except pygame.error, message:
        print 'Cannot load image:', path
        raise SystemExit, message
    image = image.convert()
    image.set_colorkey((255,0,255), RLEACCEL)
    return image

scaleAsteroidImages = True # if this is true the program loads one image and scales the other from that 
def setupImages():
    Ship.originalImage = loadImage(settings.dict["ship_image"])
    
    bs = settings.dict["bullet_image_size"].split(",")
    bc = settings.dict["bullet_image_color"].split(",")
    if not len(bs) == 2:
        raise SystemExit, "bullet_image_size option bad: "+bs
    if not len(bc) == 3:
        raise SystemExit, "bullet_image_color option bad: "+bc
    Bullet.originalImage = pygame.Surface((int(bs[0]),int(bs[1])))
    Bullet.originalImage.fill((int(bc[0]),int(bc[1]),int(bc[2])))
    Bullet.originalImage.set_colorkey((255,0,255))

#    Bullet.originalImage = loadImage("bullet.bmp")

    if scaleAsteroidImages:
        size = 128
        originalImage = loadImage(settings.dict["asteroid_image"])
        for i in range(4):
            Asteroid.mipmapImages[size] = pygame.transform.scale(originalImage, (size,size))
            size /= 2
#    else:
#        Asteroid.mipmapImages[16] = loadImage("asteroid16.bmp")
#        Asteroid.mipmapImages[32] = loadImage("asteroid32.bmp")
#        Asteroid.mipmapImages[64] = loadImage("asteroid64.bmp")
#        Asteroid.mipmapImages[128] = loadImage("asteroid128.bmp")

    Bonus.originalImage = loadImage(settings.dict["bonus_image"])
        
def setupSounds():
    Bullet.sound = loadSound(settings.dict["bullet_sound"])
    Ship.deathSound = loadSound(settings.dict["ship_sound_death"])
    Ship.bornSound = loadSound(settings.dict["ship_sound_born"])
    Engine.sound = loadSound(settings.dict["engineflame_sound"])
    Asteroid.deathSound = loadSound(settings.dict["asteroid_sound_death"])
    Bonus.deathSound = loadSound(settings.dict["bonus_sound_death"])
    Bonus.bornSound = loadSound(settings.dict["bonus_sound_born"])
    Bonus.collectSound = loadSound(settings.dict["bonus_sound_collect"])
    
def setupConstants():
    Engine.flameDistance = float(settings.dict["engineflame_distance"])
    Engine.flameInterval = float(settings.dict["engineflame_interval"])
    Engine.flameExpandSpeed = float(settings.dict["engineflame_expandespeed"])

def randomPoint():
    """ returns vector class that contains the coords to a randem position within renderTarget """
    return vector(random.randint(0,renderTarget.get_rect().width),random.randint(0,renderTarget.get_rect().height))

class BaseEntity():
    def __init__(self):
        self.position = vector(0.0,1.0)    # where we are
        self.direction = vector(0.0,0.0)    # where were travilling
        self.orientation = vector(0.0,1.0)    # where were facing
        self.angle = 0
        self.image = None
        self.boundries = renderTarget.get_rect()
        
    def rotate(self, degrees):
        """ changes self.angle according to degrees then
            rotates into place accordingly """
        self.angle += degrees
        
        # to prevent overflow
        if self.angle > 360:
            self.angle -= 360
        elif self.angle < 0:
            self.angle += 360
        
        # rotate the image accordingly
        self.image = pygame.transform.rotate(self.originalImage, -(self.angle+90))
        
        # updates the direction
        self.orientation.x = math.cos(self.angle/180.0*math.pi)
        self.orientation.y = math.sin(self.angle/180.0*math.pi)
        self.orientation.normalise()
            
    def move(self):
        """ moves forward in its direction according to speed """
        #print self.position,self.direction,self.speed
        self.position += (self.direction*deltaTime)
        
    def engineBurst(self, powerFactor=1):
        """ adds orientation to direction to get movement """
        self.direction += (self.orientation*self.acceleration*deltaTime*powerFactor)
        
    def update(self):
        self.wrapMovement()
        #self.updateRect()
        
    def wrapMovement(self):
        """ wraps the movement (if the ent exits on one side it reappears on the other side """
#        self.boundries = renderTarget.get_rect()
        if self.position.x > self.boundries.right:
            self.position.x -= self.boundries.right
        elif self.position.x < 0:
            self.position.x += self.boundries.right
        if self.position.y > self.boundries.bottom:
            self.position.y -= self.boundries.bottom
        elif self.position.y < 0:
            self.position.y += self.boundries.bottom
               
    def render(self):
        """ renders self.image centered on self.position """        
        # draw the new image
        self.image.get_rect().center = self.originalImage.get_rect().center
        renderTarget.blit(self.image, (self.position.x - self.image.get_rect().centerx, self.position.y - self.image.get_rect().centery))
        
    def sphereCollision(self, ent, offset = 1.0):
        """ true if this collides with ent, otherwise false 
            offsets makes the other entity bigger """
        l = math.hypot(self.position.x - ent.position.x, self.position.y - ent.position.y)
        if l <= (self.size+ent.size) * offset:
            return True
        else:
            return False
        
    def sphereCollisionPoint(self, x, y, offset = 0.0):
        """ same as above but tests on a point """
        l = math.hypot(self.position.x - x, self.position.y - y)
        if l <= self.size * offset:
            return True
        else:
            return False
        
    def debug(self):
        #print self.position
        start = (self.position.x, self.position.y)
        end = ( self.position.x + (self.direction.x * self.speed * 10),
                self.position.y + (self.direction.y * self.speed * 10))
        print end
        pygame.draw.line(renderTarget, (255,255,255), start, end)
        pygame.draw.rect(renderTarget, (255,255,255), self.image.get_rect())

allBullets = []
class Bullet(BaseEntity):
    image = None
    maxLifeTime = 1200
    originalImage = None
    size = 2
    speed = 0.3
    color = (255,255,0)
    sound = loadSound("")
    """ a bullet fired from the ship """
    def __init__(self, position, direction, parentShip):
        BaseEntity.__init__(self)
        self.image = self.originalImage.copy()
        self.life = 0
        self.parentShip = parentShip
        self.position = position.copy()
        self.direction = direction.copy()
        self.direction.normalise()
        # acos only returns between 0 and 180
        if self.direction.y > 0:
            self.rotate(math.degrees(math.acos(self.direction.x)))
        else:
            self.rotate(-math.degrees(math.acos(self.direction.x)))
        self.direction *= self.speed
        # a bullet have spawned so play the laser sound
        self.sound.play()
        
    def update(self):
        self.move()
        self.life += deltaTime
        
        # if this bullet has lived to long, kill it
        bulletsToKill = []
        for b in allBullets:
            if b.life > Bullet.maxLifeTime:
                bulletsToKill.append(b)
        for b in bulletsToKill:
            allBullets.remove(b)
            
        BaseEntity.update(self)
    
class ShipStats:
    def __init__(self, initialLives = 3):
        self.lives = initialLives
        self.lifeImage = None
        self.position = vector(8.0,8.0)
        self.score = 0
        self.spacing = 4
        self.scoreMultiplier = 0    # the more (and smaller roids) the bigger the score
        
    def addScore(self, score):
        self.score += (self.scoreMultiplier*score)
        
    def render(self):
        # render lives
        for i in range(self.lives):
            renderTarget.blit(self.lifeImage, (self.position.x+(i*self.lifeImage.get_rect().width), self.position.y))
            
        # render score
        t = font.render("score: "+str(self.score), True, (192,192,192), (0,0,0))
        r = t.get_rect()
        r.topleft = (self.position.x, self.position.y + self.lifeImage.get_rect().height + self.spacing)
        renderTarget.blit(t,r)
        
        # render multiplier
        color = [127,self.scoreMultiplier,self.scoreMultiplier*2]
        if color[1] > 255: color[1] = 255
        if color[2] > 255: color[2] = 255
        t = font.render("multiplier: "+str(self.scoreMultiplier), True, color, (0,0,0))
        r = t.get_rect()
        r.topleft = (self.position.x, self.position.y + self.lifeImage.get_rect().height + self.spacing + r.height)
        renderTarget.blit(t,r)
        
    def updateScoreMultiplier(self):
        """ recalculates the mulitplier, should be called after a roid have been split """
        self.scoreMultiplier = 0
        for a in allAsteroids:
            if a.size == 64:
                self.scoreMultiplier += 1
            elif a.size == 32:
                self.scoreMultiplier += 2
            elif a.size == 16:
                self.scoreMultiplier += 4
            elif a.size == 8:
                self.scoreMultiplier += 8
            
class Respawner:
    def __init__(self):
        self.respawnTime = 3500    # how many milliseconds do we wait before we respawn
        self.timeOfDeath = 0
        self.roidDistanceFactor = 4.0
        
    def respawn(self):
        """ force a respawn """
        collide = True
        while collide:
            p = randomPoint()
            collide = False
            for a in allAsteroids:
                if a.sphereCollisionPoint(p.x,p.y,self.roidDistanceFactor):
                    collide = True  
        effect.allEffects.append(effect.Explosion(p, 4, 2, 0, [255,255,255])) 
        return p
        
    def tryToRespawn(self):    
        """ if we have waited long enough it 
            returns a vector at a position a safe distance away from 'roids """
        if (pygame.time.get_ticks() - self.timeOfDeath) > self.respawnTime:
            # make up a random point
            return self.respawn()
        else:
            return False  
    
class Engine:
    """ a class that handles engine flames """
    flameInterval = None    # how often should we should we put engineflamess out?
    flameDistance = None
    flameExpandSpeed = None
    sound = None
    def __init__(self, parent):
        self.parent = parent
        self.lastFlame = pygame.time.get_ticks()
    
    def burst(self):
        """ put flames out """
        if (pygame.time.get_ticks() - self.lastFlame) > self.flameInterval:
            flamePos = vector(self.parent.position.x,self.parent.position.y)
            flamePos -= (self.parent.orientation*self.flameDistance)          
            effect.allEffects.append(effect.Explosion(flamePos, 8, self.flameExpandSpeed, 8, [random.randint(155,255),random.randint(100,200),0]))
            pygame.draw.circle(renderTarget, [random.randint(155,255),random.randint(100,200),0], (int(flamePos.x),int(flamePos.y)), 4)
            self.sound.play()
            self.lastFlame = pygame.time.get_ticks()

class Ship(BaseEntity):
    originalImage = None
    shootInterval = 350
    turnSpeed = 3
    size = 8
    acceleration = 0.0002
    deathSound = loadSound("")
    bornSound = loadSound("")
    def __init__(self):
        BaseEntity.__init__(self)
        self.respawner = Respawner()
        self.stats = ShipStats()
        self.engine = Engine(self)
        self.image = self.originalImage.copy()
        self.lastShot = pygame.time.get_ticks()
        self.alive = True
        self.stats.lifeImage = self.image
        self.rotate(0)
        # find a good place to start
        self.position = self.respawner.respawn()
        self.bornSound.play()
        
    def update(self):
        if not self.alive:
            # we are dead, try to respawn and return
            p = self.respawner.tryToRespawn()
            if p:    # we got a position
                self.position = p
                self.alive = True
                self.lastShot = 0
                self.orientation = vector(0.0,1.0)
                self.direction = vector(0.0,0.0)
                self.bornSound.play()
                
        else:
            # were alive
#            if self.lastShot > 0:
#                self.lastShot -= 1
            self.move()
            self.stats.updateScoreMultiplier()
        
            for a in allAsteroids:
                if self.sphereCollision(a):
                    # we have collided and must die
                    self.alive = False
                    self.stats.lives -= 1
                    self.respawner.timeOfDeath = pygame.time.get_ticks()
                    self.deathSound.play()
                    effect.allEffects.append(effect.Explosion(self.position, 2, 2, 0, [255,0,0], [255,255,0]))
                    # split the roid
                    self.stats.score += (100 - self.size)
                    a.split()
                    self.stats.updateScoreMultiplier()
                    
            for b in allBonuses:
                if self.sphereCollision(b):
                    b.collectSound.play()
                    self.stats.score += 1000
                    allBonuses.remove(b)
            
            BaseEntity.update(self)
        
    def shoot(self):
        """ spawn a bullet with the same position and direction as the ship """
        if self.alive:
            if (pygame.time.get_ticks() - self.lastShot) > self.shootInterval:
                allBullets.append(Bullet(self.position, self.orientation, self))
#                self.lastShot = self.shootInterval
                self.lastShot = pygame.time.get_ticks()
                
    def engineBurst(self):
        """ same as base but outputs a flame to """
        if self.alive:
            self.engine.burst()
            BaseEntity.engineBurst(self)
            
    def render(self):
        if self.alive:
            BaseEntity.render(self)
        self.stats.render()
        
allAsteroids = []
class Asteroid(BaseEntity):
    mipmapImages = {}   # here we have all the asteroids of all sizes 
#    acceleration = 0.000167
    smallRoidsFasterFactor = 0.035
    deathSound = loadSound("")
#    turnSpeed = 15
    def __init__(self, position, angle=0, size=128, speed=0.02):
        BaseEntity.__init__(self)
        self.originalImage = self.mipmapImages[size*2].copy()
        self.image = self.originalImage.copy()
        self.size = size
        self.position = position.copy()
        self.rotate(angle)
        self.direction = self.orientation.copy()
        self.direction *= speed
#        self.engineBurst()
        
    def update(self):
        self.move()      
#        self.rotate(self.turnSpeed)
#        self.image = pygame.transform.rotate(self.originalImage, self.turnSpeed)
            
        # check if weve pwned somfin
        for b in allBullets:
            if self.sphereCollision(b):
                # add points
                b.parentShip.stats.addScore(100 - self.size)
                effect.allEffects.append(effect.FlashText(b.position, str(100 - self.size), 1, 0.5, vector(0.0,-1.0), [0,255,255], [0,0,0], [0,0,127]))
                # make this bullet kill itself in the next update and add an explosion where it were
                effect.allEffects.append(effect.Explosion(b.position, 16, 4, 16, list(b.color)))
                b.life = Bullet.maxLifeTime 
                self.split()
                b.parentShip.stats.updateScoreMultiplier()
        
        BaseEntity.update(self)
        
#    def rotate(self, degrees):
#        BaseEntity.rotate(self, degrees)
#        self.engineBurst()
        #self.direction.normalise()
        
    def split(self):
        """ adds three asteroids of a smaller size and removes this asteroid """
        self.deathSound.play()
        if not self.size == 8:    # were big enough to split
            for i in range(3):
                a = Asteroid(self.position, random.randrange(0,360,15), self.size/2, self.direction.length() + self.smallRoidsFasterFactor)
#                a.orientation = self.orientation
                a.originalImage.get_rect().right /= 2
                a.originalImage.get_rect().bottom /= 2            
#                a.rotate(random.randrange(0,360,15))
                allAsteroids.append(a)
        else:   # change of dropping bonus
            allBonuses.append(Bonus(self.position, self.direction.length()/3, self.angle))
        allAsteroids.remove(self)
               
allBonuses=[]
class Bonus(BaseEntity):
    size = 8
    bornSound = None
    deathSound = None
    collectSound = None
    def __init__(self, position, speed, angle=random.randrange(0,360,15)):
        BaseEntity.__init__(self)
        self.bornSound.play()
        self.image = self.originalImage.copy()
        self.position = position
        self.rotate(angle)
        self.direction = self.orientation.copy()
        self.direction *= speed
        
    def update(self):
        """ checks if its collides with a roid and kills itself or it moves normally """
#        collide = False
#        for a in allAsteroids()
        self.move()
        BaseEntity.update(self)
        
        for a in allAsteroids:
            if self.sphereCollision(a):
                # weve hit the roid, make an explosion and kill ourselves
                effect.allEffects.append(effect.Explosion(self.position, 2, 1, 6, [0,0,255]))
                if self in allBonuses:
                    allBonuses.remove(self)
                self.deathSound.play()

if __name__ == "__main__":
	print "This is the projects largest file and putting it all together to"
	print "showcase it would produce the game itself, that operation has been moved"
	print "to a separate file: pyroids.py"