import random from pyglet.gl import * from pyglet import clock from pyglet import font from pyglet import image from pyglet import media from pyglet import window w = window.Window(caption='Shooter', fullscreen=True) w.set_exclusive_mouse() bullet_sound = media.load('bullet.wav', streaming=False) explosion_sound = media.load('explosion.wav', streaming=False) music = media.load('music.mp3') music_player = media.Player() music_player.queue(music) music_player.play() class Sprite(object): def __init__(self, x, y): self.x = x self.y = y def draw(self): self.image.blit(self.x, self.y) class Bullet(Sprite): image = image.load('bullet.png') def __init__(self, x, y, dy): super(Bullet, self).__init__(x, y) self.dy = dy bullet_sound.play() def update(self, dt): self.y += self.dy * dt if self.y < 0 or self.y > w.height: bullets.remove(self) return for enemy in list(enemies): if self.collide(enemy): enemies.remove(enemy) bullets.remove(self) explosion_sound.play() return if self.collide(player): bullets.remove(self) message.text = 'Game over' explosion_sound.play() return def collide(self, other): return (other.x <= self.x <= other.x + other.image.width and other.y <= self.y <= other.y + other.image.height) class Enemy(Sprite): image = image.load('enemy.png') class Player(Sprite): image = image.load('player.png') def on_mouse_motion(self, x, y, dx, dy): self.x += dx self.x = min(max(0, self.x), w.width - self.image.width) def on_mouse_press(self, x, y, button, modifiers): bullets.append(Bullet(self.x + self.image.width / 2 - Bullet.image.width/2, self.y + self.image.height + 1, 200)) player = Player(0, 0) w.push_handlers(player) bullets = [] enemies = [] for i in range(7): enemies.append(Enemy(i * (Enemy.image.width + 10), w.height - Enemy.image.height - 10)) enemy_dx = 200 def update_enemies(dt): global enemy_dx if enemies[0].x < 0: enemy_dx = 200 elif enemies[-1].x + Enemy.image.width > w.width: enemy_dx = -200 for enemy in enemies: enemy.x += enemy_dx * dt def enemy_shoot(dt): if not enemies: return enemy = random.choice(enemies) bullets.append(Bullet(enemy.x + enemy.image.width/2 - Bullet.image.width/2, enemy.y - 10, -400)) clock.schedule_interval(enemy_shoot, 1.0) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) font.add_file('neon.ttf') message = font.Text(font.load('Neon', 80), '', x=w.width/2, y=w.height/2, halign='center', valign='center') while not w.has_exit: dt = clock.tick() w.dispatch_events() media.dispatch_events() music_player.dispatch_events() for bullet in list(bullets): bullet.update(dt) if not enemies: message.text = 'Winner' else: update_enemies(dt) w.clear() player.draw() for bullet in bullets: bullet.draw() for enemy in enemies: enemy.draw() message.draw() w.flip()