#gamelib.py
#import the pygame library
import pygame
from pygame.locals import *
from random import randint
SCREENRECT = Rect(0,0,640,480)
class Jet(pygame.sprite.Sprite):
def init(self,image):
pygame.sprite.Sprite.init(self)
self.image = image
self.image.set_colorkey((255,255,255),RLEACCEL)
self.rect = self.image.get_rect()
self.rect.y = 200
def update(self):
self.key = pygame.key.get_pressed()
if self.key[K_UP]:
self.rect.move_ip(0,-5)
if self.key[K_DOWN]:
self.rect.move_ip(0,5)
if self.key[K_LEFT]:
self.rect.move_ip(-5,0)
if self.key[K_RIGHT]:
self.rect.move_ip(5,0)
self.rect=self.rect.clamp(Rect(0,0,800,600))
class Missile (pygame.sprite.Sprite):
def init(self,image):
pygame.sprite.Sprite.init(self)
self.image = image
self.image.set_colorkey((255,255,255), RLEACCEL)
self.x = randint(820,900)
self.y = randint(0,600)
self.rect = self.image.get_rect(center=(self.x,self.y))
self.speed = 1
def update(self):
self.rect.move_ip(-self.speed,0)
if self.rect.right<0:
self.kill()
class Cloud(pygame.sprite.Sprite):
def init (self, image):
pygame.sprite.Sprite.init(self)
self.image = image
self.image.set_colorkey((0,0,0), RLEACCEL)
self.x = randint(820,900)
self.y = randint(0,600)
self.rect = self.image.get_rect(center=(self.x,self.y))
def update(self):
self.rect.move_ip(-5,0)
if self.rect.right<0:
self.kill()
######################################################################
#pygame
from gamelib import*
#initialize pygame
pygame.init()
#create the canvas object
#here we pass it a size of 800x600
canvas=pygame.display.set_mode((800,600))
#load the image
jet=pygame.image.load(‘jet.png’).convert()
missile=pygame.image.load(‘missile.png’).convert()
cloud=pygame.image.load(‘cloud.png’).convert()
scene=pygame.image.load(‘scene.jpg’).convert()
boom =pygame.mixer.Sound(“boom.wav”)
#Create the object
f15 = Jet(jet)
exocet = []
for x in range(0,10):
new_exocet = Missile(missile)
exocet.append(new_exocet)
columbus = Cloud(cloud)
container=pygame.sprite.Group() #create object from class Group
exocet_container = pygame.sprite.Group()
container.add(f15,exocet,columbus) #add 3 objects in the container
exocet_container.add(exocet)
running = True
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
#Draw the scene on to the canvas
canvas.blit(scene,(0,0))
#Update all object in all_items object
container.update()
hits = pygame.sprite.spritecollide(f15, exocet_container, True)
if hits:
f15.kill()
boom.play()
#Draw the all the objects on the canvas
container.draw(canvas)
#Display on to the screen
pygame.display.flip()