#!/usr/bin/env python
from random import randint, random, choice, randrange, uniform
from math import sin, tan, radians, copysign, degrees, cos, asin
from os import mkdir, remove
from os.path import join, exists
from sys import argv
from glob import glob
from collections import deque
from itertools import chain
from pygame.locals import *
from pygame import Surface, Color, PixelArray
from pygame.font import Font
from pygame.mixer import Sound, Channel, get_num_channels
from pygame.draw import polygon, line, circle, aaline
from pygame.gfxdraw import aapolygon, aacircle, filled_circle
from pygame.image import load, save
from pygame.transform import rotate, smoothscale, rotozoom, scale, flip
from pygame.event import clear
from pygame.display import set_mode
from lib.pgfw.pgfw.Game import Game
from lib.pgfw.pgfw.GameChild import GameChild
from lib.pgfw.pgfw.Sprite import Sprite
from lib.pgfw.pgfw.Animation import Animation
from lib.pgfw.pgfw.Vector import Vector
from lib.pgfw.pgfw.extension import (get_distance, get_delta, place_in_rect,
get_step, collide_line_with_rect)
class SoundEffect(GameChild, Sound):
def __init__(self, parent, path, volume=1.0):
GameChild.__init__(self, parent)
Sound.__init__(self, path)
self.display_surface = self.get_display_surface()
self.set_volume(volume)
def play(self, loops=0, maxtime=0, fade_ms=0, position=None, x=None):
channel = Sound.play(self, loops, maxtime, fade_ms)
if x is not None:
position = float(x) / self.display_surface.get_width()
if position is not None and channel is not None:
channel.set_volume(*self.get_panning(position))
return channel
def get_panning(self, position):
return 1 - max(0, ((position - .5) * 2)), \
1 + min(0, ((position - .5) * 2))
# ===--------------------===
# )))) FISSION / FUSION ((((
# ===--------------------===
class iQue(Game, Sprite):
GENERATE_FLAG = "-generate"
FRAME_DIR = "frame/"
def __init__(self):
Game.__init__(self)
Sprite.__init__(self, self, 1000)
if self.check_command_line(self.GENERATE_FLAG):
pixels = PixelArray(smoothscale(\
load(self.get_resource("Untitled.png")).convert(), (500, 400)))
if not exists(self.FRAME_DIR):
mkdir(self.FRAME_DIR)
for path in glob("%s/*.png" % self.FRAME_DIR):
remove(path)
for ii in xrange(int(argv[argv.index("-" + \
self.GENERATE_FLAG) + 1])):
color = Color(0, 0, 0)
for x in xrange(len(pixels)):
for y in xrange(len(pixels[0])):
h, s, l, a = Color(*Surface((0, 0)).\
unmap_rgb(pixels[x][y])).hsla
color.hsla = int((h + (ii % 240)) % 360), int(s), 50,\
100
pixels[x][y] = color
pixels[x - 138][y - (ii % 1024)] = pixels[\
x - (ii % 128)][y - (ii % 2)]
print ii
save(pixels.make_surface(), "%s/%04i.png" % (self.FRAME_DIR,
ii))
for path in sorted(glob("%s/*.png" % self.FRAME_DIR)):
self.add_frame(load(path).convert())
self.location.topleft = -10, -10
self.goal = Goal(self)
self.calorie = Calorie(self)
self.carrot = Carrot(self)
self.subscribe(self.respond)
self.reset()
clear()
def respond(self, event):
if self.delegate.compare(event, "reset-game"):
self.reset()
def reset(self):
self.calorie.reset()
def update(self):
Sprite.update(self)
self.goal.update()
self.carrot.update()
self.calorie.update()
class Carrot(Sprite):
SIZE = 60, 35
MARGIN = 30
def __init__(self, parent):
Sprite.__init__(self, parent)
self.add_frame(smoothscale(load("Emparchment.png").convert_alpha(),
self.SIZE))
self.spawn()
def spawn(self):
place_in_rect(self.get_display_surface().get_rect(), self.location,
True, self.parent.goal.skull.location.inflate(\
[self.MARGIN] * 2))
self.parent.calorie.find_carrot()
class Goal(GameChild):
def __init__(self, parent):
GameChild.__init__(self, parent)
self.skull = Skull(self)
self.shield = Shield(self)
def update(self):
self.skull.update()
class Skull(Sprite):
MARGIN = 10
def __init__(self, parent):
Sprite.__init__(self, parent)
self.add_frame(load("Pencil.png").convert_alpha())
self.location.bottomright = self.get_display_surface().get_rect().\
move([-self.MARGIN] * 2).bottomright
class Shield(GameChild):
def __init__(self, parent):
GameChild.__init__(self, parent)
class Calorie(Sprite):
SIZE = 71, 88
SPAWN_MARGIN = 30
FETCH_DELAY = 1000
SPEED = 7
CARROT_BOX_SHRINK = -20, -10
PROJECTION_LENGTH = 2000
SPIN_RANGE = -1.2, 1.2
NORTH, EAST, SOUTH, WEST = range(4)
def __init__(self, parent):
Sprite.__init__(self, parent)
self.step = (0, 0)
self.shot_speed_nodeset = self.get_game().interpolator.\
get_nodeset("shot-speed")
self.add_frames()
self.shadow = load("Gallery.png").convert_alpha()
self.register(self.fetch_carrot, self.barf)
def add_frames(self):
morph_paths = glob(join(self.get_resource("morph"), "*.png"))
base = load("Calorie.png").convert_alpha()
self.add_frame(base)
self.add_frameset(0, name="facing-right")
self.add_frame(flip(base, True, False))
self.add_frameset(1, name="facing-left")
self.set_frameset(randint(1, 2))
for path in sorted():
self.add_frame(load(path).convert_alpha())
self.add_frameset(xrange(2, len(self.frames)), name="shooting")
def reset(self):
self.shot_count = 0
self.clear_aim()
place_in_rect(self.get_display_surface().get_rect(), self.location,
True, self.parent.goal.skull.location.inflate(\
[self.SPAWN_MARGIN] * 2))
def clear_aim(self):
self.collisions = []
self.steps = []
def find_carrot(self):
self.play(self.fetch_carrot, delay=self.FETCH_DELAY, play_once=True)
def fetch_carrot(self):
step = self.step = get_step(self.location.midbottom,
self.parent.carrot.location.center,
self.SPEED)
if step[0] < 0:
self.set_frameset("facing-left")
else:
self.set_frameset("facing-right")
def aim(self):
angles = deque(xrange(360))
angles.rotate(randrange(0, len(angles)))
magnitude = self.shot_speed_nodeset.get_y(self.shot_count)
bounds = self.get_display_surface().get_rect()
spin = uniform(*self.SPIN_RANGE)
best_wc, best_c, best_s = None, [], []
for angle in angles:
collides, wall_count, collisions, steps = self.project(angle, spin,
magnitude,
bounds)
if collides and wall_count >= best_wc and \
len(steps) >= len(best_s) and len(collisions) <= \
len(best_c) + 1:
best_wc = wall_count
best_c = collisions
best_s = steps
self.steps = best_s
self.collisions = best_c
self.shot_count += 1
self.set_frameset("shooting")
self.play(self.barf, delay=3000, play_once=True)
def project(self, angle, spin, magnitude, bounds):
traveled = 0
projection = Vector(*self.get_game().carrot.location.center)
collides = False
steps = []
collisions = []
walls = [False] * 4
while traveled < self.PROJECTION_LENGTH:
delta = get_delta(angle, magnitude)
projection += delta
angle += spin
if steps and collide_line_with_rect(self.get_game().goal.skull.\
location, steps[-1],
projection):
collides = True
break
if projection[0] < bounds.left or projection[0] > bounds.right or \
projection[1] < bounds.top or projection[1] > bounds.bottom:
if projection[0] < bounds.left:
projection[0] += 2 * (bounds.left - projection[0])
wall_angle = 0
walls[self.WEST] = True
elif projection[0] > bounds.right:
projection[0] += 2 * (bounds.right - projection[0])
wall_angle = 0
walls[self.EAST] = True
if projection[1] < bounds.top:
projection[1] += 2 * (bounds.top - projection[1])
wall_angle = 180
walls[self.NORTH] = True
elif projection[1] > bounds.bottom:
projection[1] += 2 * (bounds.bottom - projection[1])
wall_angle = 180
walls[self.SOUTH] = True
collisions.append(map(int, projection))
angle = wall_angle - angle
steps.append(tuple(projection))
traveled += magnitude
wall_count = 0
for wall in walls:
if wall:
wall_count += 1
return collides, wall_count, collisions, steps
def barf(self):
self.get_game().carrot.spawn()
self.clear_aim()
def update(self):
self.get_game().time_filter.open()
ds = self.get_display_surface()
for ii in xrange(1, len(self.steps)):
line(ds, (0, 0, 0), self.steps[ii - 1], self.steps[ii], 5)
line(ds, (128, 128, 128), self.steps[ii - 1], self.steps[ii], 3)
line(ds, (0, 255, 255), self.steps[ii - 1], self.steps[ii])
for ii, collision in enumerate(self.collisions):
font = Font(None, 20)
surface = font.render(str(ii), False, (0, 0, 255))
circle(ds, (255, 255, 255), collision, 20)
ds.blit(surface, collision)
if self.step != (0, 0):
if self.parent.carrot.location.inflate(self.CARROT_BOX_SHRINK).\
collidepoint(self.location.midbottom - ):
self.step = (0, 0)
self.get_game().time_filter.close()
self.aim()
else:
self.move(*self.step)
Sprite.update(self)
if __name__ == "__main__":
iQue().run()