code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Abstract Classes for defining an audio mixer."""
import abc
##-------- Classes
class Sound(object):
__metaclass__ = abc.ABCMeta
def __init__(self, filename=None, data=None):
pass
@abc.abstractmethod
def play(self, channel=0, volume=1.0, offset=0, fadein=0, envelope=None, loops=0):
pass
class StreamingSound(object):
__metaclass__ = abc.ABCMeta
def __init__(self, filename=None):
pass
@abc.abstractmethod
def play(self, channel=0, volume=1.0, offset=0, fadein=0, envelope=None, loops=0):
pass
class Channel(object):
__metaclass__ = abc.ABCMeta
class Mixer(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def tick(self):
pass
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo audio mixer backend for the Pygame mixer.
pygamemixer requires the pygame.mixer module, so it may not work on all
systems. It also has many limitations compared to the default mixer:
- You can't pan
- You can't use effects
- You can't position the sounds in the 2d world
- You can only stream one file at a time
Supported Formats:
- Ogg Vorbix (.ogg)
- Wave (.wav)
"""
import numpy
import pygame
from ... import core
import abstractmixer
try:
pygame.mixer.init()
except:
raise ImportError, "pygame.mixer not available."
##-------- Constants
SAMPLERATE = 0
CHANNELS = 0
CHUNKSIZE = 0
THREADED = False
##-------- Functions
def init(samplerate=44100, channels=2, chunksize=1024):
"""Initialize the mixer.
samplerate - (int) The number of samples per second.
channels - (int) The number of stereo channels to use
chunksize - (int) The number of samples processed at a time.
Returns: None
"""
pygame.mixer.init()
global SAMPLERATE, CHANNELS, CHUNKSIZE
SAMPLERATE = samplerate
CHANNELS = channels
CHUNKSIZE = chunksize
pygame.mixer.quit()
pygame.mixer.init(samplerate, 16, channels, chunksize)
Channel()
def start():
"""Start a new mixing thread."""
pass
def quit():
pygame.mixer.quit()
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
##-------- Sounds
class Sound(abstractmixer.Sound):
"""A sound loaded completely into memory."""
def __init__(self, filename):
self.data = pygame.sndarray.array(pygame.mixer.Sound(filename))
self.sound = None
def play(self, channel=0, volume=1.0, loops=0, *args, **kwargs):
d = self.data.copy()
d *= volume
Mixer.channels[channel].add_src(d, self, loops)
return self
def resample(self, samplerate):
pass
def pause(self):
if self.sound:
self.sound.pause()
def unpause(self):
if self.sound:
self.sound.unpause()
def stop(self):
if self.sound:
self.sound.stop()
length = property(lambda: len(self.data))
class StreamingSound(abstractmixer.StreamingSound):
"""A sound streamed directly from disk."""
def __init__(self, filename):
self.data = pygame.mixer.music.load(filename)
def play(self, channel=0, volume=1.0, loops=0, *args, **kwargs):
Mixer.channels[channel].volume = volume
Mixer.channels[channel].add_src("stream", self, loops)
return self
def pause(self):
pygame.mixer.music.pause()
def unpause(self):
pygame.mixer.music.unpause()
def stop(self):
pygame.mixer.music.stop()
##-------- Mixer
class Channel(abstractmixer.Channel):
"""A "mixer channel"/Group."""
def __init__(self, volume=1.0):
Mixer.channels.append(self)
self.srcs = []
self.volume = volume
def add_src(self, src, original, *args):
self.srcs.append([src, original, args])
def add_effect(self, effect):
pass
class Mixer(abstractmixer.Mixer):
"""A collection of Channels."""
channels = []
@classmethod
def tick(self, dt):
out = numpy.zeros((CHUNKSIZE, 2), numpy.float)
for ch in self.channels:
for src in ch.srcs:
if src[0] == "stream":
pygame.mixer.music.set_volume(ch.volume)
pygame.mixer.music.play(*src[2])
continue
src[0] *= ch.volume
s = pygame.sndarray.make_sound(src[0])
src[1].sound = s.play(*src[2])
ch.srcs = []
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Abstract Classes for defining an audio mixer."""
import abc
##-------- Classes
class Sound(object):
__metaclass__ = abc.ABCMeta
def __init__(self, filename=None, data=None):
pass
@abc.abstractmethod
def play(self, channel=0, volume=1.0, offset=0, fadein=0, envelope=None, loops=0):
pass
class StreamingSound(object):
__metaclass__ = abc.ABCMeta
def __init__(self, filename=None):
pass
@abc.abstractmethod
def play(self, channel=0, volume=1.0, offset=0, fadein=0, envelope=None, loops=0):
pass
class Channel(object):
__metaclass__ = abc.ABCMeta
class Mixer(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def tick(self):
pass
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo audio mixer backend for the PyAudio PortAudio bindings.
This module is heavily influenced by SWMixer by Nathan Whitehead.
"""
import time
import wave
import thread
import math
import numpy
import pyaudio
from ... import core
from ... import flmath
from ... import util
import abstractmixer
##-------- Constants
SAMPLERATE = 0
CHANNELS = 0
CHUNKSIZE = 0
PYAUDIO = None
STREAM = None
THREADED = True
THREAD = None
LOCK = thread.allocate_lock()
half_pi = math.pi * 0.5
##-------- Initialization Functions
def init(samplerate=44100, chunksize=256):
"""Initialize the mixer.
samplerate - (int) The number of samples per second.
chunksize - (int) The number of samples processed at a time.
Returns: None
"""
global SAMPLERATE, CHANNELS, CHUNKSIZE, PYAUDIO, STREAM
SAMPLERATE = samplerate
CHANNELS = 2
CHUNKSIZE = chunksize
PYAUDIO = pyaudio.PyAudio()
STREAM = PYAUDIO.open(
format = pyaudio.paInt16,
channels = CHANNELS,
rate = SAMPLERATE,
output= True
)
Channel()
def start():
"""Start a new mixing thread."""
global THREAD
def f():
while True:
try: Mixer.tick(core.GAME.data.delta_time)
except AttributeError: pass
THREAD = thread.start_new_thread(f, ())
def quit():
pass
##-------- Audio Functions
def resample(src, scale):
"""Resample a mono or stereo source."""
n = round(len(src) * scale)
return numpy.interp(
numpy.linspace(0.0, 1.0, n, endpoint=False),
numpy.linspace(0.0, 1.0, len(src), endpoint=False),
src
)
def interleave(left, right):
"""Convert two mono sources into one stereo source."""
return numpy.ravel(numpy.vstack((left, right)), order='F')
def uninterleave(src):
"""Convert one stereo source into two mono sources."""
return src.reshape(2, len(src)/2, order='FORTRAN')
def stereo_to_mono(left, right):
"""Convert one stereo source into one mono source."""
return (0.5 * left + 0.5 * right).astype(numpy.int16)
def calculate_pan(left, right, pan):
"""Pan two mono sources in the stereo field."""
if pan < -1: pan = -1
elif pan > 1: pan = 1
pan = ((pan + 1.0) * 0.5) * half_pi
l, r = math.cos(pan), math.sin(pan)
return left * l, right * r
def __distance__(distance):
if distance > 1:
v = distance**-1
if v > 0.01:
return v
return 0
return 1
distance_formula = __distance__
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
##-------- Sounds
class Sound(abstractmixer.Sound):
"""A sound completely loaded into memory."""
def __init__(self, filename):
## See if data is cached
try:
self.data = core._Data.aud_cache[filename]
except KeyError:
## Read Data
wav = wave.open(filename, 'rb')
num_ch = wav.getnchannels()
self.framerate = wav.getframerate()
fr = wav.getframerate()
sw = wav.getsampwidth()
data = []
r = ' '
while r != '':
r = wav.readframes(4096)
data.append(r)
if sw == 2:
self.data = numpy.fromstring(''.join(data), dtype=numpy.int16)
if sw == 4:
self.data = numpy.fromstring(''.join(data), dtype=numpy.int32)
self.data /= 65536.0
if sw == 1:
self.data = numpy.fromstring(''.join(data), dtype=numpy.uint8)
self.data *= 256.0
wav.close()
## Resample
if fr != SAMPLERATE:
scale = SAMPLERATE * 1.0 / fr
if num_ch == 1:
self.data = resample(self.data, scale)
if num_ch == 2:
left, right = uninterleave(self.data)
nleft = resample(left, scale)
nright = resample(right, scale)
self.data = interleave(nleft, nright)
## Stereo Conversion
if num_ch != CHANNELS:
if num_ch == 1:
## Need Stereo
self.data = interleave(self.data, self.data)
core._Data.aud_cache[filename] = self.data
def play(self, channel=0, volume=1.0, loops=0, pos=(0,0)):
"""Plays the audio data.
channel - Mixer channel to play the audio on.
volume - The volume to play at.
loops - The number of times to loop the audio. -1 is infinite
pos - The position in 2d space to play the sound at.
Returns: SoundEvent
"""
sndevent = SoundEvent(self.data, volume, loops, flmath.Vector(pos))
if Mixer.channels == []:
Channel()
LOCK.acquire()
Mixer.channels[channel].add_src(sndevent)
LOCK.release()
return sndevent
def resample(self, samplerate):
self.data = resample(self.data, SAMPLERATE * 1.0 / samplerate)
##-------- Properties
def _get_length(self):
return len(self.data)
length = property(_get_length)
class StreamingSound(abstractmixer.StreamingSound):
"""A sound streamed directly from disk."""
def __init__(self, filename):
self.filename = filename
def play(self, channel=0, volume=1.0, loops=0):
"""Plays the audio stream.
channel - Mixer channel to play the audio on.
volume - The volume to play at.
loops - The number of times to loop the audio. -1 is infinite
Returns: StreamingSoundEvent
"""
sndevent = StreamingSoundEvent(self.filename, volume, loops)
if Mixer.channels == []:
Channel()
LOCK.acquire()
Mixer.channels[channel].add_src(sndevent)
LOCK.release()
return sndevent
## Properties won't work, they're just there for compatibility
## with Sound
##-------- Properties
def _get_length(self):
return None
length = property(_get_length)
class SoundEvent(object):
"""Represents one Sound source currently playing."""
def __init__(self, data, volume, loops, pos):
self.data = data
self.seek = 0
self.volume = volume
self.loops = loops
self.pos = pos
self.active = True
self.done = False
def get_samples(self, sz):
"""Return a new buffer of samples from the audio data.
sz - The size, in samples, of the buffer
Returns: numpy.array
"""
if not self.active:
return
z = self.data[self.seek:self.seek + sz]
self.seek += sz
if len(z) < sz:
# oops, sample data didn't cover buffer
if self.loops != 0:
# loop around
self.loops -= 1
self.seek = sz - len(z)
z = numpy.append(z, self.data[:sz - len(z)])
else:
# nothing to loop, just append zeroes
z = numpy.append(z, numpy.zeros(sz - len(z), numpy.int16))
# and stop the sample, it's done
self.done = True
if self.seek == len(self.data):
# this case loops without needing any appending
if self.loops != 0:
self.loops -= 1
self.seek = 0
else:
self.done = True
return uninterleave(z * self.volume)
def pause(self):
LOCK.acquire()
self.active = False
LOCK.release()
def unpause(self):
LOCK.acquire()
self.active = True
LOCK.release()
def stop(self):
LOCK.acquire()
self.done = True
LOCK.release()
class StreamingSoundEvent(object):
"""Represents one StreamingSound currently playing."""
def __init__(self, filename, volume, loops):
self.stream = wave.open(filename, 'rb')
self.volume = volume
self.seek = 0
self.loops = loops
self.pos = (0, 0)
self.active = True
self.done = False
self.buf = ''
def get_samples(self, sz):
"""Return a new buffer of samples from the audio data.
sz - The size, in samples, of the buffer
Returns: numpy.array
"""
szb = sz * 2
while len(self.buf) < szb:
s = self.read()
if s is None or s == '': break
self.buf += s[:]
z = numpy.fromstring(self.buf[:szb], dtype=numpy.int16)
if len(z) < sz:
# In this case we ran out of stream data
# append zeros (don't try to be sample accurate for streams)
z = numpy.append(z, numpy.zeros(sz - len(z), numpy.int16))
if self.loops != 0:
self.loops -= 1
self.seek = 0
self.stream.rewind()
self.buf = ''
else:
self.done = True
self.stream.close()
else:
# remove head of buffer
self.buf = self.buf[szb:]
return uninterleave(z * self.volume)
def read(self):
"""Return a buffer from the audio file."""
return self.stream.readframes(4096)
def pause(self):
LOCK.acquire()
self.active = False
LOCK.release()
def unpause(self):
LOCK.acquire()
self.active = True
LOCK.release()
def stop(self):
LOCK.acquire()
self.done = True
self.stream.close()
LOCK.release()
##-------- Mixer
class Channel(abstractmixer.Channel):
"""Represents a channel on a hardware mixer."""
def __init__(self, volume=1.0, pan=0):
self.id = len(Mixer.channels)
Mixer.channels.append(self)
self.srcs = []
self.effects = []
self.volume = volume
self.pan = 0
def add_src(self, src):
"""Add a SoundEvent or StreamingSoundEvent to the channel."""
self.srcs.append(src)
def add_effect(self, effect):
LOCK.acquire()
self.effects.append(effect)
LOCK.release()
class Mixer(abstractmixer.Mixer):
"""Represents a limited hardware mixer.
A Mixer essentially acts as a Master Bus on an analogue mixer. All of
the other Channel's output goes through the mixer to get written to
the output stream.
"""
channels = []
effects = []
volume = 1.0
time_slept = 0 ## ms since last tick()
@classmethod
def tick(self, dt):
"""Write all of the audio buffers to the output stream.
Basic Steps:
1. Create a buffer for each Channel
2. For each Sound on each Channel, calculate panning/volume,
write to Channel Buffer
3. Write each Sound to the appropriate Channel buffer
4. Run each of the Channel's effects on it's Channel buffer
5. Mix together all of the Channel buffers to the Mixer buffer
6. Run Mixer effects on the Mixer buffer
7. Write Mixer buffer to output stream
Returns: None
"""
sz = CHUNKSIZE * CHANNELS
out = numpy.zeros(sz, numpy.float)
chout = numpy.zeros(CHUNKSIZE)
LOCK.acquire()
for ch in self.channels:
rmlist = []
## Create Channel Buffer
choutl, choutr = chout.copy(), chout.copy()
for src in ch.srcs:
if not src.active:
continue
## Read Data from Sound Buffer
l, r = src.get_samples(sz)
if src.done:
rmlist.append(src)
continue
## Calculate Sound Volume/Pan from distance
d = flmath.distance(src.pos, (0,0))
dist_vol = distance_formula(d)
angle_pan = 0
if d != 0:
a = math.radians(src.pos.angle) / 2.0
angle_pan = (2 * a) / half_pi - 1
if angle_pan > 1:
angle_pan = 1 - (angle_pan - 1)
l *= dist_vol
r *= dist_vol
l, r = calculate_pan(l, r, ch.pan - angle_pan)
## Write Sound to Channel buffer
choutl += l
choutr += r
## Render Channel Effects
for effect in ch.effects:
choutl, choutr = effect.process(choutl, choutr, CHUNKSIZE)
## Write Channel buffer to Mixer buffer
s = interleave(choutl, choutr) * ch.volume
out = out + s - (out * s) / 65536
for src in rmlist:
ch.srcs.remove(src)
## Render Mixer Effects
l, r = uninterleave(out)
for effect in self.effects:
effect.process(l, r, CHUNKSIZE)
LOCK.release()
## Write Mixer buffer to Output Stream
out = interleave(l, r) * self.volume
out = out.clip(-32767.0, 32767.0)
outdata = (out.astype(numpy.int16)).tostring()
#while STREAM.get_write_available() < sz: time.sleep(0.001)
STREAM.write(outdata, CHUNKSIZE)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo audio mixer backend for the Pygame mixer.
pygamemixer requires the pygame.mixer module, so it may not work on all
systems. It also has many limitations compared to the default mixer:
- You can't pan
- You can't use effects
- You can't position the sounds in the 2d world
- You can only stream one file at a time
Supported Formats:
- Ogg Vorbix (.ogg)
- Wave (.wav)
"""
import numpy
import pygame
from ... import core
import abstractmixer
try:
pygame.mixer.init()
except:
raise ImportError, "pygame.mixer not available."
##-------- Constants
SAMPLERATE = 0
CHANNELS = 0
CHUNKSIZE = 0
THREADED = False
##-------- Functions
def init(samplerate=44100, channels=2, chunksize=1024):
"""Initialize the mixer.
samplerate - (int) The number of samples per second.
channels - (int) The number of stereo channels to use
chunksize - (int) The number of samples processed at a time.
Returns: None
"""
pygame.mixer.init()
global SAMPLERATE, CHANNELS, CHUNKSIZE
SAMPLERATE = samplerate
CHANNELS = channels
CHUNKSIZE = chunksize
pygame.mixer.quit()
pygame.mixer.init(samplerate, 16, channels, chunksize)
Channel()
def start():
"""Start a new mixing thread."""
pass
def quit():
pygame.mixer.quit()
def ms_to_samp(ms):
return int(ms * (SAMPLERATE / 1000.0))
def samp_to_ms(samp):
return int(samp / (SAMPLERATE / 1000.0))
##-------- Sounds
class Sound(abstractmixer.Sound):
"""A sound loaded completely into memory."""
def __init__(self, filename):
self.data = pygame.sndarray.array(pygame.mixer.Sound(filename))
self.sound = None
def play(self, channel=0, volume=1.0, loops=0, *args, **kwargs):
d = self.data.copy()
d *= volume
Mixer.channels[channel].add_src(d, self, loops)
return self
def resample(self, samplerate):
pass
def pause(self):
if self.sound:
self.sound.pause()
def unpause(self):
if self.sound:
self.sound.unpause()
def stop(self):
if self.sound:
self.sound.stop()
length = property(lambda: len(self.data))
class StreamingSound(abstractmixer.StreamingSound):
"""A sound streamed directly from disk."""
def __init__(self, filename):
self.data = pygame.mixer.music.load(filename)
def play(self, channel=0, volume=1.0, loops=0, *args, **kwargs):
Mixer.channels[channel].volume = volume
Mixer.channels[channel].add_src("stream", self, loops)
return self
def pause(self):
pygame.mixer.music.pause()
def unpause(self):
pygame.mixer.music.unpause()
def stop(self):
pygame.mixer.music.stop()
##-------- Mixer
class Channel(abstractmixer.Channel):
"""A "mixer channel"/Group."""
def __init__(self, volume=1.0):
Mixer.channels.append(self)
self.srcs = []
self.volume = volume
def add_src(self, src, original, *args):
self.srcs.append([src, original, args])
def add_effect(self, effect):
pass
class Mixer(abstractmixer.Mixer):
"""A collection of Channels."""
channels = []
@classmethod
def tick(self, dt):
out = numpy.zeros((CHUNKSIZE, 2), numpy.float)
for ch in self.channels:
for src in ch.srcs:
if src[0] == "stream":
pygame.mixer.music.set_volume(ch.volume)
pygame.mixer.music.play(*src[2])
continue
src[0] *= ch.volume
s = pygame.sndarray.make_sound(src[0])
src[1].sound = s.play(*src[2])
ch.srcs = []
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import audio
import display
import event
__all__ = ["audio", "display", "event"] | Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import audio
import display
import event
__all__ = ["audio", "display", "event"] | Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import abc
import numpy
import math
class Effect(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def process(self, l, r, buffersize):
pass
class Reverb(Effect):
def __init__(self):
self.bufl = None
def process(self, l, r, buffersize):
outl, outr = l.copy(), r.copy()
return outl, outr
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import sys
from ..backends.audio import dummymixer
mixer = dummymixer
from . import effects
def load(module):
try:
global mixer
__import__(module)
mixer = sys.modules[module]
except ImportError, err:
print "{0}. Mixers unavailable. Audio disabled.".format(err)
mixer = dummymixer
__all__ = ["mixer", "effects"]
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import abc
import numpy
import math
class Effect(object):
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def process(self, l, r, buffersize):
pass
class Reverb(Effect):
def __init__(self):
self.bufl = None
def process(self, l, r, buffersize):
outl, outr = l.copy(), r.copy()
return outl, outr
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import sys
from ..backends.audio import dummymixer
mixer = dummymixer
from . import effects
def load(module):
try:
global mixer
__import__(module)
mixer = sys.modules[module]
except ImportError, err:
print "{0}. Mixers unavailable. Audio disabled.".format(err)
mixer = dummymixer
__all__ = ["mixer", "effects"]
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
class _Data(object):
"""Contains data necessary to run the Game.
All instances share the same state, so every instance created will
have exact replicas of the data. They will also all update their
data automatically if you change the data in one instance.
"""
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
##-------- Metadata
fl_version = "0.1.0"
fl_author = "Bradley Zeis"
fl_author_email = "flamingoengine@gmail.com"
fl_copyright = "2009 Bradley Zeis"
fl_url = "http://flamingoengine.googlecode.com/"
game_name = ""
game_version = ""
game_author = ""
game_author_email = ""
game_copyright = ""
game_url = ""
##-------- File Data
##-------- Screen Data
screen_title = "flamingo - {0}".format(fl_version)
screen_size = None
fullscreen = False
screens = []
painter = None
master_eventlistener = None
eventlistener = None
##-------- Clock Data
master_clock = None
logic_clock = None
render_clock = None
logic_fps = 64
current_time = 0
delta_time = 0 ## Time delta between current frame and last frame.
##-------- Caches
tex_cache = {}
##-------- Game Data
master_spr_group = None
spr_groups = []
usr_groups = []
@classmethod
def clear(cls):
cls.master_spr_group.empty()
for grp in cls.spr_groups:
grp.empty()
for grp in cls.usr_groups:
grp.empty()
cls.spr_groups = []
cls.usr_groups = []
##-------- Global Names
GAME = None
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
SCREEN_BLOCK_DRAW = 1<<0
SCREEN_CULL_SPRITES = 1<<1
SCREEN_DRAW_TEXTURES = 1<<2 ## Draws outline of Sprites
SCREEN_DRAW_MESHES = 1<<3 ## Outlines all of the Meshes
SCREEN_DRAW_WIREFRAME = 1<<4 ## Outlines bounding areas of Sprites
POLYGON_STATIC = 1<<0
POLYGON_AXIS_ALIGNED = 1<<1
POLYGON_MUTABLE_LENGTH = 1<<2
TIME_PAUSED = 1<<0
## Action Types
## Powers of 2 are "downs"
## (Powers of 2)+1 are "ups"
## (Powers of 2)+2 are "holds"
## (Powers of 2)+3 are the same as "downs" (removed Frame after)
## (Powers of 2)+4 are "ups" (removed Frame after)
## (Powers of 2)+5 are the same as "holds" (removed Frame after)
NOEVENT = 0
QUIT = -2
VIDEOEXPOSE = -3
VIDEORESIZE = -5
KEYDOWN = 8
KEYUP = 9
KEYHOLD = 10
MOUSEMOTION = 15
MOUSEBUTTONDOWN = 16
MOUSEBUTTONUP = 17
MOUSEBUTTONHOLD = 18
SCROLLWHEEL = MOUSEBUTTONDOWN
TIMERSTART = 32
TIMEREND = 33
TIMERTICK = 34
JOYAXISMOTION = 0
JOYBALLMOTION = 0
JOYHATMOTION = 0
JOYBUTTONUP = 0
JOYBUTTONDOWN = 0
## Action Keys
K_NONE = -1
K_ALT = 768
K_CAPS = 8192
K_CTRL = 192
K_LALT = 256
K_LCTRL = 64
K_LMETA = 1024
K_LSHIFT = 1
K_META = 3072
K_NUM = 4096
K_RALT = 512
K_RCTRL = 128
K_RMETA = 2048
K_RSHIFT = 2
K_SHIFT = 3
K_0 = 48
K_1 = 49
K_2 = 50
K_3 = 51
K_4 = 52
K_5 = 53
K_6 = 54
K_7 = 55
K_8 = 56
K_9 = 57
K_AMPERSAND = 38
K_ASTERISK = 42
K_AT = 64
K_BACKQUOTE = 96
K_BACKSLASH = 92
K_BACKSPACE = 8
K_BREAK = 318
K_CAPSLOCK = 301
K_CARET = 94
K_CLEAR = 12
K_COLON = 58
K_COMMA = 44
K_DELETE = 127
K_DOLLAR = 36
K_DOWN = 274
K_END = 279
K_EQUALS = 61
K_ESCAPE = 27
K_EURO = 321
K_EXCLAIM = 33
K_F1 = 282
K_F10 = 291
K_F11 = 292
K_F12 = 293
K_F13 = 294
K_F14 = 295
K_F15 = 296
K_F2 = 283
K_F3 = 284
K_F4 = 285
K_F5 = 286
K_F6 = 287
K_F7 = 288
K_F8 = 289
K_F9 = 290
K_FIRST = 0
K_GREATER = 62
K_HOME = 278
K_INSERT = 277
K_KP0 = 256
K_KP1 = 257
K_KP2 = 258
K_KP3 = 259
K_KP4 = 260
K_KP5 = 261
K_KP6 = 262
K_KP7 = 263
K_KP8 = 264
K_KP9 = 265
K_KP_DIVIDE = 267
K_KP_ENTER = 271
K_KP_EQUALS = 272
K_KP_MINUS = 269
K_KP_MULTIPLY = 268
K_KP_PERIOD = 266
K_KP_PLUS = 270
K_LAST = 323
K_LEFT = 276
K_LEFTBRACKET = 91
K_LEFTPAREN = 40
K_LESS = 60
K_LSUPER = 311
K_MENU = 319
K_MINUS = 45
K_MODE = 313
K_NUMLOCK = 300
K_PAGEDOWN = 281
K_PAGEUP = 280
K_PAUSE = 19
K_PERIOD = 46
K_PLUS = 43
K_POWER = 320
K_PRINT = 316
K_QUESTION = 63
K_QUOTE = 39
K_QUOTEDBL = 34
K_RETURN = 13
K_RIGHT = 275
K_RIGHTBRACKET = 93
K_RIGHTPAREN = 41
K_RSUPER = 312
K_SCROLLOCK = 302
K_SEMICOLON = 59
K_SLASH = 47
K_SPACE = 32
K_SYSREQ = 317
K_TAB = 9
K_UNDERSCORE = 95
K_UNKNOWN = 0
K_UP = 273
K_a = 97
K_b = 98
K_c = 99
K_d = 100
K_e = 101
K_f = 102
K_g = 103
K_h = 104
K_i = 105
K_j = 106
K_k = 107
K_l = 108
K_m = 109
K_n = 110
K_o = 111
K_p = 112
K_q = 113
K_r = 114
K_s = 115
K_t = 116
K_u = 117
K_v = 118
K_w = 119
K_x = 120
K_y = 121
K_z = 122
MB_1 = -11
MB_2 = -12
MB_3 = -13
MS_DOWN = -14
MS_UP = -15
M_MOTION = -16
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""
Terms:
Action - Something that happens generally, not something specific.
Event - A specific instance of an action that is placed in the EventRecord.
Frame - One cycle of even processing. Events are handled once per display frame.
Reaction - A callback called because of a specific event. You 'bind' reactions to EventListeners.
Modifiers - Events that 'modify' reactions. For example, pressing shift can cause a
different reaction for mouse clicks.
All times are the time of the frame when the events are handled, not the time when the event occurred. Backends
do not need to worry about what time the even happened, they just need to preserve order. (The frontend gets
the time from core._Data.current_time)
Event backends must define:
init()
poll()
"""
import sys
from . import constants
from . import core
_BACKEND = None
_INITIALIZED = False
RECORD = None
POSTED = {}
def load(event_name):
"""Load an event backend.
If the event backend has already been initialized, there will be no effect.
Return: None
"""
if _INITIALIZED:
return
try:
global _BACKEND
__import__(event_name)
_BACKEND = sys.modules[event_name]
except ImportError:
raise ImportError, "could not import backend '{0}'".format(event_name)
def init():
"""Initialize the event backend.
If a backend is not loaded before this is called, an AttributeError is raised.
Backend:
Backends should not change the values of display._BACKEND or display._INITIALIZED
Return: None
"""
try:
_BACKEND.init()
except AttributeError:
raise AttributeError, "an event backend has not been loaded"
global RECORD
RECORD = EventRecord()
class EventRecord(dict):
"""Store a record of the current events for an action key, and the last event that happened if there are None.
{
action key: [[handled this frame, action type, time], [...]],
K_m: [[1, KEYDOWN]], ## Keydown at _this_ frame
K_f: [[1, KEYHOLD]], ## Keydown at sometime before, held since then
K_g: [[1, KEYDOWN], ## Keydown and Keyup _this_ frame
[0, KEYUP]]
}
"Handled this frame" will be set to 1 if an EventListener runs a reaction for that event. This prevents multiple
EventListeners from running reactions for the same event.
"""
def __init__(self, *args):
super(EventRecord, self).__init__(*args)
def update_frame(self):
"""Update the EventRecord to reflect the curret events at the beginning of the frame.
Updating Rules:
1) Set all of the events to unhandled this frame.
2) Update times of HOLDs.
3) If there are any UP events for an action key, remove all events.
4) If there are any DOWN events for an action key, replace each one with the equivalent HOLD action type at time of DOWN.
5) If there are any posted events, remove them.
Return: None
"""
for key in self.keys():
events = self[key]
i = 0
remove = []
remove_all = False
for event in events:
event[0] = 0
## Remove leading NOEVENTS
if event[1] == constants.NOEVENT:
if i == 0 and len(events) > 1:
remove.append(i)
i += 1
continue
if event[1] == constants.MOUSEMOTION:
remove.append(i)
i += 1
continue
## Ignore Holds
if (event[1] - 2) & (event[1] - 3) == 0:
i+= 1
continue
## Change "Ups" to "NOEVENTS"
if (event[1] - 1) & (event[1] - 2) == 0:
remove_all = True
break
## Change "Downs" to "Holds"
if event[1] & (event[1]-1) == 0:
self[key][i] = [0, event[1]+2]
i += 1
continue
## Remove "Posted"
if (event[1] - 3) & (event[1] - 4) == 0:
remove.append(i)
i += 1
continue
if (event[1] - 4) & (event[1] - 5) == 0:
remove.append(i)
continue
if (event[1] - 5) & (event[1] - 6) == 0:
remove.append(i)
i += 1
continue
i += 1
if remove_all:
del self[key]
if remove == []:
continue
offset = 0
for j in remove:
del self[key][j - offset]
offset += 1
if len(events) == 0:
del self[key]
def add(self, action_key, action_type):
"""Add an event to the EventRecord.
Adding Rules:
1) If adding a NOEVENT, just return
2) Set "handled" to 0 in every case.
3) If there isn't a key for action_key yet, create it.
All other rules handle collisions:
1) If there is a single NOEVENT, overwrite it.
Adding UP:
1) If the last event is a HOLD, overwrite the last event
2) In any other situation, just append the UP event.
Return: None
"""
if action_type == constants.NOEVENT:
return
if not self.has_key(action_key):
self[action_key] = []
events = self[action_key]
## Handle single NOEVENT
if len(events) == 1 and events[0][1] == constants.NOEVENT:
self[action_key] = []
## Ups
if (action_type-1) & (action_type-2) == 0:
## Overwrite HOLDS
try:
if (events[-1][1]-2) & (events[-1][1]-3) == 0:
self[action_key] = self[action_key][:-1]
except IndexError:
pass
self[action_key].append([0, action_type])
def add_posted(self, posted):
for key in posted.keys():
if not self.has_key(key):
self[key] = []
for event in posted[key]:
self[key].append(event)
class Mods(object):
"""Holds information about modifiers for bound actions."""
def __init__(self, include=[], exclude=[]):
self.include = set(include)
self.exclude = set(exclude)
def match(self, record):
"""Return True actions in iterable work with self.include and self.exclude.
Arguments:
record - the EventRecord to check against.
Return: boolean
"""
if len(self.include) == 0 and len(self.exclude) == 0:
return True
for i in self.include:
if i not in record:
return False
#try:
# if record[i][-1][1] == constants.NOEVENT:
# return False
#except (TypeError, KeyError):
# return False
for i in self.exclude:
if i in record:
#if record[i][-1][1] == constants.NOEVENT:
# continue
return False
return True
class EventListener(dict):
"""Delegates reactions to bound events.
{
(K_l, KEYDOWN): {
Mods: [delay, last_event, [(function, args), (function, args)]],
Mods: [delay, last_event, [(function, args), (function, args)]]
},
(K_a, KEYHOLD): {
ModifierPair: [delay, last_event, [(function, args), (function, args)]]
}
}
"""
def __init__(self, parent=None):
super(EventListener, self).__init__()
self.parent = None
def bind(self, callback, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None, delay=0, args=()):
"""Bind an action to the EventListener.
Return: None
"""
if act_type == constants.NOEVENT:
return
action = (act_key, act_type)
if not self.has_key(action):
self[action] = {}
dest = None
if mods is None:
mods = Mods()
for modpair in self[action]:
if modpair.include == mods.include and modpair.exclude == mods.exclude:
dest = self[action][modpair]
break
if dest is None:
self[action][mods] = [delay, -delay, []]
dest = self[action][mods]
dest[2].append((callback, args))
def unbind(self, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None):
"""Unbind an action from the EventListner.
If modpair is None, unbind all.
Return: None
"""
if act_key == constants.K_NONE and act_type == constants.NOEVENT:
return
action = (act_key, act_type)
if not self.has_key(action):
if act_key == constants.K_NONE:
actions = []
for key in self.keys():
if key[0] == act_key:
actions.append(key)
for action in actions:
self._unbind(action, mods)
return
if act_type == constants.NOEVENT:
actions = []
for key in self.keys():
if key[1] == act_type:
actions.append(key)
for action in actions:
self._unbind(action, mods)
return
raise KeyError, "Action {0} not bound.".format(action)
self._unbind(action, mods)
def _unbind(self, action, mods):
if mods is None:
self[action] = {}
return
if not self[action].has_key(mods):
raise KeyError, "Action {0} bound, but ModifierPair {1} is not.".format(action, mods)
del self[action][mods]
def process(self):
"""Handle event processing for the current frame.
1) Go through all events in the EventRecord and run bound reactions (check if event has been handled by a child, then check mods).
2) If there is a parent, let it handle te rest of the EventRecord
Return: None
"""
keys = RECORD.keys()
for key in keys:
event_number = 0
for event in RECORD[key]:
if event[0] == 1:
event_number += 1
continue
action = (key, event[1])
if action[1] == constants.NOEVENT:
event[0] = 1
event_number += 1
continue
if not self.has_key(action):
actionp = (key, event[1] - 3)
if self.has_key(actionp):
action = actionp
else:
event_number += 1
continue
for modpair in self[action].keys():
if modpair.match(RECORD):
## Check delays
if core._Data.current_time < self[action][modpair][0] + self[action][modpair][1]:
break
self[action][modpair][1] = core._Data.current_time
## Run bound methods
for bound in self[action][modpair][2]:
bound[0](*bound[1])
RECORD[key][event_number][0] = 1
break
event_number += 1
if self.parent is not None:
self.parent.process()
def process():
"""Handle event processing for the current frame.
Return: None
"""
RECORD.update_frame()
for event in _BACKEND.poll():
RECORD.add(event[0], event[1])
RECORD.add_posted(POSTED)
POSTED.clear()
core._Data.eventlistener.process()
def post(action_key, action_type):
"""Manually add an event to be processed.
Return: None
"""
if action_type == constants.NOEVENT:
return
if not POSTED.has_key(action_key):
POSTED[action_key] = []
POSTED[action_key].append([0, action_type + 3, core._Data.current_time])
def bind(callback, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None, delay=0, args=()):
"""Shortcut for binding an action to the current EventListener.
Return: None
"""
core._Data.eventlistener.bind(callback, act_key, act_type, mods, delay, args)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
SCREEN_BLOCK_DRAW = 1<<0
SCREEN_CULL_SPRITES = 1<<1
SCREEN_DRAW_TEXTURES = 1<<2 ## Draws outline of Sprites
SCREEN_DRAW_MESHES = 1<<3 ## Outlines all of the Meshes
SCREEN_DRAW_WIREFRAME = 1<<4 ## Outlines bounding areas of Sprites
POLYGON_STATIC = 1<<0
POLYGON_AXIS_ALIGNED = 1<<1
POLYGON_MUTABLE_LENGTH = 1<<2
TIME_PAUSED = 1<<0
## Action Types
## Powers of 2 are "downs"
## (Powers of 2)+1 are "ups"
## (Powers of 2)+2 are "holds"
## (Powers of 2)+3 are the same as "downs" (removed Frame after)
## (Powers of 2)+4 are "ups" (removed Frame after)
## (Powers of 2)+5 are the same as "holds" (removed Frame after)
NOEVENT = 0
QUIT = -2
VIDEOEXPOSE = -3
VIDEORESIZE = -5
KEYDOWN = 8
KEYUP = 9
KEYHOLD = 10
MOUSEMOTION = 15
MOUSEBUTTONDOWN = 16
MOUSEBUTTONUP = 17
MOUSEBUTTONHOLD = 18
SCROLLWHEEL = MOUSEBUTTONDOWN
TIMERSTART = 32
TIMEREND = 33
TIMERTICK = 34
JOYAXISMOTION = 0
JOYBALLMOTION = 0
JOYHATMOTION = 0
JOYBUTTONUP = 0
JOYBUTTONDOWN = 0
## Action Keys
K_NONE = -1
K_ALT = 768
K_CAPS = 8192
K_CTRL = 192
K_LALT = 256
K_LCTRL = 64
K_LMETA = 1024
K_LSHIFT = 1
K_META = 3072
K_NUM = 4096
K_RALT = 512
K_RCTRL = 128
K_RMETA = 2048
K_RSHIFT = 2
K_SHIFT = 3
K_0 = 48
K_1 = 49
K_2 = 50
K_3 = 51
K_4 = 52
K_5 = 53
K_6 = 54
K_7 = 55
K_8 = 56
K_9 = 57
K_AMPERSAND = 38
K_ASTERISK = 42
K_AT = 64
K_BACKQUOTE = 96
K_BACKSLASH = 92
K_BACKSPACE = 8
K_BREAK = 318
K_CAPSLOCK = 301
K_CARET = 94
K_CLEAR = 12
K_COLON = 58
K_COMMA = 44
K_DELETE = 127
K_DOLLAR = 36
K_DOWN = 274
K_END = 279
K_EQUALS = 61
K_ESCAPE = 27
K_EURO = 321
K_EXCLAIM = 33
K_F1 = 282
K_F10 = 291
K_F11 = 292
K_F12 = 293
K_F13 = 294
K_F14 = 295
K_F15 = 296
K_F2 = 283
K_F3 = 284
K_F4 = 285
K_F5 = 286
K_F6 = 287
K_F7 = 288
K_F8 = 289
K_F9 = 290
K_FIRST = 0
K_GREATER = 62
K_HOME = 278
K_INSERT = 277
K_KP0 = 256
K_KP1 = 257
K_KP2 = 258
K_KP3 = 259
K_KP4 = 260
K_KP5 = 261
K_KP6 = 262
K_KP7 = 263
K_KP8 = 264
K_KP9 = 265
K_KP_DIVIDE = 267
K_KP_ENTER = 271
K_KP_EQUALS = 272
K_KP_MINUS = 269
K_KP_MULTIPLY = 268
K_KP_PERIOD = 266
K_KP_PLUS = 270
K_LAST = 323
K_LEFT = 276
K_LEFTBRACKET = 91
K_LEFTPAREN = 40
K_LESS = 60
K_LSUPER = 311
K_MENU = 319
K_MINUS = 45
K_MODE = 313
K_NUMLOCK = 300
K_PAGEDOWN = 281
K_PAGEUP = 280
K_PAUSE = 19
K_PERIOD = 46
K_PLUS = 43
K_POWER = 320
K_PRINT = 316
K_QUESTION = 63
K_QUOTE = 39
K_QUOTEDBL = 34
K_RETURN = 13
K_RIGHT = 275
K_RIGHTBRACKET = 93
K_RIGHTPAREN = 41
K_RSUPER = 312
K_SCROLLOCK = 302
K_SEMICOLON = 59
K_SLASH = 47
K_SPACE = 32
K_SYSREQ = 317
K_TAB = 9
K_UNDERSCORE = 95
K_UNKNOWN = 0
K_UP = 273
K_a = 97
K_b = 98
K_c = 99
K_d = 100
K_e = 101
K_f = 102
K_g = 103
K_h = 104
K_i = 105
K_j = 106
K_k = 107
K_l = 108
K_m = 109
K_n = 110
K_o = 111
K_p = 112
K_q = 113
K_r = 114
K_s = 115
K_t = 116
K_u = 117
K_v = 118
K_w = 119
K_x = 120
K_y = 121
K_z = 122
MB_1 = -11
MB_2 = -12
MB_3 = -13
MS_DOWN = -14
MS_UP = -15
M_MOTION = -16
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
| Python |
#!/usr/bin/env python
from distutils.core import setup, Extension
import os
## Windows (32), Python 2.6, with GCC (MinGW or Cygwin) Only, for now
if os.name == "nt":
## Constants
library_dirs = [os.path.abspath('lib/win32')]
include_dirs = [os.path.abspath('ext/include'), os.path.abspath(os.path.join(os.sys.exec_prefix + 'include'))]
## Configure Extensions
fltime = Extension('fltime', include_dirs=include_dirs,
sources=['ext/fltime.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/fltime.lib,--export-all-symbols'])
flmath = Extension('flmath', include_dirs=include_dirs,
sources=['ext/flmath.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/flmath.lib,--export-all-symbols'])
flcolor = Extension("flcolor", include_dirs=include_dirs,
sources=['ext/flcolor.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/flcolor.lib,--export-all-symbols'])
image = Extension('image', libraries=['opengl32', 'glu32', 'DevIL', 'ILU'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/image.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/image.lib,--export-all-symbols'])
mesh = Extension('mesh', libraries=['flmath'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/mesh.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/mesh.lib,--export-all-symbols'])
sprite = Extension('sprite', libraries=['flcolor', 'flmath', 'image', 'mesh'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/sprite.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/sprite.lib,--export-all-symbols'])
screen = Extension('screen', libraries=['opengl32', 'SDL', 'flcolor', 'flmath', 'sprite'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/screen.c'])
ext_modules = [fltime, flmath, flcolor, image, mesh, sprite, screen]
elif os.name == "mac":
pass
elif os.name == "posix":
pass
## Setup
if __name__ == "__main__":
setup(ext_modules=ext_modules)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
class _Data(object):
"""Contains data necessary to run the Game.
All instances share the same state, so every instance created will
have exact replicas of the data. They will also all update their
data automatically if you change the data in one instance.
"""
_shared_state = {}
def __init__(self):
self.__dict__ = self._shared_state
##-------- Metadata
fl_version = "0.1.0"
fl_author = "Bradley Zeis"
fl_author_email = "flamingoengine@gmail.com"
fl_copyright = "2009 Bradley Zeis"
fl_url = "http://flamingoengine.googlecode.com/"
game_name = ""
game_version = ""
game_author = ""
game_author_email = ""
game_copyright = ""
game_url = ""
##-------- File Data
##-------- Screen Data
screen_title = "flamingo - {0}".format(fl_version)
screen_size = None
fullscreen = False
screens = []
painter = None
master_eventlistener = None
eventlistener = None
##-------- Clock Data
master_clock = None
logic_clock = None
render_clock = None
logic_fps = 64
current_time = 0
delta_time = 0 ## Time delta between current frame and last frame.
##-------- Caches
tex_cache = {}
##-------- Game Data
master_spr_group = None
spr_groups = []
usr_groups = []
@classmethod
def clear(cls):
cls.master_spr_group.empty()
for grp in cls.spr_groups:
grp.empty()
for grp in cls.usr_groups:
grp.empty()
cls.spr_groups = []
cls.usr_groups = []
##-------- Global Names
GAME = None
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""
Terms:
Action - Something that happens generally, not something specific.
Event - A specific instance of an action that is placed in the EventRecord.
Frame - One cycle of even processing. Events are handled once per display frame.
Reaction - A callback called because of a specific event. You 'bind' reactions to EventListeners.
Modifiers - Events that 'modify' reactions. For example, pressing shift can cause a
different reaction for mouse clicks.
All times are the time of the frame when the events are handled, not the time when the event occurred. Backends
do not need to worry about what time the even happened, they just need to preserve order. (The frontend gets
the time from core._Data.current_time)
Event backends must define:
init()
poll()
"""
import sys
from . import constants
from . import core
_BACKEND = None
_INITIALIZED = False
RECORD = None
POSTED = {}
def load(event_name):
"""Load an event backend.
If the event backend has already been initialized, there will be no effect.
Return: None
"""
if _INITIALIZED:
return
try:
global _BACKEND
__import__(event_name)
_BACKEND = sys.modules[event_name]
except ImportError:
raise ImportError, "could not import backend '{0}'".format(event_name)
def init():
"""Initialize the event backend.
If a backend is not loaded before this is called, an AttributeError is raised.
Backend:
Backends should not change the values of display._BACKEND or display._INITIALIZED
Return: None
"""
try:
_BACKEND.init()
except AttributeError:
raise AttributeError, "an event backend has not been loaded"
global RECORD
RECORD = EventRecord()
class EventRecord(dict):
"""Store a record of the current events for an action key, and the last event that happened if there are None.
{
action key: [[handled this frame, action type, time], [...]],
K_m: [[1, KEYDOWN]], ## Keydown at _this_ frame
K_f: [[1, KEYHOLD]], ## Keydown at sometime before, held since then
K_g: [[1, KEYDOWN], ## Keydown and Keyup _this_ frame
[0, KEYUP]]
}
"Handled this frame" will be set to 1 if an EventListener runs a reaction for that event. This prevents multiple
EventListeners from running reactions for the same event.
"""
def __init__(self, *args):
super(EventRecord, self).__init__(*args)
def update_frame(self):
"""Update the EventRecord to reflect the curret events at the beginning of the frame.
Updating Rules:
1) Set all of the events to unhandled this frame.
2) Update times of HOLDs.
3) If there are any UP events for an action key, remove all events.
4) If there are any DOWN events for an action key, replace each one with the equivalent HOLD action type at time of DOWN.
5) If there are any posted events, remove them.
Return: None
"""
for key in self.keys():
events = self[key]
i = 0
remove = []
remove_all = False
for event in events:
event[0] = 0
## Remove leading NOEVENTS
if event[1] == constants.NOEVENT:
if i == 0 and len(events) > 1:
remove.append(i)
i += 1
continue
if event[1] == constants.MOUSEMOTION:
remove.append(i)
i += 1
continue
## Ignore Holds
if (event[1] - 2) & (event[1] - 3) == 0:
i+= 1
continue
## Change "Ups" to "NOEVENTS"
if (event[1] - 1) & (event[1] - 2) == 0:
remove_all = True
break
## Change "Downs" to "Holds"
if event[1] & (event[1]-1) == 0:
self[key][i] = [0, event[1]+2]
i += 1
continue
## Remove "Posted"
if (event[1] - 3) & (event[1] - 4) == 0:
remove.append(i)
i += 1
continue
if (event[1] - 4) & (event[1] - 5) == 0:
remove.append(i)
continue
if (event[1] - 5) & (event[1] - 6) == 0:
remove.append(i)
i += 1
continue
i += 1
if remove_all:
del self[key]
if remove == []:
continue
offset = 0
for j in remove:
del self[key][j - offset]
offset += 1
if len(events) == 0:
del self[key]
def add(self, action_key, action_type):
"""Add an event to the EventRecord.
Adding Rules:
1) If adding a NOEVENT, just return
2) Set "handled" to 0 in every case.
3) If there isn't a key for action_key yet, create it.
All other rules handle collisions:
1) If there is a single NOEVENT, overwrite it.
Adding UP:
1) If the last event is a HOLD, overwrite the last event
2) In any other situation, just append the UP event.
Return: None
"""
if action_type == constants.NOEVENT:
return
if not self.has_key(action_key):
self[action_key] = []
events = self[action_key]
## Handle single NOEVENT
if len(events) == 1 and events[0][1] == constants.NOEVENT:
self[action_key] = []
## Ups
if (action_type-1) & (action_type-2) == 0:
## Overwrite HOLDS
try:
if (events[-1][1]-2) & (events[-1][1]-3) == 0:
self[action_key] = self[action_key][:-1]
except IndexError:
pass
self[action_key].append([0, action_type])
def add_posted(self, posted):
for key in posted.keys():
if not self.has_key(key):
self[key] = []
for event in posted[key]:
self[key].append(event)
class Mods(object):
"""Holds information about modifiers for bound actions."""
def __init__(self, include=[], exclude=[]):
self.include = set(include)
self.exclude = set(exclude)
def match(self, record):
"""Return True actions in iterable work with self.include and self.exclude.
Arguments:
record - the EventRecord to check against.
Return: boolean
"""
if len(self.include) == 0 and len(self.exclude) == 0:
return True
for i in self.include:
if i not in record:
return False
#try:
# if record[i][-1][1] == constants.NOEVENT:
# return False
#except (TypeError, KeyError):
# return False
for i in self.exclude:
if i in record:
#if record[i][-1][1] == constants.NOEVENT:
# continue
return False
return True
class EventListener(dict):
"""Delegates reactions to bound events.
{
(K_l, KEYDOWN): {
Mods: [delay, last_event, [(function, args), (function, args)]],
Mods: [delay, last_event, [(function, args), (function, args)]]
},
(K_a, KEYHOLD): {
ModifierPair: [delay, last_event, [(function, args), (function, args)]]
}
}
"""
def __init__(self, parent=None):
super(EventListener, self).__init__()
self.parent = None
def bind(self, callback, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None, delay=0, args=()):
"""Bind an action to the EventListener.
Return: None
"""
if act_type == constants.NOEVENT:
return
action = (act_key, act_type)
if not self.has_key(action):
self[action] = {}
dest = None
if mods is None:
mods = Mods()
for modpair in self[action]:
if modpair.include == mods.include and modpair.exclude == mods.exclude:
dest = self[action][modpair]
break
if dest is None:
self[action][mods] = [delay, -delay, []]
dest = self[action][mods]
dest[2].append((callback, args))
def unbind(self, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None):
"""Unbind an action from the EventListner.
If modpair is None, unbind all.
Return: None
"""
if act_key == constants.K_NONE and act_type == constants.NOEVENT:
return
action = (act_key, act_type)
if not self.has_key(action):
if act_key == constants.K_NONE:
actions = []
for key in self.keys():
if key[0] == act_key:
actions.append(key)
for action in actions:
self._unbind(action, mods)
return
if act_type == constants.NOEVENT:
actions = []
for key in self.keys():
if key[1] == act_type:
actions.append(key)
for action in actions:
self._unbind(action, mods)
return
raise KeyError, "Action {0} not bound.".format(action)
self._unbind(action, mods)
def _unbind(self, action, mods):
if mods is None:
self[action] = {}
return
if not self[action].has_key(mods):
raise KeyError, "Action {0} bound, but ModifierPair {1} is not.".format(action, mods)
del self[action][mods]
def process(self):
"""Handle event processing for the current frame.
1) Go through all events in the EventRecord and run bound reactions (check if event has been handled by a child, then check mods).
2) If there is a parent, let it handle te rest of the EventRecord
Return: None
"""
keys = RECORD.keys()
for key in keys:
event_number = 0
for event in RECORD[key]:
if event[0] == 1:
event_number += 1
continue
action = (key, event[1])
if action[1] == constants.NOEVENT:
event[0] = 1
event_number += 1
continue
if not self.has_key(action):
actionp = (key, event[1] - 3)
if self.has_key(actionp):
action = actionp
else:
event_number += 1
continue
for modpair in self[action].keys():
if modpair.match(RECORD):
## Check delays
if core._Data.current_time < self[action][modpair][0] + self[action][modpair][1]:
break
self[action][modpair][1] = core._Data.current_time
## Run bound methods
for bound in self[action][modpair][2]:
bound[0](*bound[1])
RECORD[key][event_number][0] = 1
break
event_number += 1
if self.parent is not None:
self.parent.process()
def process():
"""Handle event processing for the current frame.
Return: None
"""
RECORD.update_frame()
for event in _BACKEND.poll():
RECORD.add(event[0], event[1])
RECORD.add_posted(POSTED)
POSTED.clear()
core._Data.eventlistener.process()
def post(action_key, action_type):
"""Manually add an event to be processed.
Return: None
"""
if action_type == constants.NOEVENT:
return
if not POSTED.has_key(action_key):
POSTED[action_key] = []
POSTED[action_key].append([0, action_type + 3, core._Data.current_time])
def bind(callback, act_key=constants.K_NONE, act_type=constants.NOEVENT, mods=None, delay=0, args=()):
"""Shortcut for binding an action to the current EventListener.
Return: None
"""
core._Data.eventlistener.bind(callback, act_key, act_type, mods, delay, args)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo v0.1.0
Flamingo is an advanced 2d game engine written on top of pygame
<www.pygame.org>. Flamingo goes a step beyond other game engines
written in Python by supplying _all_ necessary tools for the
development of a game allowing the developer to focus on content
instead of the engine.
Dependencies:
Python - <www.python.org> - 2.x series, 2.5+
pygame - <www.pygame.org> - 1.9.x
PyOpenGL - <pyopengl.sourceforge.com> - 3.0.x
pybox2d - <pybox2d.googlecode.com> - 2.0.2b1
numpy - <numpy.scipy.org> - 1.3.x
PIL - <> - 1.1.x
"""
## Define constants
__version__ = "0.1.0"
__author__ = "Bradley Zeis"
import os
fl_path = os.path.split(__file__)[0]
## Import flamingo modules
import constants
import backends
import fltime
import flcolor
import flmath
import image
import mesh
import sprite
import screen
import core
import util
import event
import objects
import audio
import game
## Import/Check dependencies
try:
import pygame
import Box2D as box2d
import numpy
import OpenGL
if pygame.__version__[:3] != '1.9':
raise ImportError, "Wrong pygame version (1.9.x required). Version {0} found."\
.format(pygame.__version__)
if box2d.__version__ != '2.0.2b1':
raise ImportError, "Wrong pybox2d version (2.0.2b1 required). Version {0} found."\
.format(box2d.__version__)
if numpy.version.version[:3] != '1.3':
raise ImportError, "Wrong numpy version (1.3.x required). Version {0} found."\
.format(numpy.version.version)
if OpenGL.version.__version__[:3] != '3.0':
raise ImportError, "Wrong pyOpenGL version (3.0.x required). Version {0} found."\
.format(OpenGL.version.__version__)
except ImportError, err:
raise ImportError, err
__all__ = ["constants", "backends",
"flcolor", "fltime", "flmath", "image", "mesh",
"sprite", "screen",
"core", "util", "event", "objects", "audio", "game"]
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""The core Game related classes and functions."""
import sys
import os
import thread
import math
import constants
import fltime
import core
import display
import util
import flmath
import event
import image
import sprite
import objects
import audio
import screen
import OpenGL.GL as gl
class Game(object):
"""Base class used to create Games."""
def __init__(self):
core.GAME = self
self.data = core._Data
self.data.screen_size = (800, 600)
self.data.master_spr_group = sprite._MasterGroup()
self.data.painter = screen.Painter()
self.data.master_clock = fltime.Clock()
self.data.render_clock = fltime.Clock()
self.data.logic_clock = fltime.Clock()
fltime._set_master_clock(self.data.master_clock)
self.data.master_eventlistener = event.EventListener()
self.data.eventlistener = self.data.master_eventlistener
## Open ini file(s) here to load settings.
audio.load("flamingo.backends.audio.pygame_mixer")
def run(self, start_game, flags, *args):
"""Runs the entire application.
Returns: None
"""
self._run_init()
self.init(*args)
self.start_main(start_game)
##-------- Initialization
def _run_init(self):
"""Initialize the application before running.
Returns: None
"""
display.load('flamingo.backends.display.pygame_display',
'flamingo.backends.event.pygame_event')
display.init(800, 600, self.data.screen_title)
## OpenGL
gl.glShadeModel(gl.GL_SMOOTH)
gl.glClearColor(0, 0, 0, 1)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glDisable(gl.GL_LIGHTING)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(gl.GL_POINT_SMOOTH)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glEnable(gl.GL_POLYGON_SMOOTH)
# Flamingo
self.data.eventlistener.bind(self.quit_all, constants.QUIT, constants.QUIT)
audio.mixer.init()
self.quit = False
def init(self, *args):
"""User initialization.
Returns: None
"""
pass
##-------- Screens
def add_screen(self, screen):
"""Add a Screen to the stack.
screen - (Screen)
Returns: None
"""
self.data.screens.append(screen)
def rem_screen(self, screen):
"""Remove a Screen from the stack.
screen - (Screen)
Returns: None
"""
self.data.screens.remove(screen)
##--------- Startup
def start_main(self, start_game=False):
"""Runs the entire program.
Returns: None
"""
## Initialize
## Main Loop
#audio.mixer.start()
if start_game:
self.start_game()
self._gameloop()
## Tear Down
def start_game(self):
"""Starts the threads relating to the game itself.
Returns: None
"""
pass
##-------- Loop/Quitting
def _gameloop(self):
"""The main game loop.
Returns: None
"""
self.data.master_clock.init()
self.data.logic_clock.init()
self.data.render_clock.init()
self.quit = False
self.data.current_time = self.data.master_clock.ticks()
timestep = 1.0 / self.data.logic_fps
accumulator = 0
while not self.quit:
self.data.master_clock.sync()
newTime = self.data.master_clock.ticks()
self.data.delta_time = newTime - self.data.current_time
self.data.current_time = newTime
fltime._timer_sync(self.data.current_time)
accumulator += self.data.delta_time
## Process Input
event.process()
if self.quit:
break
## Update Physics/Objects
while accumulator>=timestep:
accumulator -= timestep
# Physics step
for group in self.data.spr_groups:
group.update(self.data.delta_time)
self.data.master_spr_group.update()
## Render
#if not audio.mixer.THREADED:
# audio.mixer.Mixer.tick(self.data.delta_time)
#self.data.screens[0].orientation += .01
self.data.render_clock.sync()
interpolation = accumulator / timestep
self.data.painter.draw(interpolation)
display.flip()
#print fltime.ticks_to_seconds(self.data.current_time)
def quit_game(self):
"""Exits the main loop of the program without killing everything.
Returns: None
"""
self.quit = True
self.data.clear()
def quit_all(self):
"""Kills the entire application cleanly.
Returns: None
"""
self.quit = True
sys.exit()
| Python |
#!/usr/bin/env python
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import sys
from . import event
_BACKEND = None
_INITIALIZED = False
def load(display_name, event_name):
"""Load a display backend.
If the display backend has already been initialized, there will be no effect.
Return: None
"""
if _INITIALIZED:
return
try:
global _BACKEND
__import__(display_name)
_BACKEND = sys.modules[display_name]
event.load(event_name)
event.init()
except ImportError:
raise ImportError, "could not import backend '{0}'".format(display_name)
def init(width, height, caption, fullscreen=0, depth=0, flags=0):
"""Initialize the display.
If a backend is not loaded before this is called, an AttributeError is raised.
Backend:
Backends should not change the values of display._BACKEND or display._INITIALIZED
Return: None
"""
try:
_BACKEND.init(width, height, caption, fullscreen, flags, depth)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
Display.width = width
Display.height = height
Display.caption = caption
Display.fullscreen = fullscreen
Display.depth = 0
Display.flags = 0
def get_init():
"""Return true if the display is initialized.
Return: boolean
"""
return _INITIALIZED
def quit():
"""Quit the display.
If a backend is not loaded before this is called, an AttributeError is raised.
Return: None
"""
try:
_BACKEND.quit()
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
Display.clear()
def flip():
"""Update the contents on the display surface.
If a backend is not loaded, an AttributeError will be raised.
Return: None
"""
try:
_BACKEND.flip()
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
def get_size():
"""Get the caption of the display window.
Return: string
"""
return Display.width, Display.height
def set_size(width, height):
"""Set the size of the display window.
If the display size can't be changed by the current backend, the backend should
do nothing instead of raising an exception.
Return: None
"""
try:
_BACKEND.set_caption(width, height)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
def get_caption():
"""Get the caption of the display window.
Return: string
"""
return Display.caption
def set_caption(caption):
"""Set the caption of the display window.
Return: None
"""
try:
_BACKEND.set_caption(caption)
except AttributeError:
raise AttributeError, "a display backend has not been loaded"
class Display(object):
"""Holds information about the display surface."""
width = 0
height = 0
caption = ""
fullscreen = 0
depth = 0
flags = 0
@classmethod
def clear(cls):
width = 0
height = 0
caption = 0
fullscreen = 0
depth = 0
flags = 0
| Python |
#!/usr/bin/env python
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
| Python |
#!/usr/bin/env python
"""Unit Tests for fmath.py"""
import unittest
import flamingo.fmath as fmath
import math
import pickle
from numbers import Number
class TestPow(unittest.TestCase):
def setUp(self):
self.data = [2, 3, 4, 7, 17, 710, 483, 60495, 712345]
self.bad = ["hello world!", [1, 2, 3], {'foo': 'bar'},
fmath.Vector([1, 1])]
def testClosestIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.closest_pow2(d),
Number))
def testClosestIsPow2(self):
for d in self.data:
result = fmath.closest_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testClosestIsOne(self):
for d in self.data:
self.assertTrue(fmath.closest_pow2(d) >= 1)
def testClosestIsClosest(self):
for d in self.data:
less = math.pow(2, math.ceil(math.log(d)/math.log(2.0)))
greater = math.pow(2, math.floor(math.log(d)/math.log(2.0)))
lessd = d - less
greaterd = greater - d
if lessd < greaterd:
self.assertEqual(fmath.closest_pow2(d), greater)
else:
self.assertEqual(fmath.closest_pow2(d), less)
def testClosestBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.closest_pow2, b)
def testClosestNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.closest_pow2, -d)
def testNextIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.next_pow2(d),
Number))
def testNextIsPow2(self):
for d in self.data:
result = fmath.next_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testNextIsOne(self):
for d in self.data:
self.assertTrue(fmath.next_pow2(d) >= 1)
def testNextGreater(self):
for d in self.data:
result = fmath.next_pow2(d)
self.assertTrue(result >= d)
def testNextBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.next_pow2, b)
def testNextNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.next_pow2, -d)
def testPrevIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.prev_pow2(d),
Number))
def testPrevIsPow2(self):
for d in self.data:
result = fmath.prev_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testPrevIsOne(self):
for d in self.data:
self.assertTrue(fmath.prev_pow2(d) >= 1)
def testPrevLess(self):
for d in self.data:
result = fmath.prev_pow2(d)
if result is None:
self.assertTrue(False)
self.assertTrue(result <= d)
def testPrevBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.prev_pow2, b)
def testPrevNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.prev_pow2, -d)
class TestDistance(unittest.TestCase):
def setUp(self):
## data = [[point, point, distance, distance_sq]]
self.data = [[(0, 0), (0, 1), 1, 1],
[(2.5, 2),(4.76, 3.1), 2.5134, 6.3176],
[(10, 16),(100, 160), 169.8116, 28836],
[fmath.Vector([1.2, 1]), fmath.Vector([16, 1]), 14.8, 219.04],
[(0, 0), (0, 0), 0, 0],
[fmath.Vector([0, 0]), fmath.Vector([0, 0]), 0, 0]]
self.long = [[(21, 4, 6, 4, 3), (14, 16, 71, 723, 5)],
[(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)],
[(1, 2, 3, 4), (5, 4, 3, 2, 1)]]
self.short = [[(), ()]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.distance(d[0], d[1]),
Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(fmath.distance(d[0], d[1]) >= 0)
def testValue(self):
for d in self.data:
result = fmath.distance(d[0], d[1])
self.assertEquals(round(result, 2), round(d[2], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.distance, b[0],b[1])
##-------- Sq
def testIsNumberSq(self):
for d in self.data:
self.assertTrue(isinstance(fmath.distance_sq(d[0], d[1]),
Number))
def testIsPosSq(self):
for d in self.data:
self.assertTrue(fmath.distance_sq(d[0], d[1]) >= 0)
def testValueSq(self):
for d in self.data:
result = fmath.distance_sq(d[0], d[1])
self.assertEquals(round(result, 2), round(d[3], 2))
def testBadSq(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.distance_sq, b[0],b[1])
class TestMidpoint(unittest.TestCase):
def setUp(self):
## data = [[point, point, midpoint]]
self.data = [[(0, 0), (0, 1), (0, 0.5)],
[(2.5, 2),(4.76, 3.1), (3.63, 2.55)],
[(10, 16),(100, 160), (55, 88)],
[fmath.Vector([1.13, 1]), (16, 1), (8.565, 1)],
[(0, 0), (0, 0), (0, 0)]]
self.wrong = [[(), ()],
[(2,), (1,)]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testValue(self):
for d in self.data:
result = fmath.midpoint(d[0], d[1])
self.assertEquals(round(result[0]), round(d[2][0]))
self.assertEquals(round(result[1]), round(d[2][1]))
def testWrong(self):
for d in self.wrong:
self.assertRaises(TypeError,
fmath.midpoint, d[0], d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.midpoint, b[0],b[1])
class TestArea(unittest.TestCase):
def setUp(self):
## [[data], area, signed_area]
self.data = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], 4, 4],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], 4, -4],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], 1002.66, 1002.66 ],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], 1002.66, -1002.66 ]]
self.odata = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], True],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], False],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], True],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], False]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}],
[(1,), (2,), (3,)],
[(1, 2), (3, 4)],
[(1, 2)],
[]]
##-------- Pos Area
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.area(d[0]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(fmath.area(d[0]) > 0)
def testValue(self):
for d in self.data:
result = fmath.area(d[0])
self.assertEquals(round(result, 2), round(d[1], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.area, b)
##-------- Signed Area
def testIsNumberS(self):
for d in self.data:
self.assertTrue(isinstance(fmath.signed_area(d[0]), Number))
def testValueS(self):
for d in self.data:
result = fmath.signed_area(d[0])
self.assertEquals(round(result, 2), round(d[2], 2))
def testBadS(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.signed_area, b)
##-------- Orientation
def testValueO(self):
for d in self.odata:
result = fmath.orientation_poly(d[0])
self.assertEquals(result, d[1])
def testBadO(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.orientation_poly, b)
class TestNormalizeAngle(unittest.TestCase):
def setUp(self):
self.datad = [[45, 45],
[360, 0],
[400, 40],
[4000, 40],
[-100, 260]]
self.datar = [[math.radians(45), math.radians(45)],
[math.radians(360), math.radians(0)],
[math.radians(400), math.radians(40)],
[math.radians(4000), math.radians(40)],
[math.radians(-100), math.radians(260)]]
self.bad = ["meow",
[16],
{'foo': 'bar'}]
##-------- Degress
def testNumber(self):
for i in range(0, 1000):
self.assertTrue(isinstance(fmath.normalize_angle(i),
Number))
def testIsPos(self):
for i in range(0, 1000):
self.assertTrue(fmath.normalize_angle(i) >= 0)
def testValue(self):
for d in self.datad:
self.assertEquals(fmath.normalize_angle(d[0]), d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.normalize_angle, b)
##-------- Radians
def testNumberR(self):
for i in range(0, 1000):
self.assertTrue(isinstance(fmath.normalize_angler(i),
Number))
def testIsPosR(self):
for i in range(0, 1000):
self.assertTrue(fmath.normalize_angler(i) >= 0)
def testValueR(self):
for d in self.datar:
self.assertAlmostEquals(fmath.normalize_angler(d[0]), d[1])
def testBadR(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.normalize_angler, b)
class TestNormalizePoly(unittest.TestCase):
def setUp(self):
self.p = [fmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1)]
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testNormalize(self):
self.assert_(fmath.normalize_poly(self.p) == self.p)
p = [fmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1), (-1, 1)]
self.assert_(fmath.normalize_poly(p) == self.p)
self.assert_(fmath.normalize_poly(self.p, 1) == p)
p = [(-1,1), (-1,-1), [1,-1], (1,1), (-1, 1), (-1,-1)]
self.assert_(fmath.normalize_poly(p) == self.p)
self.assert_(fmath.normalize_poly(self.p, 2) == p)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.normalize_poly, b)
class TestPolySimplify(unittest.TestCase):
def setUp(self):
self.data = [[(1, 0), (1, 8.12), (19.95, 5), (-1, -5), (-1.25, -5.15)],
[[-1, 0], [-1, -4.12], [-16.95, -5], [14, 5], [1.25, 5.15]]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}]]
def testReturnsList(self):
for i in range(8):
for d in self.data:
self.assertTrue(isinstance(fmath.simplify_poly(d, i),
list))
def testReturnsCoords(self):
for i in range(8):
for d in self.data:
result = fmath.simplify_poly(d, i)
b = True
for p in result:
if not (isinstance(p[0], Number) and isinstance(p[1], Number)):
b = b and False
break
self.assertTrue(b)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.simplify_poly, b, 1)
class TestVector(unittest.TestCase):
def setUp(self):
self.v = fmath.Vector((111, 222))
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assert_(v.x == 111 and v.y == 222)
v.x = 333
v[1] = 444
self.assert_(v[0] == 333 and v[1] == 444)
def testMath(self):
v = self.v.copy()
self.assertEqual(v + 1, fmath.Vector((112, 223)))
self.assertEqual(v - 2, [109,220])
self.assert_(v * 3 == (333,666))
self.assert_(v / 2.0 == fmath.Vector((55.5, 111)))
self.assert_(v / 2 == (55.5, 111))
self.assert_(v ** fmath.Vector((2,3)) == [12321, 10941048])
self.assert_(v + [-11, 78] == fmath.Vector((100, 300)))
def testReverseMath(self):
v = self.v.copy()
self.assert_(1 + v == fmath.Vector((112,223)))
self.assert_(2 - v == [-109,-220])
self.assert_(3 * v == (333,666))
self.assert_([111,222] ** fmath.Vector((2,3)) == [12321, 10941048])
self.assert_(v + fmath.Vector((1,1)) == [112, 223])
def testInplaceMath(self):
inplace_vec = fmath.Vector((5, 13))
inplace_src = fmath.Vector((inplace_vec))
inplace_vec *= .5
inplace_vec += .5
inplace_vec /= 3
inplace_vec += fmath.Vector((-1, -1))
alternate = (inplace_src*.5 + .5)/3 + [-1, -1]
self.assertEquals(inplace_vec, alternate)
def testUnary(self):
v = self.v.copy()
v = -v
self.assert_(v == [-111,-222])
v = abs(v)
self.assert_(v == [111,222])
def testLength(self):
v = fmath.Vector((3, 4))
self.assert_(v.length == 5)
v.length = 10
self.assert_(v == [6, 8])
def testAngles(self):
v = fmath.Vector((0,3))
self.assert_(v.angle == 90)
v.angle = 0
self.assert_(v == (3, 0))
v2 = (-3,0)
self.assert_(v.angle_about(v2) == 0)
v2 = fmath.Vector(v2)
self.assert_(v2.angle_about(v) == 180)
v.angle = 90, (0,0)
self.assert_(v == [0, 3])
def testComparison(self):
int_vec = fmath.Vector((3, -2))
flt_vec = fmath.Vector((3.0, -2.0))
zero_vec = fmath.Vector((0, 0))
self.assert_(int_vec == flt_vec)
self.assert_(int_vec != zero_vec)
self.assert_((flt_vec == zero_vec) == False)
self.assert_((flt_vec != int_vec) == False)
self.assert_(int_vec == (3, -2))
self.assert_(int_vec != [0, 0])
self.assert_(int_vec != 5)
def testConversion(self):
self.assert_(list(self.v) == [111, 222] and isinstance(list(self.v), list))
self.assert_(tuple(self.v) == (111, 222) and isinstance(tuple(self.v), tuple))
def testPickle(self):
testvec = fmath.Vector((5, .3))
testvec_str = pickle.dumps(testvec)
loaded_vec = pickle.loads(testvec_str)
self.assertEquals(testvec, loaded_vec)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Vector, b)
class TestPolygon(unittest.TestCase):
def setUp(self):
self.p = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.bad = [[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]]]
def testAccess(self):
p = self.p.copy()
self.assert_(p[0] == (-1, 1))
p[0] = (-5, 5)
self.assert_(p[0] == (-5, 5) and isinstance(p[0], fmath.Vector))
self.assert_(p.center == (-1, 1))
p[1] = -4, 7
self.assert_(p[1] == (-4, 7))
p[3] = 16
self.assert_(p[3] == (16, 16))
def testComparison(self):
p = self.p.copy()
self.assert_(p == [(-1,1), (-1,-1), (1,-1), (1,1)])
q = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.assert_(p == q)
q[0] = -5, 5
self.assert_(p != q)
self.assert_(q != p)
def testConversion(self):
p = self.p.copy()
self.assert_(list(p) == p and isinstance(list(p), list))
self.assert_(tuple(p) == p and isinstance(tuple(p), tuple))
def testAngle(self):
p = self.p.copy()
self.assert_(p.angle == 0)
p.center = 1,0
self.assert_(p.angle == 0)
p.center = 0, 10
self.assert_(p.angle == 90)
def testOrientation(self):
p = self.p.copy()
self.assert_(p.orientation == 0)
l = list(p)
p.orientation = 90
self.assert_(p != l)
self.assertEquals(p, [(-1.0000000000000002, -1.0),
(0.99999999999999978, -1.0000000000000002),
(1.0000000000000002, 1.0), (-1.0, 1.0000000000000002)])
def testCollision(self):
p1 = self.p.copy()
p2 = [(-0.5,0.5), (-0.5,-0.5), (0.5,-0.5), (0.5,0.5)]
self.assert_(p1.intersects(p2))
self.assert_(p1.intersects(p1))
p1.center = 90, -60
self.assert_(p1.intersects(p2) == False)
p1.center = 1.5, 0
self.assert_(p1.intersects(p2))
p1.center = 0, -1.5
self.assert_(p1.intersects(p2))
p1.center = -1.4, 0
self.assert_(p1.intersects(p2))
def testPickle(self):
testpoly = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
testpoly_str = pickle.dumps(testpoly)
loaded_poly = pickle.loads(testpoly_str)
self.assertEquals(testpoly, loaded_poly)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Polygon, b)
class TestRect(unittest.TestCase):
def setUp(self):
self.p = fmath.Rect((0, 0), 2, 2)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testAccess(self):
p = self.p.copy()
self.assert_(p.center == (0,0))
self.assert_(p.topleft == (-1, 1))
self.assert_(p.bottomleft == (-1, -1))
p.center = 1, 3
self.assert_(p.center == (1, 3))
p.topright = 4
self.assert_(p.topright == (4, 4))
self.assert_(p.bottomright == (4, 2))
p[2] = 4, 1
self.assert_(p.topright == (4, 3))
self.assert_(p.bottomright == (4, 1))
p.width = 4
self.assert_(p.topright == (5, 3))
p.size = (1, 1)
self.assert_(p.topleft == (2.5, 2.5))
def testMath(self):
pass
def testComparison(self):
p = self.p.copy()
q = [(-1,1), (-1,-1), (1,-1), (1,1)]
self.assert_(p == q)
q[0] = (-1, 2)
self.assert_(p != q)
def testAngle(self):
p = self.p.copy()
self.assert_(p.angle == 0)
p.center = 1,0
self.assert_(p.angle == 0)
p.center = 0, 10
self.assert_(p.angle == 90)
p.angle = 0
self.assert_(p.center == (10, 0))
def testOrientation(self):
p = self.p.copy()
self.assert_(p.orientation == 0)
l = list(p)
p.orientation = 90
self.assert_(p != l)
self.assertEquals(p, [(-1.0000000000000002, -1.0),
(0.99999999999999978, -1.0000000000000002),
(1.0000000000000002, 1.0), (-1.0, 1.0000000000000002)])
def testConversion(self):
p = self.p.copy()
self.assert_(list(p) == p and isinstance(list(p), list))
self.assert_(tuple(p) == p and isinstance(tuple(p), tuple))
def testPickle(self):
testrect = fmath.Rect((-1, 1), 2, 2)
testrect_str = pickle.dumps(testrect)
loaded_rect = pickle.loads(testrect_str)
self.assertEquals(testrect, loaded_rect)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Rect, b)
##-------- Test Suite
testpow = unittest.TestLoader().loadTestsFromTestCase(TestPow)
testdistance = unittest.TestLoader().loadTestsFromTestCase(TestDistance)
testmidpoint = unittest.TestLoader().loadTestsFromTestCase(TestMidpoint)
testarea = unittest.TestLoader().loadTestsFromTestCase(TestArea)
testnormalized = unittest.TestLoader().loadTestsFromTestCase(TestNormalizeAngle)
testnormalizepoly = unittest.TestLoader().loadTestsFromTestCase(TestNormalizePoly)
testsimplify = unittest.TestLoader().loadTestsFromTestCase(TestPolySimplify)
testvector = unittest.TestLoader().loadTestsFromTestCase(TestVector)
testpolygon = unittest.TestLoader().loadTestsFromTestCase(TestPolygon)
testrect = unittest.TestLoader().loadTestsFromTestCase(TestRect)
testsuite = unittest.TestSuite((testpow, testdistance, testmidpoint, testarea,
testnormalized, testnormalizepoly,
testsimplify,
testvector, testpolygon, testrect))
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import flamingo as fl
class Game(fl.game.Game):
def init(self, *args):
self.screen1 = fl.screen.Screen((0, 0), 800, 600)
self.add_screen(self.screen1)
self.screen1.center = 400, 300
fl.event.bind(lambda: self.data.screens[0].__setattr__('centerx', self.data.screens[0].centerx + 1),
fl.constants.K_d, fl.constants.KEYHOLD, mods=fl.event.Mods([], [fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('centerx', self.data.screens[0].centerx - 1),
fl.constants.K_a, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('centery', self.data.screens[0].centery + 1),
fl.constants.K_w, fl.constants.KEYHOLD, delay=5)
fl.event.bind(lambda: self.data.screens[0].__setattr__('centery', self.data.screens[0].centery - 1),
fl.constants.K_s, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom * 0.96),
fl.constants.MS_DOWN, fl.constants.SCROLLWHEEL, mods=fl.event.Mods([fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom / 0.96),
fl.constants.MS_UP, fl.constants.SCROLLWHEEL, mods=fl.event.Mods([fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom * 0.96),
fl.constants.K_i, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom / 0.96),
fl.constants.K_o, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('orientation', self.data.screens[0].orientation + 1),
fl.constants.K_k, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('orientation', self.data.screens[0].orientation - 1),
fl.constants.K_l, fl.constants.KEYHOLD)
fl.event.bind(self.data.master_clock.pause, fl.constants.K_COMMA, fl.constants.KEYDOWN)
fl.event.bind(self.data.master_clock.resume, fl.constants.K_PERIOD, fl.constants.KEYDOWN)
fl.event.bind(self.quit_game, fl.constants.K_ESCAPE, fl.constants.KEYDOWN)
def start_game(self):
i = fl.image.load("res/flamingo.png")
ii = fl.image.load("res/test.gif")
iii = fl.image.load_sheeth("res/swatch.png", width=100, speed=50)
s1 = fl.sprite.Sprite(i)
s1.center = (200, 450)
s2 = fl.sprite.Sprite(ii)
s2.center = (400, 300)
s2.color.a = 0.08
s3 = fl.sprite.Sprite(iii)
s3.center = (600, 150)
s3.color.a = 0.08
t = fl.fltime.Timer(15000)
fl.event.bind(self.quit_game, t, fl.constants.TIMEREND)
fl.event.bind(t.start, fl.constants.K_SPACE, fl.constants.KEYDOWN)
def p():
self.screen1.orientation = -(144**(t.percent() * 1.5) - 1)
self.screen1.zoom = 0.005 + t.percent_left() * 0.995
#s2.color.a = t.percent_left()
s1.color.b = 1 - 0.5 * t.percent()
s3.color.r = t.percent_left()
s3.color.g = 1 - 0.5 * t.percent()
def va():
s1.bones[0].angle -= .03
s1.bones[0][0].angle -= .02
s1.bones[1].angle -= .1
s1.bones[1][0].angle -= .03
s1.bones[1].length -= .01
s1.bones[2].angle -= .015
s1.bones[2][0].angle -= .01
s1.bones[3].angle -= -.005
s1.bones[3][0].angle -= -.008
def vs():
s1.bones[0].angle += .03
s1.bones[0][0].angle += .02
s1.bones[1].angle += .1
s1.bones[1][0].angle += .03
s1.bones[1].length += .01
s1.bones[2].angle += .015
s1.bones[2][0].angle += .01
s1.bones[3].angle += -.005
s1.bones[3][0].angle += -.008
fl.event.bind(va, fl.constants.K_DOWN, fl.constants.KEYHOLD)
fl.event.bind(vs, fl.constants.K_UP, fl.constants.KEYHOLD)
fl.event.bind(p, t, fl.constants.TIMERTICK)
if __name__ == "__main__":
fl.util.enable_logging()
try:
import psyco
psyco.full()
except ImportError:
pass
game = Game()
game.run(True, 0)
| Python |
#!/usr/bin/env python
## fl - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import os
import unittest
import pickle
import flamingo as fl
##-------- Data
i = fl.image.load(os.path.join(fl.fl_path, "tests/res/glass.bmp"))
ii = fl.image.load(os.path.join(fl.fl_path, "tests/res/swatch.png"))
iii = fl.image.load(os.path.join(fl.fl_path, "tests/res/swatchv.png"))
sk = {"glass": i, "swatch": ii}
SPR1 = fl.sprite.Sprite(i, default="glass")
SPR2 = fl.sprite.Sprite(sk, SPR1, default="glass")
SGRP = fl.sprite.Group()
UGRP = SPR2.groups()[0]
##-------- Test Cases
class TestSprite(unittest.TestCase):
def testAccess(self):
self.assertEqual(SPR1.center, (0,0))
SPR1.center += 100
self.assertEqual(SPR1.center, (100, 100))
SPR1.center -= 100
self.assertEqual(SPR1.z, 0)
SPR1.z = 200
self.assertEqual(SPR1.z, 200)
objste = SPR1.state
self.assertEqual(fl.sprite.ObjectState, objste.__class__)
self.assertEqual(SPR1.texture.width, 128)
self.assertEqual(SPR1.texture.height, 128)
tex = SPR2.texture
self.assertEqual(fl.image.Texture, tex.__class__)
self.assertEqual(tex, SPR2['glass'])
self.assertNotEqual(tex, SPR2['swatch'])
self.assertEqual(len(SPR2), 2)
self.assertEqual(SPR2.skins, sk)
## Color
self.assertEqual(SPR1.parent, None)
self.assertEqual(SPR2.parent, SPR1)
self.assertNotEqual(SPR1.groups(), [])
self.assertEqual(len(SPR1.groups()), 1)
def testGroups(self):
SPR1.add(SGRP)
self.assertTrue(SGRP in SPR1.groups())
SPR1.remove(SGRP)
self.assertTrue(SGRP not in SPR1.groups())
SPR1.add(SGRP)
SPR1.kill()
self.assertEqual(len(SPR1.groups()), 0)
def testSkins(self):
new_skin = {'swatchv': iii}
SPR2.change_skin('swatch')
self.assertEqual(SPR2.texture, ii)
self.assertRaises(AttributeError, fl.sprite.Sprite.remove_skin, SPR2, 'swatch')
self.assertRaises(KeyError, fl.sprite.Sprite.remove_skin, SPR2, 'swatc')
SPR2.merge_skins(new_skin)
self.assertEqual(SPR2.skins, {'glass': i, 'swatch': ii, 'swatchv': iii})
SPR1.add_skin('swatch', ii)
SPR1.remove_skin('swatch')
SPR2.remove_skin('swatchv')
self.assertRaises(KeyError, fl.sprite.Sprite.change_skin, SPR1, 'swatch')
def testUpdate(self):
SPR1._update(0)
SPR1.center = 1, 1
SPR1.color = fl.flcolor.Color(0, 0, 0, 0)
self.assertNotEqual(SPR1.center, SPR1.prevstate.bound.center)
self.assertEqual(SPR1.prevstate.bound.center, (0,0))
self.assertNotEqual(SPR1.color, SPR1.prevstate.color)
self.assertEqual(SPR1.color, (0,0,0,0))
self.assertEqual(SPR1.prevstate.color, (1, 1, 1, 1))
SPR1.center = 0, 0
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
class TestObjectState(unittest.TestCase):
def testAccess(self):
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
self.assertEqual(SPR1.color, (1, 1, 1 ,1))
self.assertEqual(SPR1.state.bound, ((-64,-64), (64, -64), (64, 64), (-64, 64)))
def testInterpolate(self):
SPR1._update(0)
SPR1.center = 1, 1
SPR1.prevstate.color = fl.flcolor.Color(1,1,1,1)
SPR1.color = fl.flcolor.Color(0, 0, 0, 0)
interstate = SPR1.interpolate(0.5)
self.assertEqual(interstate.color, (0.5, 0.5, 0.5, 0.5))
self.assertEqual(interstate.bound.center, (0.5, 0.5))
SPR1.center = 0, 0
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
def testPickle(self):
test_str = pickle.dumps(SPR1.state)
loaded = pickle.loads(test_str)
self.assertEqual(SPR1.state.color, loaded.color)
self.assertEqual(SPR1.state.bound, loaded.bound)
class TestGroup(unittest.TestCase):
def testAccess(self):
self.assertTrue(isinstance(UGRP.sprites(), list))
self.assertEqual(len(UGRP.sprites()), 1)
self.assertTrue(SPR2 in UGRP.sprites())
def testManagement(self):
SGRP.add(SPR1)
SGRP.add(SPR1)
self.assertTrue(SPR1 in SGRP.sprites())
SGRP.add(SPR2)
self.assertTrue(SPR2 in SGRP.sprites())
SGRP.remove(SPR2)
self.assertTrue(SPR2 not in SGRP.sprites())
SGRP.empty()
self.assertEqual(len(SGRP.sprites()), 0)
##-------- Test Suite
testsprite = unittest.TestLoader().loadTestsFromTestCase(TestSprite)
testobjectstate = unittest.TestLoader().loadTestsFromTestCase(TestObjectState)
testgroup = unittest.TestLoader().loadTestsFromTestCase(TestGroup)
testsuite = unittest.TestSuite((testsprite, testobjectstate, testgroup))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import unittest
import pickle
import flamingo
class TestScreen(unittest.TestCase):
def setUp(self):
self.p = flamingo.screen.Screen((0, 0), 800, 600)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), 2, 3]]
def testAccess(self):
self.assertEqual(self.p.center, (400, 300))
self.assertEqual(self.p.local_rect, ((0, 0), (800, 0), (800, 600), (0, 600)))
self.p.height = 400
self.assertEqual(self.p.local_rect.height, 600)
self.assertTrue(self.p.local_rect.enabled(flamingo.constants.POLYGON_AXIS_ALIGNED))
self.assertRaises(AttributeError, flamingo.screen.Screen.disable,
self.p.local_rect, flamingo.constants.POLYGON_AXIS_ALIGNED)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Rect, b)
##-------- Test Suite
testscreen = unittest.TestLoader().loadTestsFromTestCase(TestScreen)
testsuite = unittest.TestSuite((testscreen))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Unit Tests for flamingo.flmath"""
import unittest
import flamingo
import math
import pickle
from numbers import Number
class TestPow(unittest.TestCase):
def setUp(self):
self.data = [2, 3, 4, 7, 17, 710, 483, 60495, 712345]
self.bad = ["hello world!", [1, 2, 3], {'foo': 'bar'},
flamingo.flmath.Vector([1, 1])]
def testClosestIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.closest_pow2(d), Number))
def testClosestIsPow2(self):
for d in self.data:
result = flamingo.flmath.closest_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testClosestIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.closest_pow2(d) >= 1)
def testClosestIsClosest(self):
for d in self.data:
less = math.pow(2, math.ceil(math.log(d)/math.log(2.0)))
greater = math.pow(2, math.floor(math.log(d)/math.log(2.0)))
lessd = d - less
greaterd = greater - d
if lessd < greaterd:
self.assertEqual(flamingo.flmath.closest_pow2(d), greater)
else:
self.assertEqual(flamingo.flmath.closest_pow2(d), less)
def testClosestBad(self):
for b in self.bad:
self.assertRaises(TypeError,
flamingo.flmath.closest_pow2, b)
def testClosestNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.closest_pow2, -d)
def testNextIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.next_pow2(d), Number))
def testNextIsPow2(self):
for d in self.data:
result = flamingo.flmath.next_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testNextIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.next_pow2(d) >= 1)
def testNextGreater(self):
for d in self.data:
result = flamingo.flmath.next_pow2(d)
self.assertTrue(result >= d)
def testNextBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.next_pow2, b)
def testNextNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.next_pow2, -d)
def testPrevIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.prev_pow2(d), Number))
def testPrevIsPow2(self):
for d in self.data:
result = flamingo.flmath.prev_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testPrevIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.prev_pow2(d) >= 1)
def testPrevLess(self):
for d in self.data:
result = flamingo.flmath.prev_pow2(d)
if result is None:
self.assertTrue(False)
self.assertTrue(result <= d)
def testPrevBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.prev_pow2, b)
def testPrevNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.prev_pow2, -d)
class TestDistance(unittest.TestCase):
def setUp(self):
## data = [[point, point, distance, distance_sq]]
self.data = [[(0, 0), (0, 1), 1, 1],
[(2.5, 2),(4.76, 3.1), 2.5134, 6.3176],
[(10, 16),(100, 160), 169.8116, 28836],
[flamingo.flmath.Vector([1.2, 1]), flamingo.flmath.Vector([16, 1]), 14.8, 219.04],
[(0, 0), (0, 0), 0, 0],
[flamingo.flmath.Vector([0, 0]), flamingo.flmath.Vector([0, 0]), 0, 0]]
self.long = [[(21, 4, 6, 4, 3), (14, 16, 71, 723, 5)],
[(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)],
[(1, 2, 3, 4), (5, 4, 3, 2, 1)]]
self.short = [[(), ()]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.distance(d[0], d[1]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(flamingo.flmath.distance(d[0], d[1]) >= 0)
def testValue(self):
for d in self.data:
result = flamingo.flmath.distance(d[0], d[1])
self.assertEqual(round(result, 2), round(d[2], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.distance, b[0],b[1])
##-------- Sq
def testIsNumberSq(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.distance_sq(d[0], d[1]), Number))
def testIsPosSq(self):
for d in self.data:
self.assertTrue(flamingo.flmath.distance_sq(d[0], d[1]) >= 0)
def testValueSq(self):
for d in self.data:
result = flamingo.flmath.distance_sq(d[0], d[1])
self.assertEqual(round(result, 2), round(d[3], 2))
def testBadSq(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.distance_sq, b[0],b[1])
class TestMidpoint(unittest.TestCase):
def setUp(self):
## data = [[point, point, midpoint]]
self.data = [[(0, 0), (0, 1), (0, 0.5)],
[(2.5, 2),(4.76, 3.1), (3.63, 2.55)],
[(10, 16),(100, 160), (55, 88)],
[flamingo.flmath.Vector([1.13, 1]), (16, 1), (8.565, 1)],
[(0, 0), (0, 0), (0, 0)]]
self.wrong = [[(), ()],
[(2,), (1,)]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testValue(self):
for d in self.data:
result = flamingo.flmath.midpoint(d[0], d[1])
self.assertEqual(round(result[0]), round(d[2][0]))
self.assertEqual(round(result[1]), round(d[2][1]))
def testWrong(self):
for d in self.wrong:
self.assertRaises(TypeError, flamingo.flmath.midpoint, d[0], d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.midpoint, b[0],b[1])
class TestArea(unittest.TestCase):
def setUp(self):
## [[data], area, signed_area]
self.data = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], 4, 4],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], 4, -4],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], 1002.66, 1002.66 ],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], 1002.66, -1002.66 ]]
self.odata = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], True],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], False],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], True],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], False]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}],
[(1,), (2,), (3,)],
[(1, 2), (3, 4)],
[(1, 2)],
[]]
##-------- Pos Area
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.area(d[0]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(flamingo.flmath.area(d[0]) > 0)
def testValue(self):
for d in self.data:
result = flamingo.flmath.area(d[0])
self.assertEqual(round(result, 2), round(d[1], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.area, b)
##-------- Signed Area
def testIsNumberS(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.signed_area(d[0]), Number))
def testValueS(self):
for d in self.data:
result = flamingo.flmath.signed_area(d[0])
self.assertEqual(round(result, 2), round(d[2], 2))
def testBadS(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.signed_area, b)
##-------- Orientation
def testValueO(self):
for d in self.odata:
result = flamingo.flmath.orientation_poly(d[0])
self.assertEqual(result, d[1])
def testBadO(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.orientation_poly, b)
class TestNormalizeAngle(unittest.TestCase):
def setUp(self):
self.datad = [[45, 45],
[360, 0],
[400, 40],
[4000, 40],
[-100, 260]]
self.datar = [[math.radians(45), math.radians(45)],
[math.radians(360), math.radians(0)],
[math.radians(400), math.radians(40)],
[math.radians(4000), math.radians(40)],
[math.radians(-100), math.radians(260)]]
self.bad = ["meow",
[16],
{'foo': 'bar'}]
##-------- Degress
def testNumber(self):
for i in range(0, 1000):
self.assertTrue(isinstance(flamingo.flmath.normalize_angle(i), Number))
def testIsPos(self):
for i in range(0, 1000):
self.assertTrue(flamingo.flmath.normalize_angle(i) >= 0)
def testValue(self):
for d in self.datad:
self.assertEqual(flamingo.flmath.normalize_angle(d[0]), d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_angle, b)
##-------- Radians
def testNumberR(self):
for i in range(0, 1000):
self.assertTrue(isinstance(flamingo.flmath.normalize_angler(i), Number))
def testIsPosR(self):
for i in range(0, 1000):
self.assertTrue(flamingo.flmath.normalize_angler(i) >= 0)
def testValueR(self):
for d in self.datar:
self.assertAlmostEqual(flamingo.flmath.normalize_angler(d[0]), d[1])
def testBadR(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_angler, b)
class TestNormalizePoly(unittest.TestCase):
def setUp(self):
self.p = [flamingo.flmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1)]
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testNormalize(self):
self.assertEqual(flamingo.flmath.normalize_poly(self.p), self.p)
p = [flamingo.flmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1), (-1, 1)]
self.assertEqual(flamingo.flmath.normalize_poly(p), self.p)
self.assertEqual(flamingo.flmath.normalize_poly(self.p, 1), p)
p = [(-1,1), (-1,-1), [1,-1], (1,1), (-1, 1), (-1,-1)]
self.assertEqual(flamingo.flmath.normalize_poly(p), self.p)
self.assertEqual(flamingo.flmath.normalize_poly(self.p, 2), p)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_poly, b)
class TestPolySimplify(unittest.TestCase):
def setUp(self):
self.data = [[(1, 0), (1, 8.12), (19.95, 5), (-1, -5), (-1.25, -5.15)],
[[-1, 0], [-1, -4.12], [-16.95, -5], [14, 5], [1.25, 5.15]]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}]]
def testReturnsList(self):
for i in range(8):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.simplify_poly(d, i), list))
def testReturnsCoords(self):
for i in range(8):
for d in self.data:
result = flamingo.flmath.simplify_poly(d, i)
b = True
for p in result:
if not (isinstance(p[0], Number) and isinstance(p[1], Number)):
b = b and False
break
self.assertTrue(b)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.simplify_poly, b, 1)
class TestVector(unittest.TestCase):
def setUp(self):
self.v = flamingo.flmath.Vector((111, 222))
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assertEqual(v.x, 111)
self.assertEqual(v.y, 222)
v.x = 333
v[1] = 444
self.assertEqual(v[0], 333)
self.assertEqual(v[1], 444)
def testMath(self):
v = self.v.copy()
self.assertEqual(v + 1, flamingo.flmath.Vector((112, 223)))
self.assertEqual(v - 2, [109,220])
self.assertEqual(v * 3, (333,666))
self.assertEqual(v / 2.0, flamingo.flmath.Vector((55.5, 111)))
self.assertEqual(v / 2, (55.5, 111))
self.assertEqual(v ** flamingo.flmath.Vector((2,3)), [12321, 10941048])
self.assertEqual(v + [-11, 78], flamingo.flmath.Vector((100, 300)))
def testReverseMath(self):
v = self.v.copy()
self.assertEqual(1 + v, flamingo.flmath.Vector((112,223)))
self.assertEqual(2 - v, [-109,-220])
self.assertEqual(3 * v, (333,666))
self.assertEqual([111,222] ** flamingo.flmath.Vector((2,3)), [12321, 10941048])
self.assertEqual(v + flamingo.flmath.Vector((1,1)), [112, 223])
def testInplaceMath(self):
inplace_vec = flamingo.flmath.Vector((5, 13))
inplace_src = flamingo.flmath.Vector((inplace_vec))
inplace_vec *= .5
inplace_vec += .5
inplace_vec /= 3
inplace_vec += flamingo.flmath.Vector((-1, -1))
alternate = (inplace_src*.5 + .5)/3 + [-1, -1]
self.assertEqual(inplace_vec, alternate)
def testUnary(self):
v = self.v.copy()
v = -v
self.assertEqual(v, [-111,-222])
v = abs(v)
self.assertEqual(v, [111,222])
def testLength(self):
v = flamingo.flmath.Vector((3, 4))
self.assertEqual(v.length, 5)
v.length = 10
self.assertEqual(v, [6, 8])
def testAngles(self):
v = flamingo.flmath.Vector((0,3))
self.assertEqual(v.angle, 90)
v.angle = 0
self.assertEqual(v, (3, 0))
v2 = (-3,0)
self.assertEqual(v.angle_about(v2), 0)
v2 = flamingo.flmath.Vector(v2)
self.assertEqual(v2.angle_about(v), 180)
v.angle = 90, (0,0)
self.assertEqual(v, [0, 3])
def testComparison(self):
int_vec = flamingo.flmath.Vector((3, -2))
flt_vec = flamingo.flmath.Vector((3.0, -2.0))
zero_vec = flamingo.flmath.Vector((0, 0))
self.assertEqual(int_vec, flt_vec)
self.assertNotEqual(int_vec, zero_vec)
self.assertFalse(flt_vec == zero_vec)
self.assertFalse(flt_vec != int_vec)
self.assertEqual(int_vec, (3, -2))
self.assertNotEqual(int_vec, [0, 0])
self.assertNotEqual(int_vec, 5)
def testConversion(self):
self.assertEqual(list(self.v), [111, 222])
self.assertTrue(isinstance(list(self.v), list))
self.assertEqual(tuple(self.v), (111, 222))
self.assertTrue(isinstance(tuple(self.v), tuple))
def testPickle(self):
testvec = flamingo.flmath.Vector((5, .3))
testvec_str = pickle.dumps(testvec)
loaded_vec = pickle.loads(testvec_str)
self.assertEqual(testvec, loaded_vec)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Vector, b)
class TestPolygon(unittest.TestCase):
def setUp(self):
self.p = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.bad = [[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]]]
def testAccess(self):
p = self.p.copy()
self.assertEqual(p[0], (-1, 1))
p[0] = (-5, 5)
self.assertEqual(p[0], (-5, 5))
self.assertTrue(isinstance(p[0], flamingo.flmath.Vector))
self.assertEqual(p.center, (-1, 1))
p[1] = -4, 7
self.assertEqual(p[1], (-4, 7))
p[3] = 16
self.assertEqual(p[3], (16, 16))
def testComparison(self):
p = self.p.copy()
self.assertEqual(p, [(-1,1), (-1,-1), (1,-1), (1,1)])
q = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.assertEqual(p, q)
q[0] = -5, 5
self.assertNotEqual(p, q)
self.assertNotEqual(q, p)
def testAppend(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.append, p, (0, 2.5))
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.append((0, 2.5))
self.assertEqual(len(p), 5)
self.assertEqual(p.center, (0, 0.5))
p[4] -= 0, 1
self.asserEqual(p.center, (0,0))
p.append((-0.5, 1))
self.assertEqual(len(p), 6)
self.asserEqual(p.center, (0,0))
def testInsert(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.insert, p, 1, (-2.5, 0))
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.insert(1, (-2.5, 0))
self.assertEqual(len(p), 5)
self.assertEqual(p.center, (-0.5, 0))
def testRemove(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.insert, p, 3)
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.remove(3)
self.assertEqual(len(p), 3)
self.assertEqual(p.center, -1.0/3)
self.assertRaises(TypeError, Polygon.remove, p, 1)
def testConversion(self):
p = self.p.copy()
self.assertEqual(list(p), p)
self.assertTrue(isinstance(list(p), list))
self.assertEqual(tuple(p), p)
self.assertTrue(isinstance(tuple(p), tuple))
def testAngle(self):
p = self.p.copy()
self.assertEqual(p.angle, 0)
p.center = 1,0
self.assertEqual(p.angle, 0)
p.center = 0, 10
self.assertEqual(p.angle, 90)
def testOrientation(self):
p = self.p.copy()
self.assertEqual(p.orientation, 0)
l = list(p)
p.orientation = 90
self.assertNotEqual(p, l)
self.assertAlmostEqual(p[0].x, -1, 0.001)
self.assertAlmostEqual(p[0].y, -1, 0.001)
self.assertAlmostEqual(p[1].x, 1, 0.001)
self.assertAlmostEqual(p[1].y, -1, 0.001)
self.assertAlmostEqual(p[2].x, 1, 0.001)
self.assertAlmostEqual(p[2].y, 1, 0.001)
self.assertAlmostEqual(p[3].x, -1, 0.001)
self.assertAlmostEqual(p[3].y, 1, 0.001)
def testCollision(self):
p1 = self.p.copy()
p2 = [(-0.5,0.5), (-0.5,-0.5), (0.5,-0.5), (0.5,0.5)]
self.assertTrue(p1.intersects(p2))
self.assertTrue(p1.intersects(p1))
p1.center = 90, -60
self.assertFalse(p1.intersects(p2))
p1.center = 1.5, 0
self.assertTrue(p1.intersects(p2))
p1.center = 0, -1.5
self.assertTrue(p1.intersects(p2))
p1.center = -1.4, 0
self.assertTrue(p1.intersects(p2))
def testPickle(self):
testpoly = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
testpoly_str = pickle.dumps(testpoly)
loaded_poly = pickle.loads(testpoly_str)
self.assertEqual(testpoly, loaded_poly)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Polygon, b)
class TestRect(unittest.TestCase):
def setUp(self):
self.p = flamingo.flmath.Rect((0, 0), 2, 2)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testAccess(self):
p = self.p.copy()
self.assertEqual(p.center, (0,0))
self.assertEqual(p.topleft, (-1, 1))
self.assertEqual(p.bottomleft, (-1, -1))
p.center = 1, 3
self.assertEqual(p.center, (1, 3))
p.topright = 4
self.assertEqual(p.topright, (4, 4))
self.assertEqual(p.bottomright, (4, 2))
p[1] = 4, 1
self.assertEqual(p.topright, (4, 3))
self.assertEqual(p.bottomright, (4, 1))
p.width = 4
self.assertEqual(p.topright, (5, 3))
p.size = (1, 1)
self.assertEqual(p.topleft, (2.5, 2.5))
def testComparison(self):
p = self.p.copy()
q = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
self.assertEqual(p, q)
q[3] = (-1, 2)
self.assertNotEqual(p, q)
def testAppend(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.append, p, (0,0))
def testInsert(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.insert, p, 1, (0,0))
def testRemove(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.remove, p, 1)
def testAngle(self):
p = self.p.copy()
self.assertEqual(p.angle, 0)
p.center = 1,0
self.assertEqual(p.angle, 0)
p.center = 0, 10
self.assertEqual(p.angle, 90)
p.angle = 0
self.assertEqual(p.center, (10, 0))
def testOrientation(self):
p = self.p.copy()
self.assertEqual(p.orientation, 0)
l = list(p)
p.orientation = 90
self.assertNotEqual(p, l)
self.assertAlmostEqual(p[0].x, 1, 0.001)
self.assertAlmostEqual(p[0].y, -1, 0.001)
self.assertAlmostEqual(p[1].x, 1, 0.001)
self.assertAlmostEqual(p[1].y, 1, 0.001)
self.assertAlmostEqual(p[2].x, -1, 0.001)
self.assertAlmostEqual(p[2].y, 1, 0.001)
self.assertAlmostEqual(p[3].x, -1, 0.001)
self.assertAlmostEqual(p[3].y, -1, 0.001)
def testConversion(self):
p = self.p.copy()
self.assertEqual(list(p), p)
self.assertTrue(isinstance(list(p), list))
self.assertEqual(tuple(p), p)
self.assertTrue(isinstance(tuple(p), tuple))
def testPickle(self):
testrect = flamingo.flmath.Rect((-1, 1), 2, 2)
testrect_str = pickle.dumps(testrect)
loaded_rect = pickle.loads(testrect_str)
self.assertEqual(testrect, loaded_rect)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Rect, b)
##-------- Test Suite
testpow = unittest.TestLoader().loadTestsFromTestCase(TestPow)
testdistance = unittest.TestLoader().loadTestsFromTestCase(TestDistance)
testmidpoint = unittest.TestLoader().loadTestsFromTestCase(TestMidpoint)
testarea = unittest.TestLoader().loadTestsFromTestCase(TestArea)
testnormalized = unittest.TestLoader().loadTestsFromTestCase(TestNormalizeAngle)
testnormalizepoly = unittest.TestLoader().loadTestsFromTestCase(TestNormalizePoly)
testsimplify = unittest.TestLoader().loadTestsFromTestCase(TestPolySimplify)
testvector = unittest.TestLoader().loadTestsFromTestCase(TestVector)
testpolygon = unittest.TestLoader().loadTestsFromTestCase(TestPolygon)
testrect = unittest.TestLoader().loadTestsFromTestCase(TestRect)
testsuite = unittest.TestSuite((testpow, testdistance, testmidpoint, testarea,
testnormalized, testnormalizepoly, #testsimplify,
testvector, testpolygon, testrect))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import unittest
import pickle
import flamingo
import flmath_test
class TestMesh(unittest.TestCase):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
def testAccess(self):
self.assertEqual(len(self.m), 3)
v = self.m.v[0]
t = self.m.t[0]
self.assertEqual(flamingo.mesh.MeshNode, type(t))
self.assertEqual(flamingo.mesh.VMeshNode, type(v))
class TestMeshNode(flmath_test.TestVector):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
self.v = self.m.t[0]
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
class TestVMeshNode(flmath_test.TestVector):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
self.v = self.m.v[0]
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assertEqual(v.x, 111)
self.assertEqual(v.y, 222)
v.x = 333
v[1] = 444
self.assertEqual(v[0], 333)
self.assertEqual(v[1], 444)
## More stuff later
##-------- Test Suite
testmesh = unittest.TestLoader().loadTestsFromTestCase(TestMesh)
testnode = unittest.TestLoader().loadTestsFromTestCase(TestMeshNode)
testvnode = unittest.TestLoader().loadTestsFromTestCase(TestVMeshNode)
testsuite = unittest.TestSuite((testmesh, testnode, testvnode))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import os
import unittest
import pickle
import flamingo
class TestLoad(unittest.TestCase):
def testLoad(self):
good = [(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/glass.bmp"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/test.gif"), -1, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/test.gif"), 740, [])]
for g in good:
self.assertTrue(isinstance(flamingo.image.load(*g), flamingo.image.Texture))
def testBad(self):
b = [(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), "-1", []),
(os.path.join(flamingo.fl_path, "tests/res/flaming.png"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), "-1", [(1,)])]
self.assertRaises(TypeError, flamingo.image.load, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load, *b[1])
self.assertRaises(TypeError, flamingo.image.load, *b[2])
class TestLoadSheet(unittest.TestCase):
def testLoadSheetH(self):
g = [(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 100, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 600, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 100, 0, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 0, 100, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 700, 100, [])]
t = flamingo.image.load_sheeth(*g[0])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheeth(*g[1])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 600)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 1)
t = flamingo.image.load_sheeth(*g[2])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheeth(*g[3])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 1)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 600)
t = flamingo.image.load_sheeth(*g[4])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 600)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 1)
def testLoadSheetV(self):
g = [(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 600, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 0, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 0, 100, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 700, 100, [])]
t = flamingo.image.load_sheetv(*g[0])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheetv(*g[1])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 600)
self.assertEqual(len(t), 1)
t = flamingo.image.load_sheetv(*g[2])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheetv(*g[3])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 1)
self.assertEqual(len(t), 600)
t = flamingo.image.load_sheetv(*g[4])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 600)
self.assertEqual(len(t), 1)
def testBad(self):
b = [(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), "100", 1, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchvt.png"), 100, 750, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, "750", []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 750, [(1,)])]
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load_sheeth, *b[1])
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[2])
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[3])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load_sheetv, *b[1])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[2])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[3])
class TestTexture(unittest.TestCase):
def setUp(self):
self.t = flamingo.image.load(os.path.join(flamingo.fl_path, "tests/res/test.gif"))
self.width = 347
self.height = 326
self.speed = 750
self.length = 5
def testAccess(self):
self.assertEqual(self.t.width, self.width)
self.assertEqual(self.t.height, self.height)
self.assertEqual(self.t.speed, self.speed)
self.assertEqual(len(self.t), self.length)
self.assertEqual(self.t.frame, 0)
self.t.speed = -2
self.t.frame = 6
self.assertEqual(self.t.speed, -2)
self.assertEqual(self.t.frame, 1)
try:
self.t.width = 400
self.fail()
except TypeError:
pass
try:
self.t.height = 400
self.fail()
except TypeError:
pass
def testUpdate(self):
self.t.speed = 750
self.t.frame = 0
self.t.update(700)
self.assertEqual(self.t.frame, 0)
self.t.update(50)
self.assertEqual(self.t.frame, 1)
self.t.frame = 0
self.t.update(3750)
self.assertEqual(self.t.frame, 0)
##-------- Test Suite
testload = unittest.TestLoader().loadTestsFromTestCase(TestLoad)
testloadsheet = unittest.TestLoader().loadTestsFromTestCase(TestLoadSheet)
testtexture = unittest.TestLoader().loadTestsFromTestCase(TestTexture)
testsuite = unittest.TestSuite((testload, testloadsheet, testtexture))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import unittest
import pickle
import flamingo
import flmath_test
class TestMesh(unittest.TestCase):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
def testAccess(self):
self.assertEqual(len(self.m), 3)
v = self.m.v[0]
t = self.m.t[0]
self.assertEqual(flamingo.mesh.MeshNode, type(t))
self.assertEqual(flamingo.mesh.VMeshNode, type(v))
class TestMeshNode(flmath_test.TestVector):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
self.v = self.m.t[0]
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
class TestVMeshNode(flmath_test.TestVector):
def setUp(self):
self.m = flamingo.mesh.Mesh([flamingo.mesh.VMeshNode((111, 222)),
flamingo.mesh.VMeshNode((333, 444)),
flamingo.mesh.VMeshNode((111, 444))],
[flamingo.mesh.MeshNode((111, 222)),
flamingo.mesh.MeshNode((333, 444)),
flamingo.mesh.MeshNode((111, 444))])
self.v = self.m.v[0]
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assertEqual(v.x, 111)
self.assertEqual(v.y, 222)
v.x = 333
v[1] = 444
self.assertEqual(v[0], 333)
self.assertEqual(v[1], 444)
## More stuff later
##-------- Test Suite
testmesh = unittest.TestLoader().loadTestsFromTestCase(TestMesh)
testnode = unittest.TestLoader().loadTestsFromTestCase(TestMeshNode)
testvnode = unittest.TestLoader().loadTestsFromTestCase(TestVMeshNode)
testsuite = unittest.TestSuite((testmesh, testnode, testvnode))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import unittest
import pickle
import flamingo
class TestScreen(unittest.TestCase):
def setUp(self):
self.p = flamingo.screen.Screen((0, 0), 800, 600)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), 2, 3]]
def testAccess(self):
self.assertEqual(self.p.center, (400, 300))
self.assertEqual(self.p.local_rect, ((0, 0), (800, 0), (800, 600), (0, 600)))
self.p.height = 400
self.assertEqual(self.p.local_rect.height, 600)
self.assertTrue(self.p.local_rect.enabled(flamingo.constants.POLYGON_AXIS_ALIGNED))
self.assertRaises(AttributeError, flamingo.screen.Screen.disable,
self.p.local_rect, flamingo.constants.POLYGON_AXIS_ALIGNED)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Rect, b)
##-------- Test Suite
testscreen = unittest.TestLoader().loadTestsFromTestCase(TestScreen)
testsuite = unittest.TestSuite((testscreen))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
from . import flmath_test
from . import image_test
from . import mesh_test
from . import screen_test
from . import sprite_test
| Python |
#!/usr/bin/env python
## fl - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import os
import unittest
import pickle
import flamingo as fl
##-------- Data
i = fl.image.load(os.path.join(fl.fl_path, "tests/res/glass.bmp"))
ii = fl.image.load(os.path.join(fl.fl_path, "tests/res/swatch.png"))
iii = fl.image.load(os.path.join(fl.fl_path, "tests/res/swatchv.png"))
sk = {"glass": i, "swatch": ii}
SPR1 = fl.sprite.Sprite(i, default="glass")
SPR2 = fl.sprite.Sprite(sk, SPR1, default="glass")
SGRP = fl.sprite.Group()
UGRP = SPR2.groups()[0]
##-------- Test Cases
class TestSprite(unittest.TestCase):
def testAccess(self):
self.assertEqual(SPR1.center, (0,0))
SPR1.center += 100
self.assertEqual(SPR1.center, (100, 100))
SPR1.center -= 100
self.assertEqual(SPR1.z, 0)
SPR1.z = 200
self.assertEqual(SPR1.z, 200)
objste = SPR1.state
self.assertEqual(fl.sprite.ObjectState, objste.__class__)
self.assertEqual(SPR1.texture.width, 128)
self.assertEqual(SPR1.texture.height, 128)
tex = SPR2.texture
self.assertEqual(fl.image.Texture, tex.__class__)
self.assertEqual(tex, SPR2['glass'])
self.assertNotEqual(tex, SPR2['swatch'])
self.assertEqual(len(SPR2), 2)
self.assertEqual(SPR2.skins, sk)
## Color
self.assertEqual(SPR1.parent, None)
self.assertEqual(SPR2.parent, SPR1)
self.assertNotEqual(SPR1.groups(), [])
self.assertEqual(len(SPR1.groups()), 1)
def testGroups(self):
SPR1.add(SGRP)
self.assertTrue(SGRP in SPR1.groups())
SPR1.remove(SGRP)
self.assertTrue(SGRP not in SPR1.groups())
SPR1.add(SGRP)
SPR1.kill()
self.assertEqual(len(SPR1.groups()), 0)
def testSkins(self):
new_skin = {'swatchv': iii}
SPR2.change_skin('swatch')
self.assertEqual(SPR2.texture, ii)
self.assertRaises(AttributeError, fl.sprite.Sprite.remove_skin, SPR2, 'swatch')
self.assertRaises(KeyError, fl.sprite.Sprite.remove_skin, SPR2, 'swatc')
SPR2.merge_skins(new_skin)
self.assertEqual(SPR2.skins, {'glass': i, 'swatch': ii, 'swatchv': iii})
SPR1.add_skin('swatch', ii)
SPR1.remove_skin('swatch')
SPR2.remove_skin('swatchv')
self.assertRaises(KeyError, fl.sprite.Sprite.change_skin, SPR1, 'swatch')
def testUpdate(self):
SPR1._update(0)
SPR1.center = 1, 1
SPR1.color = fl.flcolor.Color(0, 0, 0, 0)
self.assertNotEqual(SPR1.center, SPR1.prevstate.bound.center)
self.assertEqual(SPR1.prevstate.bound.center, (0,0))
self.assertNotEqual(SPR1.color, SPR1.prevstate.color)
self.assertEqual(SPR1.color, (0,0,0,0))
self.assertEqual(SPR1.prevstate.color, (1, 1, 1, 1))
SPR1.center = 0, 0
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
class TestObjectState(unittest.TestCase):
def testAccess(self):
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
self.assertEqual(SPR1.color, (1, 1, 1 ,1))
self.assertEqual(SPR1.state.bound, ((-64,-64), (64, -64), (64, 64), (-64, 64)))
def testInterpolate(self):
SPR1._update(0)
SPR1.center = 1, 1
SPR1.prevstate.color = fl.flcolor.Color(1,1,1,1)
SPR1.color = fl.flcolor.Color(0, 0, 0, 0)
interstate = SPR1.interpolate(0.5)
self.assertEqual(interstate.color, (0.5, 0.5, 0.5, 0.5))
self.assertEqual(interstate.bound.center, (0.5, 0.5))
SPR1.center = 0, 0
SPR1.color = fl.flcolor.Color(1, 1, 1, 1)
def testPickle(self):
test_str = pickle.dumps(SPR1.state)
loaded = pickle.loads(test_str)
self.assertEqual(SPR1.state.color, loaded.color)
self.assertEqual(SPR1.state.bound, loaded.bound)
class TestGroup(unittest.TestCase):
def testAccess(self):
self.assertTrue(isinstance(UGRP.sprites(), list))
self.assertEqual(len(UGRP.sprites()), 1)
self.assertTrue(SPR2 in UGRP.sprites())
def testManagement(self):
SGRP.add(SPR1)
SGRP.add(SPR1)
self.assertTrue(SPR1 in SGRP.sprites())
SGRP.add(SPR2)
self.assertTrue(SPR2 in SGRP.sprites())
SGRP.remove(SPR2)
self.assertTrue(SPR2 not in SGRP.sprites())
SGRP.empty()
self.assertEqual(len(SGRP.sprites()), 0)
##-------- Test Suite
testsprite = unittest.TestLoader().loadTestsFromTestCase(TestSprite)
testobjectstate = unittest.TestLoader().loadTestsFromTestCase(TestObjectState)
testgroup = unittest.TestLoader().loadTestsFromTestCase(TestGroup)
testsuite = unittest.TestSuite((testsprite, testobjectstate, testgroup))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Unit Tests for flamingo.flmath"""
import unittest
import flamingo
import math
import pickle
from numbers import Number
class TestPow(unittest.TestCase):
def setUp(self):
self.data = [2, 3, 4, 7, 17, 710, 483, 60495, 712345]
self.bad = ["hello world!", [1, 2, 3], {'foo': 'bar'},
flamingo.flmath.Vector([1, 1])]
def testClosestIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.closest_pow2(d), Number))
def testClosestIsPow2(self):
for d in self.data:
result = flamingo.flmath.closest_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testClosestIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.closest_pow2(d) >= 1)
def testClosestIsClosest(self):
for d in self.data:
less = math.pow(2, math.ceil(math.log(d)/math.log(2.0)))
greater = math.pow(2, math.floor(math.log(d)/math.log(2.0)))
lessd = d - less
greaterd = greater - d
if lessd < greaterd:
self.assertEqual(flamingo.flmath.closest_pow2(d), greater)
else:
self.assertEqual(flamingo.flmath.closest_pow2(d), less)
def testClosestBad(self):
for b in self.bad:
self.assertRaises(TypeError,
flamingo.flmath.closest_pow2, b)
def testClosestNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.closest_pow2, -d)
def testNextIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.next_pow2(d), Number))
def testNextIsPow2(self):
for d in self.data:
result = flamingo.flmath.next_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testNextIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.next_pow2(d) >= 1)
def testNextGreater(self):
for d in self.data:
result = flamingo.flmath.next_pow2(d)
self.assertTrue(result >= d)
def testNextBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.next_pow2, b)
def testNextNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.next_pow2, -d)
def testPrevIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.prev_pow2(d), Number))
def testPrevIsPow2(self):
for d in self.data:
result = flamingo.flmath.prev_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testPrevIsOne(self):
for d in self.data:
self.assertTrue(flamingo.flmath.prev_pow2(d) >= 1)
def testPrevLess(self):
for d in self.data:
result = flamingo.flmath.prev_pow2(d)
if result is None:
self.assertTrue(False)
self.assertTrue(result <= d)
def testPrevBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.prev_pow2, b)
def testPrevNeg(self):
for d in self.data:
self.assertRaises(ValueError, flamingo.flmath.prev_pow2, -d)
class TestDistance(unittest.TestCase):
def setUp(self):
## data = [[point, point, distance, distance_sq]]
self.data = [[(0, 0), (0, 1), 1, 1],
[(2.5, 2),(4.76, 3.1), 2.5134, 6.3176],
[(10, 16),(100, 160), 169.8116, 28836],
[flamingo.flmath.Vector([1.2, 1]), flamingo.flmath.Vector([16, 1]), 14.8, 219.04],
[(0, 0), (0, 0), 0, 0],
[flamingo.flmath.Vector([0, 0]), flamingo.flmath.Vector([0, 0]), 0, 0]]
self.long = [[(21, 4, 6, 4, 3), (14, 16, 71, 723, 5)],
[(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)],
[(1, 2, 3, 4), (5, 4, 3, 2, 1)]]
self.short = [[(), ()]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.distance(d[0], d[1]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(flamingo.flmath.distance(d[0], d[1]) >= 0)
def testValue(self):
for d in self.data:
result = flamingo.flmath.distance(d[0], d[1])
self.assertEqual(round(result, 2), round(d[2], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.distance, b[0],b[1])
##-------- Sq
def testIsNumberSq(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.distance_sq(d[0], d[1]), Number))
def testIsPosSq(self):
for d in self.data:
self.assertTrue(flamingo.flmath.distance_sq(d[0], d[1]) >= 0)
def testValueSq(self):
for d in self.data:
result = flamingo.flmath.distance_sq(d[0], d[1])
self.assertEqual(round(result, 2), round(d[3], 2))
def testBadSq(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.distance_sq, b[0],b[1])
class TestMidpoint(unittest.TestCase):
def setUp(self):
## data = [[point, point, midpoint]]
self.data = [[(0, 0), (0, 1), (0, 0.5)],
[(2.5, 2),(4.76, 3.1), (3.63, 2.55)],
[(10, 16),(100, 160), (55, 88)],
[flamingo.flmath.Vector([1.13, 1]), (16, 1), (8.565, 1)],
[(0, 0), (0, 0), (0, 0)]]
self.wrong = [[(), ()],
[(2,), (1,)]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testValue(self):
for d in self.data:
result = flamingo.flmath.midpoint(d[0], d[1])
self.assertEqual(round(result[0]), round(d[2][0]))
self.assertEqual(round(result[1]), round(d[2][1]))
def testWrong(self):
for d in self.wrong:
self.assertRaises(TypeError, flamingo.flmath.midpoint, d[0], d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.midpoint, b[0],b[1])
class TestArea(unittest.TestCase):
def setUp(self):
## [[data], area, signed_area]
self.data = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], 4, 4],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], 4, -4],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], 1002.66, 1002.66 ],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], 1002.66, -1002.66 ]]
self.odata = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], True],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], False],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], True],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], False]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}],
[(1,), (2,), (3,)],
[(1, 2), (3, 4)],
[(1, 2)],
[]]
##-------- Pos Area
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.area(d[0]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(flamingo.flmath.area(d[0]) > 0)
def testValue(self):
for d in self.data:
result = flamingo.flmath.area(d[0])
self.assertEqual(round(result, 2), round(d[1], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.area, b)
##-------- Signed Area
def testIsNumberS(self):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.signed_area(d[0]), Number))
def testValueS(self):
for d in self.data:
result = flamingo.flmath.signed_area(d[0])
self.assertEqual(round(result, 2), round(d[2], 2))
def testBadS(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.signed_area, b)
##-------- Orientation
def testValueO(self):
for d in self.odata:
result = flamingo.flmath.orientation_poly(d[0])
self.assertEqual(result, d[1])
def testBadO(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.orientation_poly, b)
class TestNormalizeAngle(unittest.TestCase):
def setUp(self):
self.datad = [[45, 45],
[360, 0],
[400, 40],
[4000, 40],
[-100, 260]]
self.datar = [[math.radians(45), math.radians(45)],
[math.radians(360), math.radians(0)],
[math.radians(400), math.radians(40)],
[math.radians(4000), math.radians(40)],
[math.radians(-100), math.radians(260)]]
self.bad = ["meow",
[16],
{'foo': 'bar'}]
##-------- Degress
def testNumber(self):
for i in range(0, 1000):
self.assertTrue(isinstance(flamingo.flmath.normalize_angle(i), Number))
def testIsPos(self):
for i in range(0, 1000):
self.assertTrue(flamingo.flmath.normalize_angle(i) >= 0)
def testValue(self):
for d in self.datad:
self.assertEqual(flamingo.flmath.normalize_angle(d[0]), d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_angle, b)
##-------- Radians
def testNumberR(self):
for i in range(0, 1000):
self.assertTrue(isinstance(flamingo.flmath.normalize_angler(i), Number))
def testIsPosR(self):
for i in range(0, 1000):
self.assertTrue(flamingo.flmath.normalize_angler(i) >= 0)
def testValueR(self):
for d in self.datar:
self.assertAlmostEqual(flamingo.flmath.normalize_angler(d[0]), d[1])
def testBadR(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_angler, b)
class TestNormalizePoly(unittest.TestCase):
def setUp(self):
self.p = [flamingo.flmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1)]
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testNormalize(self):
self.assertEqual(flamingo.flmath.normalize_poly(self.p), self.p)
p = [flamingo.flmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1), (-1, 1)]
self.assertEqual(flamingo.flmath.normalize_poly(p), self.p)
self.assertEqual(flamingo.flmath.normalize_poly(self.p, 1), p)
p = [(-1,1), (-1,-1), [1,-1], (1,1), (-1, 1), (-1,-1)]
self.assertEqual(flamingo.flmath.normalize_poly(p), self.p)
self.assertEqual(flamingo.flmath.normalize_poly(self.p, 2), p)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.normalize_poly, b)
class TestPolySimplify(unittest.TestCase):
def setUp(self):
self.data = [[(1, 0), (1, 8.12), (19.95, 5), (-1, -5), (-1.25, -5.15)],
[[-1, 0], [-1, -4.12], [-16.95, -5], [14, 5], [1.25, 5.15]]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}]]
def testReturnsList(self):
for i in range(8):
for d in self.data:
self.assertTrue(isinstance(flamingo.flmath.simplify_poly(d, i), list))
def testReturnsCoords(self):
for i in range(8):
for d in self.data:
result = flamingo.flmath.simplify_poly(d, i)
b = True
for p in result:
if not (isinstance(p[0], Number) and isinstance(p[1], Number)):
b = b and False
break
self.assertTrue(b)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.simplify_poly, b, 1)
class TestVector(unittest.TestCase):
def setUp(self):
self.v = flamingo.flmath.Vector((111, 222))
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assertEqual(v.x, 111)
self.assertEqual(v.y, 222)
v.x = 333
v[1] = 444
self.assertEqual(v[0], 333)
self.assertEqual(v[1], 444)
def testMath(self):
v = self.v.copy()
self.assertEqual(v + 1, flamingo.flmath.Vector((112, 223)))
self.assertEqual(v - 2, [109,220])
self.assertEqual(v * 3, (333,666))
self.assertEqual(v / 2.0, flamingo.flmath.Vector((55.5, 111)))
self.assertEqual(v / 2, (55.5, 111))
self.assertEqual(v ** flamingo.flmath.Vector((2,3)), [12321, 10941048])
self.assertEqual(v + [-11, 78], flamingo.flmath.Vector((100, 300)))
def testReverseMath(self):
v = self.v.copy()
self.assertEqual(1 + v, flamingo.flmath.Vector((112,223)))
self.assertEqual(2 - v, [-109,-220])
self.assertEqual(3 * v, (333,666))
self.assertEqual([111,222] ** flamingo.flmath.Vector((2,3)), [12321, 10941048])
self.assertEqual(v + flamingo.flmath.Vector((1,1)), [112, 223])
def testInplaceMath(self):
inplace_vec = flamingo.flmath.Vector((5, 13))
inplace_src = flamingo.flmath.Vector((inplace_vec))
inplace_vec *= .5
inplace_vec += .5
inplace_vec /= 3
inplace_vec += flamingo.flmath.Vector((-1, -1))
alternate = (inplace_src*.5 + .5)/3 + [-1, -1]
self.assertEqual(inplace_vec, alternate)
def testUnary(self):
v = self.v.copy()
v = -v
self.assertEqual(v, [-111,-222])
v = abs(v)
self.assertEqual(v, [111,222])
def testLength(self):
v = flamingo.flmath.Vector((3, 4))
self.assertEqual(v.length, 5)
v.length = 10
self.assertEqual(v, [6, 8])
def testAngles(self):
v = flamingo.flmath.Vector((0,3))
self.assertEqual(v.angle, 90)
v.angle = 0
self.assertEqual(v, (3, 0))
v2 = (-3,0)
self.assertEqual(v.angle_about(v2), 0)
v2 = flamingo.flmath.Vector(v2)
self.assertEqual(v2.angle_about(v), 180)
v.angle = 90, (0,0)
self.assertEqual(v, [0, 3])
def testComparison(self):
int_vec = flamingo.flmath.Vector((3, -2))
flt_vec = flamingo.flmath.Vector((3.0, -2.0))
zero_vec = flamingo.flmath.Vector((0, 0))
self.assertEqual(int_vec, flt_vec)
self.assertNotEqual(int_vec, zero_vec)
self.assertFalse(flt_vec == zero_vec)
self.assertFalse(flt_vec != int_vec)
self.assertEqual(int_vec, (3, -2))
self.assertNotEqual(int_vec, [0, 0])
self.assertNotEqual(int_vec, 5)
def testConversion(self):
self.assertEqual(list(self.v), [111, 222])
self.assertTrue(isinstance(list(self.v), list))
self.assertEqual(tuple(self.v), (111, 222))
self.assertTrue(isinstance(tuple(self.v), tuple))
def testPickle(self):
testvec = flamingo.flmath.Vector((5, .3))
testvec_str = pickle.dumps(testvec)
loaded_vec = pickle.loads(testvec_str)
self.assertEqual(testvec, loaded_vec)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Vector, b)
class TestPolygon(unittest.TestCase):
def setUp(self):
self.p = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.bad = [[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]]]
def testAccess(self):
p = self.p.copy()
self.assertEqual(p[0], (-1, 1))
p[0] = (-5, 5)
self.assertEqual(p[0], (-5, 5))
self.assertTrue(isinstance(p[0], flamingo.flmath.Vector))
self.assertEqual(p.center, (-1, 1))
p[1] = -4, 7
self.assertEqual(p[1], (-4, 7))
p[3] = 16
self.assertEqual(p[3], (16, 16))
def testComparison(self):
p = self.p.copy()
self.assertEqual(p, [(-1,1), (-1,-1), (1,-1), (1,1)])
q = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.assertEqual(p, q)
q[0] = -5, 5
self.assertNotEqual(p, q)
self.assertNotEqual(q, p)
def testAppend(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.append, p, (0, 2.5))
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.append((0, 2.5))
self.assertEqual(len(p), 5)
self.assertEqual(p.center, (0, 0.5))
p[4] -= 0, 1
self.asserEqual(p.center, (0,0))
p.append((-0.5, 1))
self.assertEqual(len(p), 6)
self.asserEqual(p.center, (0,0))
def testInsert(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.insert, p, 1, (-2.5, 0))
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.insert(1, (-2.5, 0))
self.assertEqual(len(p), 5)
self.assertEqual(p.center, (-0.5, 0))
def testRemove(self):
p = self.p.copy()
self.assertRaises(AttributeError, flamingo.flmath.Polygon.insert, p, 3)
p.enable(flamingo.constants.POLYGON_MUTABLE_LENGTH)
p.remove(3)
self.assertEqual(len(p), 3)
self.assertEqual(p.center, -1.0/3)
self.assertRaises(TypeError, Polygon.remove, p, 1)
def testConversion(self):
p = self.p.copy()
self.assertEqual(list(p), p)
self.assertTrue(isinstance(list(p), list))
self.assertEqual(tuple(p), p)
self.assertTrue(isinstance(tuple(p), tuple))
def testAngle(self):
p = self.p.copy()
self.assertEqual(p.angle, 0)
p.center = 1,0
self.assertEqual(p.angle, 0)
p.center = 0, 10
self.assertEqual(p.angle, 90)
def testOrientation(self):
p = self.p.copy()
self.assertEqual(p.orientation, 0)
l = list(p)
p.orientation = 90
self.assertNotEqual(p, l)
self.assertAlmostEqual(p[0].x, -1, 0.001)
self.assertAlmostEqual(p[0].y, -1, 0.001)
self.assertAlmostEqual(p[1].x, 1, 0.001)
self.assertAlmostEqual(p[1].y, -1, 0.001)
self.assertAlmostEqual(p[2].x, 1, 0.001)
self.assertAlmostEqual(p[2].y, 1, 0.001)
self.assertAlmostEqual(p[3].x, -1, 0.001)
self.assertAlmostEqual(p[3].y, 1, 0.001)
def testCollision(self):
p1 = self.p.copy()
p2 = [(-0.5,0.5), (-0.5,-0.5), (0.5,-0.5), (0.5,0.5)]
self.assertTrue(p1.intersects(p2))
self.assertTrue(p1.intersects(p1))
p1.center = 90, -60
self.assertFalse(p1.intersects(p2))
p1.center = 1.5, 0
self.assertTrue(p1.intersects(p2))
p1.center = 0, -1.5
self.assertTrue(p1.intersects(p2))
p1.center = -1.4, 0
self.assertTrue(p1.intersects(p2))
def testPickle(self):
testpoly = flamingo.flmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
testpoly_str = pickle.dumps(testpoly)
loaded_poly = pickle.loads(testpoly_str)
self.assertEqual(testpoly, loaded_poly)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Polygon, b)
class TestRect(unittest.TestCase):
def setUp(self):
self.p = flamingo.flmath.Rect((0, 0), 2, 2)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testAccess(self):
p = self.p.copy()
self.assertEqual(p.center, (0,0))
self.assertEqual(p.topleft, (-1, 1))
self.assertEqual(p.bottomleft, (-1, -1))
p.center = 1, 3
self.assertEqual(p.center, (1, 3))
p.topright = 4
self.assertEqual(p.topright, (4, 4))
self.assertEqual(p.bottomright, (4, 2))
p[1] = 4, 1
self.assertEqual(p.topright, (4, 3))
self.assertEqual(p.bottomright, (4, 1))
p.width = 4
self.assertEqual(p.topright, (5, 3))
p.size = (1, 1)
self.assertEqual(p.topleft, (2.5, 2.5))
def testComparison(self):
p = self.p.copy()
q = [(-1, -1), (1, -1), (1, 1), (-1, 1)]
self.assertEqual(p, q)
q[3] = (-1, 2)
self.assertNotEqual(p, q)
def testAppend(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.append, p, (0,0))
def testInsert(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.insert, p, 1, (0,0))
def testRemove(self):
p = self.p.copy()
self.assertRaises(TypeError, flamingo.flmath.Rect.remove, p, 1)
def testAngle(self):
p = self.p.copy()
self.assertEqual(p.angle, 0)
p.center = 1,0
self.assertEqual(p.angle, 0)
p.center = 0, 10
self.assertEqual(p.angle, 90)
p.angle = 0
self.assertEqual(p.center, (10, 0))
def testOrientation(self):
p = self.p.copy()
self.assertEqual(p.orientation, 0)
l = list(p)
p.orientation = 90
self.assertNotEqual(p, l)
self.assertAlmostEqual(p[0].x, 1, 0.001)
self.assertAlmostEqual(p[0].y, -1, 0.001)
self.assertAlmostEqual(p[1].x, 1, 0.001)
self.assertAlmostEqual(p[1].y, 1, 0.001)
self.assertAlmostEqual(p[2].x, -1, 0.001)
self.assertAlmostEqual(p[2].y, 1, 0.001)
self.assertAlmostEqual(p[3].x, -1, 0.001)
self.assertAlmostEqual(p[3].y, -1, 0.001)
def testConversion(self):
p = self.p.copy()
self.assertEqual(list(p), p)
self.assertTrue(isinstance(list(p), list))
self.assertEqual(tuple(p), p)
self.assertTrue(isinstance(tuple(p), tuple))
def testPickle(self):
testrect = flamingo.flmath.Rect((-1, 1), 2, 2)
testrect_str = pickle.dumps(testrect)
loaded_rect = pickle.loads(testrect_str)
self.assertEqual(testrect, loaded_rect)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, flamingo.flmath.Rect, b)
##-------- Test Suite
testpow = unittest.TestLoader().loadTestsFromTestCase(TestPow)
testdistance = unittest.TestLoader().loadTestsFromTestCase(TestDistance)
testmidpoint = unittest.TestLoader().loadTestsFromTestCase(TestMidpoint)
testarea = unittest.TestLoader().loadTestsFromTestCase(TestArea)
testnormalized = unittest.TestLoader().loadTestsFromTestCase(TestNormalizeAngle)
testnormalizepoly = unittest.TestLoader().loadTestsFromTestCase(TestNormalizePoly)
testsimplify = unittest.TestLoader().loadTestsFromTestCase(TestPolySimplify)
testvector = unittest.TestLoader().loadTestsFromTestCase(TestVector)
testpolygon = unittest.TestLoader().loadTestsFromTestCase(TestPolygon)
testrect = unittest.TestLoader().loadTestsFromTestCase(TestRect)
testsuite = unittest.TestSuite((testpow, testdistance, testmidpoint, testarea,
testnormalized, testnormalizepoly, #testsimplify,
testvector, testpolygon, testrect))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## bradzeis@gmail.com
import os
import unittest
import pickle
import flamingo
class TestLoad(unittest.TestCase):
def testLoad(self):
good = [(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/glass.bmp"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/test.gif"), -1, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/test.gif"), 740, [])]
for g in good:
self.assertTrue(isinstance(flamingo.image.load(*g), flamingo.image.Texture))
def testBad(self):
b = [(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), "-1", []),
(os.path.join(flamingo.fl_path, "tests/res/flaming.png"), -1, []),
(os.path.join(flamingo.fl_path, "tests/res/flamingo.png"), "-1", [(1,)])]
self.assertRaises(TypeError, flamingo.image.load, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load, *b[1])
self.assertRaises(TypeError, flamingo.image.load, *b[2])
class TestLoadSheet(unittest.TestCase):
def testLoadSheetH(self):
g = [(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 100, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 600, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 100, 0, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 0, 100, []),
(os.path.join(flamingo.fl_path, "tests/res/swatch.png"), 700, 100, [])]
t = flamingo.image.load_sheeth(*g[0])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheeth(*g[1])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 600)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 1)
t = flamingo.image.load_sheeth(*g[2])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheeth(*g[3])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 1)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 600)
t = flamingo.image.load_sheeth(*g[4])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 600)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 1)
def testLoadSheetV(self):
g = [(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 600, 0, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 0, [(), ()]),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 0, 100, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 700, 100, [])]
t = flamingo.image.load_sheetv(*g[0])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheetv(*g[1])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 600)
self.assertEqual(len(t), 1)
t = flamingo.image.load_sheetv(*g[2])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 100)
self.assertEqual(len(t), 6)
t = flamingo.image.load_sheetv(*g[3])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 1)
self.assertEqual(len(t), 600)
t = flamingo.image.load_sheetv(*g[4])
self.assertTrue(isinstance(t, flamingo.image.Texture))
self.assertEqual(t.width, 100)
self.assertEqual(t.height, 600)
self.assertEqual(len(t), 1)
def testBad(self):
b = [(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), "100", 1, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchvt.png"), 100, 750, []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, "750", []),
(os.path.join(flamingo.fl_path, "tests/res/swatchv.png"), 100, 750, [(1,)])]
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load_sheeth, *b[1])
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[2])
self.assertRaises(TypeError, flamingo.image.load_sheeth, *b[3])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[0])
self.assertRaises(flamingo.image.LoadingError, flamingo.image.load_sheetv, *b[1])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[2])
self.assertRaises(TypeError, flamingo.image.load_sheetv, *b[3])
class TestTexture(unittest.TestCase):
def setUp(self):
self.t = flamingo.image.load(os.path.join(flamingo.fl_path, "tests/res/test.gif"))
self.width = 347
self.height = 326
self.speed = 750
self.length = 5
def testAccess(self):
self.assertEqual(self.t.width, self.width)
self.assertEqual(self.t.height, self.height)
self.assertEqual(self.t.speed, self.speed)
self.assertEqual(len(self.t), self.length)
self.assertEqual(self.t.frame, 0)
self.t.speed = -2
self.t.frame = 6
self.assertEqual(self.t.speed, -2)
self.assertEqual(self.t.frame, 1)
try:
self.t.width = 400
self.fail()
except TypeError:
pass
try:
self.t.height = 400
self.fail()
except TypeError:
pass
def testUpdate(self):
self.t.speed = 750
self.t.frame = 0
self.t.update(700)
self.assertEqual(self.t.frame, 0)
self.t.update(50)
self.assertEqual(self.t.frame, 1)
self.t.frame = 0
self.t.update(3750)
self.assertEqual(self.t.frame, 0)
##-------- Test Suite
testload = unittest.TestLoader().loadTestsFromTestCase(TestLoad)
testloadsheet = unittest.TestLoader().loadTestsFromTestCase(TestLoadSheet)
testtexture = unittest.TestLoader().loadTestsFromTestCase(TestTexture)
testsuite = unittest.TestSuite((testload, testloadsheet, testtexture))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
from . import flmath_test
from . import image_test
from . import mesh_test
from . import screen_test
from . import sprite_test
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import flamingo as fl
class Game(fl.game.Game):
def init(self, *args):
self.screen1 = fl.screen.Screen((0, 0), 800, 600)
self.add_screen(self.screen1)
self.screen1.center = 400, 300
fl.event.bind(lambda: self.data.screens[0].__setattr__('centerx', self.data.screens[0].centerx + 1),
fl.constants.K_d, fl.constants.KEYHOLD, mods=fl.event.Mods([], [fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('centerx', self.data.screens[0].centerx - 1),
fl.constants.K_a, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('centery', self.data.screens[0].centery + 1),
fl.constants.K_w, fl.constants.KEYHOLD, delay=5)
fl.event.bind(lambda: self.data.screens[0].__setattr__('centery', self.data.screens[0].centery - 1),
fl.constants.K_s, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom * 0.96),
fl.constants.MS_DOWN, fl.constants.SCROLLWHEEL, mods=fl.event.Mods([fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom / 0.96),
fl.constants.MS_UP, fl.constants.SCROLLWHEEL, mods=fl.event.Mods([fl.constants.K_LSHIFT]))
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom * 0.96),
fl.constants.K_i, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('zoom', self.data.screens[0].zoom / 0.96),
fl.constants.K_o, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('orientation', self.data.screens[0].orientation + 1),
fl.constants.K_k, fl.constants.KEYHOLD)
fl.event.bind(lambda: self.data.screens[0].__setattr__('orientation', self.data.screens[0].orientation - 1),
fl.constants.K_l, fl.constants.KEYHOLD)
fl.event.bind(self.data.master_clock.pause, fl.constants.K_COMMA, fl.constants.KEYDOWN)
fl.event.bind(self.data.master_clock.resume, fl.constants.K_PERIOD, fl.constants.KEYDOWN)
fl.event.bind(self.quit_game, fl.constants.K_ESCAPE, fl.constants.KEYDOWN)
def start_game(self):
i = fl.image.load("res/flamingo.png")
ii = fl.image.load("res/test.gif")
iii = fl.image.load_sheeth("res/swatch.png", width=100, speed=50)
s1 = fl.sprite.Sprite(i)
s1.center = (200, 450)
s2 = fl.sprite.Sprite(ii)
s2.center = (400, 300)
s2.color.a = 0.08
s3 = fl.sprite.Sprite(iii)
s3.center = (600, 150)
s3.color.a = 0.08
t = fl.fltime.Timer(15000)
fl.event.bind(self.quit_game, t, fl.constants.TIMEREND)
fl.event.bind(t.start, fl.constants.K_SPACE, fl.constants.KEYDOWN)
def p():
self.screen1.orientation = -(144**(t.percent() * 1.5) - 1)
self.screen1.zoom = 0.005 + t.percent_left() * 0.995
#s2.color.a = t.percent_left()
s1.color.b = 1 - 0.5 * t.percent()
s3.color.r = t.percent_left()
s3.color.g = 1 - 0.5 * t.percent()
def va():
s1.bones[0].angle -= .03
s1.bones[0][0].angle -= .02
s1.bones[1].angle -= .1
s1.bones[1][0].angle -= .03
s1.bones[1].length -= .01
s1.bones[2].angle -= .015
s1.bones[2][0].angle -= .01
s1.bones[3].angle -= -.005
s1.bones[3][0].angle -= -.008
def vs():
s1.bones[0].angle += .03
s1.bones[0][0].angle += .02
s1.bones[1].angle += .1
s1.bones[1][0].angle += .03
s1.bones[1].length += .01
s1.bones[2].angle += .015
s1.bones[2][0].angle += .01
s1.bones[3].angle += -.005
s1.bones[3][0].angle += -.008
fl.event.bind(va, fl.constants.K_DOWN, fl.constants.KEYHOLD)
fl.event.bind(vs, fl.constants.K_UP, fl.constants.KEYHOLD)
fl.event.bind(p, t, fl.constants.TIMERTICK)
if __name__ == "__main__":
fl.util.enable_logging()
try:
import psyco
psyco.full()
except ImportError:
pass
game = Game()
game.run(True, 0)
| Python |
#!/usr/bin/env python
"""Unit Tests for fmath.py"""
import unittest
import flamingo.fmath as fmath
import math
import pickle
from numbers import Number
class TestPow(unittest.TestCase):
def setUp(self):
self.data = [2, 3, 4, 7, 17, 710, 483, 60495, 712345]
self.bad = ["hello world!", [1, 2, 3], {'foo': 'bar'},
fmath.Vector([1, 1])]
def testClosestIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.closest_pow2(d),
Number))
def testClosestIsPow2(self):
for d in self.data:
result = fmath.closest_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testClosestIsOne(self):
for d in self.data:
self.assertTrue(fmath.closest_pow2(d) >= 1)
def testClosestIsClosest(self):
for d in self.data:
less = math.pow(2, math.ceil(math.log(d)/math.log(2.0)))
greater = math.pow(2, math.floor(math.log(d)/math.log(2.0)))
lessd = d - less
greaterd = greater - d
if lessd < greaterd:
self.assertEqual(fmath.closest_pow2(d), greater)
else:
self.assertEqual(fmath.closest_pow2(d), less)
def testClosestBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.closest_pow2, b)
def testClosestNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.closest_pow2, -d)
def testNextIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.next_pow2(d),
Number))
def testNextIsPow2(self):
for d in self.data:
result = fmath.next_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testNextIsOne(self):
for d in self.data:
self.assertTrue(fmath.next_pow2(d) >= 1)
def testNextGreater(self):
for d in self.data:
result = fmath.next_pow2(d)
self.assertTrue(result >= d)
def testNextBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.next_pow2, b)
def testNextNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.next_pow2, -d)
def testPrevIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.prev_pow2(d),
Number))
def testPrevIsPow2(self):
for d in self.data:
result = fmath.prev_pow2(d)
self.assertEqual(math.log(result, 2) % 1, 0.0)
def testPrevIsOne(self):
for d in self.data:
self.assertTrue(fmath.prev_pow2(d) >= 1)
def testPrevLess(self):
for d in self.data:
result = fmath.prev_pow2(d)
if result is None:
self.assertTrue(False)
self.assertTrue(result <= d)
def testPrevBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.prev_pow2, b)
def testPrevNeg(self):
for d in self.data:
self.assertRaises(ValueError, fmath.prev_pow2, -d)
class TestDistance(unittest.TestCase):
def setUp(self):
## data = [[point, point, distance, distance_sq]]
self.data = [[(0, 0), (0, 1), 1, 1],
[(2.5, 2),(4.76, 3.1), 2.5134, 6.3176],
[(10, 16),(100, 160), 169.8116, 28836],
[fmath.Vector([1.2, 1]), fmath.Vector([16, 1]), 14.8, 219.04],
[(0, 0), (0, 0), 0, 0],
[fmath.Vector([0, 0]), fmath.Vector([0, 0]), 0, 0]]
self.long = [[(21, 4, 6, 4, 3), (14, 16, 71, 723, 5)],
[(10, 9, 8, 7, 6, 5, 4, 3, 2, 1), (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)],
[(1, 2, 3, 4), (5, 4, 3, 2, 1)]]
self.short = [[(), ()]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.distance(d[0], d[1]),
Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(fmath.distance(d[0], d[1]) >= 0)
def testValue(self):
for d in self.data:
result = fmath.distance(d[0], d[1])
self.assertEquals(round(result, 2), round(d[2], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.distance, b[0],b[1])
##-------- Sq
def testIsNumberSq(self):
for d in self.data:
self.assertTrue(isinstance(fmath.distance_sq(d[0], d[1]),
Number))
def testIsPosSq(self):
for d in self.data:
self.assertTrue(fmath.distance_sq(d[0], d[1]) >= 0)
def testValueSq(self):
for d in self.data:
result = fmath.distance_sq(d[0], d[1])
self.assertEquals(round(result, 2), round(d[3], 2))
def testBadSq(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.distance_sq, b[0],b[1])
class TestMidpoint(unittest.TestCase):
def setUp(self):
## data = [[point, point, midpoint]]
self.data = [[(0, 0), (0, 1), (0, 0.5)],
[(2.5, 2),(4.76, 3.1), (3.63, 2.55)],
[(10, 16),(100, 160), (55, 88)],
[fmath.Vector([1.13, 1]), (16, 1), (8.565, 1)],
[(0, 0), (0, 0), (0, 0)]]
self.wrong = [[(), ()],
[(2,), (1,)]]
self.bad = [["hello", "world"],
[{'foo': 'bar'}, {'bar': 'foo'}],
["hello world", 35]]
def testValue(self):
for d in self.data:
result = fmath.midpoint(d[0], d[1])
self.assertEquals(round(result[0]), round(d[2][0]))
self.assertEquals(round(result[1]), round(d[2][1]))
def testWrong(self):
for d in self.wrong:
self.assertRaises(TypeError,
fmath.midpoint, d[0], d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.midpoint, b[0],b[1])
class TestArea(unittest.TestCase):
def setUp(self):
## [[data], area, signed_area]
self.data = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], 4, 4],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], 4, -4],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], 1002.66, 1002.66 ],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], 1002.66, -1002.66 ]]
self.odata = [[ [(1, 1), (-1, 1), (-1, -1), (1, -1)], True],
[ [(1, 1), (1, -1), (-1, -1), (-1, 1)], False],
[ [(0, 15.4), (-64.24, -10.1), (14.4, -10.1)], True],
[ [(0, 15.4), (14.4, -10.1), (-64.24, -10.1)], False]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}],
[(1,), (2,), (3,)],
[(1, 2), (3, 4)],
[(1, 2)],
[]]
##-------- Pos Area
def testIsNumber(self):
for d in self.data:
self.assertTrue(isinstance(fmath.area(d[0]), Number))
def testIsPos(self):
for d in self.data:
self.assertTrue(fmath.area(d[0]) > 0)
def testValue(self):
for d in self.data:
result = fmath.area(d[0])
self.assertEquals(round(result, 2), round(d[1], 2))
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.area, b)
##-------- Signed Area
def testIsNumberS(self):
for d in self.data:
self.assertTrue(isinstance(fmath.signed_area(d[0]), Number))
def testValueS(self):
for d in self.data:
result = fmath.signed_area(d[0])
self.assertEquals(round(result, 2), round(d[2], 2))
def testBadS(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.signed_area, b)
##-------- Orientation
def testValueO(self):
for d in self.odata:
result = fmath.orientation_poly(d[0])
self.assertEquals(result, d[1])
def testBadO(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.orientation_poly, b)
class TestNormalizeAngle(unittest.TestCase):
def setUp(self):
self.datad = [[45, 45],
[360, 0],
[400, 40],
[4000, 40],
[-100, 260]]
self.datar = [[math.radians(45), math.radians(45)],
[math.radians(360), math.radians(0)],
[math.radians(400), math.radians(40)],
[math.radians(4000), math.radians(40)],
[math.radians(-100), math.radians(260)]]
self.bad = ["meow",
[16],
{'foo': 'bar'}]
##-------- Degress
def testNumber(self):
for i in range(0, 1000):
self.assertTrue(isinstance(fmath.normalize_angle(i),
Number))
def testIsPos(self):
for i in range(0, 1000):
self.assertTrue(fmath.normalize_angle(i) >= 0)
def testValue(self):
for d in self.datad:
self.assertEquals(fmath.normalize_angle(d[0]), d[1])
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.normalize_angle, b)
##-------- Radians
def testNumberR(self):
for i in range(0, 1000):
self.assertTrue(isinstance(fmath.normalize_angler(i),
Number))
def testIsPosR(self):
for i in range(0, 1000):
self.assertTrue(fmath.normalize_angler(i) >= 0)
def testValueR(self):
for d in self.datar:
self.assertAlmostEquals(fmath.normalize_angler(d[0]), d[1])
def testBadR(self):
for b in self.bad:
self.assertRaises(TypeError,
fmath.normalize_angler, b)
class TestNormalizePoly(unittest.TestCase):
def setUp(self):
self.p = [fmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1)]
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testNormalize(self):
self.assert_(fmath.normalize_poly(self.p) == self.p)
p = [fmath.Vector((-1,1)), (-1,-1), [1,-1], (1,1), (-1, 1)]
self.assert_(fmath.normalize_poly(p) == self.p)
self.assert_(fmath.normalize_poly(self.p, 1) == p)
p = [(-1,1), (-1,-1), [1,-1], (1,1), (-1, 1), (-1,-1)]
self.assert_(fmath.normalize_poly(p) == self.p)
self.assert_(fmath.normalize_poly(self.p, 2) == p)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.normalize_poly, b)
class TestPolySimplify(unittest.TestCase):
def setUp(self):
self.data = [[(1, 0), (1, 8.12), (19.95, 5), (-1, -5), (-1.25, -5.15)],
[[-1, 0], [-1, -4.12], [-16.95, -5], [14, 5], [1.25, 5.15]]]
self.bad = [["meow", "rawrf", "ROAR"],
[("meow", "woof"), ("woof", "meow"), ("rawr", "roar")],
[{'foo': 'bar'}, {'foo': 'bar'}, {'foo': 'bar'}]]
def testReturnsList(self):
for i in range(8):
for d in self.data:
self.assertTrue(isinstance(fmath.simplify_poly(d, i),
list))
def testReturnsCoords(self):
for i in range(8):
for d in self.data:
result = fmath.simplify_poly(d, i)
b = True
for p in result:
if not (isinstance(p[0], Number) and isinstance(p[1], Number)):
b = b and False
break
self.assertTrue(b)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.simplify_poly, b, 1)
class TestVector(unittest.TestCase):
def setUp(self):
self.v = fmath.Vector((111, 222))
self.bad = [(8, {'foo': 'bar'}),
("meow!", "imah vector!")]
def testAccess(self):
v = self.v.copy()
self.assert_(v.x == 111 and v.y == 222)
v.x = 333
v[1] = 444
self.assert_(v[0] == 333 and v[1] == 444)
def testMath(self):
v = self.v.copy()
self.assertEqual(v + 1, fmath.Vector((112, 223)))
self.assertEqual(v - 2, [109,220])
self.assert_(v * 3 == (333,666))
self.assert_(v / 2.0 == fmath.Vector((55.5, 111)))
self.assert_(v / 2 == (55.5, 111))
self.assert_(v ** fmath.Vector((2,3)) == [12321, 10941048])
self.assert_(v + [-11, 78] == fmath.Vector((100, 300)))
def testReverseMath(self):
v = self.v.copy()
self.assert_(1 + v == fmath.Vector((112,223)))
self.assert_(2 - v == [-109,-220])
self.assert_(3 * v == (333,666))
self.assert_([111,222] ** fmath.Vector((2,3)) == [12321, 10941048])
self.assert_(v + fmath.Vector((1,1)) == [112, 223])
def testInplaceMath(self):
inplace_vec = fmath.Vector((5, 13))
inplace_src = fmath.Vector((inplace_vec))
inplace_vec *= .5
inplace_vec += .5
inplace_vec /= 3
inplace_vec += fmath.Vector((-1, -1))
alternate = (inplace_src*.5 + .5)/3 + [-1, -1]
self.assertEquals(inplace_vec, alternate)
def testUnary(self):
v = self.v.copy()
v = -v
self.assert_(v == [-111,-222])
v = abs(v)
self.assert_(v == [111,222])
def testLength(self):
v = fmath.Vector((3, 4))
self.assert_(v.length == 5)
v.length = 10
self.assert_(v == [6, 8])
def testAngles(self):
v = fmath.Vector((0,3))
self.assert_(v.angle == 90)
v.angle = 0
self.assert_(v == (3, 0))
v2 = (-3,0)
self.assert_(v.angle_about(v2) == 0)
v2 = fmath.Vector(v2)
self.assert_(v2.angle_about(v) == 180)
v.angle = 90, (0,0)
self.assert_(v == [0, 3])
def testComparison(self):
int_vec = fmath.Vector((3, -2))
flt_vec = fmath.Vector((3.0, -2.0))
zero_vec = fmath.Vector((0, 0))
self.assert_(int_vec == flt_vec)
self.assert_(int_vec != zero_vec)
self.assert_((flt_vec == zero_vec) == False)
self.assert_((flt_vec != int_vec) == False)
self.assert_(int_vec == (3, -2))
self.assert_(int_vec != [0, 0])
self.assert_(int_vec != 5)
def testConversion(self):
self.assert_(list(self.v) == [111, 222] and isinstance(list(self.v), list))
self.assert_(tuple(self.v) == (111, 222) and isinstance(tuple(self.v), tuple))
def testPickle(self):
testvec = fmath.Vector((5, .3))
testvec_str = pickle.dumps(testvec)
loaded_vec = pickle.loads(testvec_str)
self.assertEquals(testvec, loaded_vec)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Vector, b)
class TestPolygon(unittest.TestCase):
def setUp(self):
self.p = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.bad = [[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]]]
def testAccess(self):
p = self.p.copy()
self.assert_(p[0] == (-1, 1))
p[0] = (-5, 5)
self.assert_(p[0] == (-5, 5) and isinstance(p[0], fmath.Vector))
self.assert_(p.center == (-1, 1))
p[1] = -4, 7
self.assert_(p[1] == (-4, 7))
p[3] = 16
self.assert_(p[3] == (16, 16))
def testComparison(self):
p = self.p.copy()
self.assert_(p == [(-1,1), (-1,-1), (1,-1), (1,1)])
q = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
self.assert_(p == q)
q[0] = -5, 5
self.assert_(p != q)
self.assert_(q != p)
def testConversion(self):
p = self.p.copy()
self.assert_(list(p) == p and isinstance(list(p), list))
self.assert_(tuple(p) == p and isinstance(tuple(p), tuple))
def testAngle(self):
p = self.p.copy()
self.assert_(p.angle == 0)
p.center = 1,0
self.assert_(p.angle == 0)
p.center = 0, 10
self.assert_(p.angle == 90)
def testOrientation(self):
p = self.p.copy()
self.assert_(p.orientation == 0)
l = list(p)
p.orientation = 90
self.assert_(p != l)
self.assertEquals(p, [(-1.0000000000000002, -1.0),
(0.99999999999999978, -1.0000000000000002),
(1.0000000000000002, 1.0), (-1.0, 1.0000000000000002)])
def testCollision(self):
p1 = self.p.copy()
p2 = [(-0.5,0.5), (-0.5,-0.5), (0.5,-0.5), (0.5,0.5)]
self.assert_(p1.intersects(p2))
self.assert_(p1.intersects(p1))
p1.center = 90, -60
self.assert_(p1.intersects(p2) == False)
p1.center = 1.5, 0
self.assert_(p1.intersects(p2))
p1.center = 0, -1.5
self.assert_(p1.intersects(p2))
p1.center = -1.4, 0
self.assert_(p1.intersects(p2))
def testPickle(self):
testpoly = fmath.Polygon([(-1,1), (-1,-1), (1,-1), (1,1)])
testpoly_str = pickle.dumps(testpoly)
loaded_poly = pickle.loads(testpoly_str)
self.assertEquals(testpoly, loaded_poly)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Polygon, b)
class TestRect(unittest.TestCase):
def setUp(self):
self.p = fmath.Rect((0, 0), 2, 2)
self.bad = [[1, 2, 3],
[{'foo': 'bar'}, "meow!", (1, 2), ["3","4"]],
[(1,), (2,), (3,)]]
def testAccess(self):
p = self.p.copy()
self.assert_(p.center == (0,0))
self.assert_(p.topleft == (-1, 1))
self.assert_(p.bottomleft == (-1, -1))
p.center = 1, 3
self.assert_(p.center == (1, 3))
p.topright = 4
self.assert_(p.topright == (4, 4))
self.assert_(p.bottomright == (4, 2))
p[2] = 4, 1
self.assert_(p.topright == (4, 3))
self.assert_(p.bottomright == (4, 1))
p.width = 4
self.assert_(p.topright == (5, 3))
p.size = (1, 1)
self.assert_(p.topleft == (2.5, 2.5))
def testMath(self):
pass
def testComparison(self):
p = self.p.copy()
q = [(-1,1), (-1,-1), (1,-1), (1,1)]
self.assert_(p == q)
q[0] = (-1, 2)
self.assert_(p != q)
def testAngle(self):
p = self.p.copy()
self.assert_(p.angle == 0)
p.center = 1,0
self.assert_(p.angle == 0)
p.center = 0, 10
self.assert_(p.angle == 90)
p.angle = 0
self.assert_(p.center == (10, 0))
def testOrientation(self):
p = self.p.copy()
self.assert_(p.orientation == 0)
l = list(p)
p.orientation = 90
self.assert_(p != l)
self.assertEquals(p, [(-1.0000000000000002, -1.0),
(0.99999999999999978, -1.0000000000000002),
(1.0000000000000002, 1.0), (-1.0, 1.0000000000000002)])
def testConversion(self):
p = self.p.copy()
self.assert_(list(p) == p and isinstance(list(p), list))
self.assert_(tuple(p) == p and isinstance(tuple(p), tuple))
def testPickle(self):
testrect = fmath.Rect((-1, 1), 2, 2)
testrect_str = pickle.dumps(testrect)
loaded_rect = pickle.loads(testrect_str)
self.assertEquals(testrect, loaded_rect)
def testBad(self):
for b in self.bad:
self.assertRaises(TypeError, fmath.Rect, b)
##-------- Test Suite
testpow = unittest.TestLoader().loadTestsFromTestCase(TestPow)
testdistance = unittest.TestLoader().loadTestsFromTestCase(TestDistance)
testmidpoint = unittest.TestLoader().loadTestsFromTestCase(TestMidpoint)
testarea = unittest.TestLoader().loadTestsFromTestCase(TestArea)
testnormalized = unittest.TestLoader().loadTestsFromTestCase(TestNormalizeAngle)
testnormalizepoly = unittest.TestLoader().loadTestsFromTestCase(TestNormalizePoly)
testsimplify = unittest.TestLoader().loadTestsFromTestCase(TestPolySimplify)
testvector = unittest.TestLoader().loadTestsFromTestCase(TestVector)
testpolygon = unittest.TestLoader().loadTestsFromTestCase(TestPolygon)
testrect = unittest.TestLoader().loadTestsFromTestCase(TestRect)
testsuite = unittest.TestSuite((testpow, testdistance, testmidpoint, testarea,
testnormalized, testnormalizepoly,
testsimplify,
testvector, testpolygon, testrect))
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import unittest
import unit
testsuite = unittest.TestSuite((unit.flmath_test.testsuite,
unit.screen_test.testsuite,
unit.image_test.testsuite,
unit.mesh_test.testsuite,
unit.sprite_test.testsuite))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
import unittest
import unit
testsuite = unittest.TestSuite((unit.flmath_test.testsuite,
unit.screen_test.testsuite,
unit.image_test.testsuite,
unit.mesh_test.testsuite,
unit.sprite_test.testsuite))
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(testsuite)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Flamingo v0.1.0
Flamingo is an advanced 2d game engine written on top of pygame
<www.pygame.org>. Flamingo goes a step beyond other game engines
written in Python by supplying _all_ necessary tools for the
development of a game allowing the developer to focus on content
instead of the engine.
Dependencies:
Python - <www.python.org> - 2.x series, 2.5+
pygame - <www.pygame.org> - 1.9.x
PyOpenGL - <pyopengl.sourceforge.com> - 3.0.x
pybox2d - <pybox2d.googlecode.com> - 2.0.2b1
numpy - <numpy.scipy.org> - 1.3.x
PIL - <> - 1.1.x
"""
## Define constants
__version__ = "0.1.0"
__author__ = "Bradley Zeis"
import os
fl_path = os.path.split(__file__)[0]
## Import flamingo modules
import constants
import backends
import fltime
import flcolor
import flmath
import image
import mesh
import sprite
import screen
import core
import util
import event
import objects
import audio
import game
## Import/Check dependencies
try:
import pygame
import Box2D as box2d
import numpy
import OpenGL
if pygame.__version__[:3] != '1.9':
raise ImportError, "Wrong pygame version (1.9.x required). Version {0} found."\
.format(pygame.__version__)
if box2d.__version__ != '2.0.2b1':
raise ImportError, "Wrong pybox2d version (2.0.2b1 required). Version {0} found."\
.format(box2d.__version__)
if numpy.version.version[:3] != '1.3':
raise ImportError, "Wrong numpy version (1.3.x required). Version {0} found."\
.format(numpy.version.version)
if OpenGL.version.__version__[:3] != '3.0':
raise ImportError, "Wrong pyOpenGL version (3.0.x required). Version {0} found."\
.format(OpenGL.version.__version__)
except ImportError, err:
raise ImportError, err
__all__ = ["constants", "backends",
"flcolor", "fltime", "flmath", "image", "mesh",
"sprite", "screen",
"core", "util", "event", "objects", "audio", "game"]
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Contains useful utility functions for use throughout Flamingo.
General Functions:
create_key(dict) - Return a 7-digit number that is not a
key in dict.
to_filename(name) - Return name as an appropriate filename.
hasattrs(object, *names) - Return True if object has all attributes
names.
format_types(type) - Return the names of types without the
extra formatting.
enable_logging() - Enable global exception logging.
disable_logging() - Disable exception logging.
"""
import sys, os
import random
import re
import logging
##-------- Constants
ERRORLOG = "flamingo-error.txt"
##-------- General Functions
def create_key(dict=None):
"""Return a 7-digit key that is not a key in dict.
dict - (dict) If provided, a key in dict won't be returned.
Returns: int
"""
def key():
random.seed()
return int(random.random() * 10000000)
if dict:
k = key()
while k in dict: k = key()
return k
return key()
def to_filename(name):
"""Return the name as an appropriate filename without the extension.
This function is mainly used by the Flamingo Tools.
name - (str) The name of the segment.
Returns: str
"""
segname = segname.lower()
string = ""
for i in range(0, len(segname)):
if segname[i] == " ": string += "_"
elif re.search("[a-z0-9_-]|\.", segname[i]): string += segname[i]
return string
def hasattrs(object, *names):
"""Return True if object has all attributes names.
Returns: bool
"""
return all(hasattr(object, name) for name in names)
def format_types(*types):
"""Return the names of types without the extra formatting.
Usage:
>>> format_types(tuple, int, float)
'tuple, int float'
Returns: str
"""
return ", ".join([str(t).split("'")[1] for t in types])
##-------- Exception Logging
def enable_logging():
"""Enable global exception logging.
Returns: None
"""
if os.path.abspath(os.curdir) != sys.prefix:
sys.excepthook = _excepthook
def disable_logging():
"""Disable exception logging.
Returns: None
"""
sys.excepthook = sys.__excepthook__
def _excepthook(type, value, tback):
"""Append the traceback to the end of the global error log."""
with open(ERRORLOG, "a") as log:
import traceback
tb = traceback.format_exception(type, value, tback)
for line in tb:
log.write(line)
print line
log.write("\n\n")
##-------- Decorators
## Memoization
class memoize(object):
def __init__(self, func):
self.cache = {}
self.func = func
def __call__(self, *args, **kw):
try:
return self.cache[(args, kw)]
except KeyError:
self.cache[(args, kw)] = value = self.func(*args, **kw)
return value
except TypeError:
return self.func(*args, **kw)
def __repr__(self):
return self.func.__doc__
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
from .util import * | Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""Contains useful utility functions for use throughout Flamingo.
General Functions:
create_key(dict) - Return a 7-digit number that is not a
key in dict.
to_filename(name) - Return name as an appropriate filename.
hasattrs(object, *names) - Return True if object has all attributes
names.
format_types(type) - Return the names of types without the
extra formatting.
enable_logging() - Enable global exception logging.
disable_logging() - Disable exception logging.
"""
import sys, os
import random
import re
import logging
##-------- Constants
ERRORLOG = "flamingo-error.txt"
##-------- General Functions
def create_key(dict=None):
"""Return a 7-digit key that is not a key in dict.
dict - (dict) If provided, a key in dict won't be returned.
Returns: int
"""
def key():
random.seed()
return int(random.random() * 10000000)
if dict:
k = key()
while k in dict: k = key()
return k
return key()
def to_filename(name):
"""Return the name as an appropriate filename without the extension.
This function is mainly used by the Flamingo Tools.
name - (str) The name of the segment.
Returns: str
"""
segname = segname.lower()
string = ""
for i in range(0, len(segname)):
if segname[i] == " ": string += "_"
elif re.search("[a-z0-9_-]|\.", segname[i]): string += segname[i]
return string
def hasattrs(object, *names):
"""Return True if object has all attributes names.
Returns: bool
"""
return all(hasattr(object, name) for name in names)
def format_types(*types):
"""Return the names of types without the extra formatting.
Usage:
>>> format_types(tuple, int, float)
'tuple, int float'
Returns: str
"""
return ", ".join([str(t).split("'")[1] for t in types])
##-------- Exception Logging
def enable_logging():
"""Enable global exception logging.
Returns: None
"""
if os.path.abspath(os.curdir) != sys.prefix:
sys.excepthook = _excepthook
def disable_logging():
"""Disable exception logging.
Returns: None
"""
sys.excepthook = sys.__excepthook__
def _excepthook(type, value, tback):
"""Append the traceback to the end of the global error log."""
with open(ERRORLOG, "a") as log:
import traceback
tb = traceback.format_exception(type, value, tback)
for line in tb:
log.write(line)
print line
log.write("\n\n")
##-------- Decorators
## Memoization
class memoize(object):
def __init__(self, func):
self.cache = {}
self.func = func
def __call__(self, *args, **kw):
try:
return self.cache[(args, kw)]
except KeyError:
self.cache[(args, kw)] = value = self.func(*args, **kw)
return value
except TypeError:
return self.func(*args, **kw)
def __repr__(self):
return self.func.__doc__
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
from .util import * | Python |
#!/usr/bin/env python
from distutils.core import setup, Extension
import os
## Windows (32), Python 2.6, with GCC (MinGW or Cygwin) Only, for now
if os.name == "nt":
## Constants
library_dirs = [os.path.abspath('lib/win32')]
include_dirs = [os.path.abspath('ext/include'), os.path.abspath(os.path.join(os.sys.exec_prefix + 'include'))]
## Configure Extensions
fltime = Extension('fltime', include_dirs=include_dirs,
sources=['ext/fltime.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/fltime.lib,--export-all-symbols'])
flmath = Extension('flmath', include_dirs=include_dirs,
sources=['ext/flmath.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/flmath.lib,--export-all-symbols'])
flcolor = Extension("flcolor", include_dirs=include_dirs,
sources=['ext/flcolor.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/flcolor.lib,--export-all-symbols'])
image = Extension('image', libraries=['opengl32', 'glu32', 'DevIL', 'ILU'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/image.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/image.lib,--export-all-symbols'])
mesh = Extension('mesh', libraries=['flmath'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/mesh.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/mesh.lib,--export-all-symbols'])
sprite = Extension('sprite', libraries=['flcolor', 'flmath', 'image', 'mesh'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/sprite.c'],
extra_link_args=['-Wl,--out-implib=lib/win32/sprite.lib,--export-all-symbols'])
screen = Extension('screen', libraries=['opengl32', 'SDL', 'flcolor', 'flmath', 'sprite'],
library_dirs=library_dirs,
include_dirs=include_dirs,
sources=['ext/screen.c'])
ext_modules = [fltime, flmath, flcolor, image, mesh, sprite, screen]
elif os.name == "mac":
pass
elif os.name == "posix":
pass
## Setup
if __name__ == "__main__":
setup(ext_modules=ext_modules)
| Python |
#!/usr/bin/env python
## flamingo - 2D Game Engine
## Copyright (C) 2009 Bradley Zeis
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program. If not, see <http://www.gnu.org/licenses/>.
##
## Bradley Zeis
## flamingoengine@gmail.com
"""The core Game related classes and functions."""
import sys
import os
import thread
import math
import constants
import fltime
import core
import display
import util
import flmath
import event
import image
import sprite
import objects
import audio
import screen
import OpenGL.GL as gl
class Game(object):
"""Base class used to create Games."""
def __init__(self):
core.GAME = self
self.data = core._Data
self.data.screen_size = (800, 600)
self.data.master_spr_group = sprite._MasterGroup()
self.data.painter = screen.Painter()
self.data.master_clock = fltime.Clock()
self.data.render_clock = fltime.Clock()
self.data.logic_clock = fltime.Clock()
fltime._set_master_clock(self.data.master_clock)
self.data.master_eventlistener = event.EventListener()
self.data.eventlistener = self.data.master_eventlistener
## Open ini file(s) here to load settings.
audio.load("flamingo.backends.audio.pygame_mixer")
def run(self, start_game, flags, *args):
"""Runs the entire application.
Returns: None
"""
self._run_init()
self.init(*args)
self.start_main(start_game)
##-------- Initialization
def _run_init(self):
"""Initialize the application before running.
Returns: None
"""
display.load('flamingo.backends.display.pygame_display',
'flamingo.backends.event.pygame_event')
display.init(800, 600, self.data.screen_title)
## OpenGL
gl.glShadeModel(gl.GL_SMOOTH)
gl.glClearColor(0, 0, 0, 1)
gl.glDisable(gl.GL_DEPTH_TEST)
gl.glDisable(gl.GL_LIGHTING)
gl.glEnable(gl.GL_BLEND)
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(gl.GL_POINT_SMOOTH)
gl.glEnable(gl.GL_LINE_SMOOTH)
gl.glEnable(gl.GL_POLYGON_SMOOTH)
# Flamingo
self.data.eventlistener.bind(self.quit_all, constants.QUIT, constants.QUIT)
audio.mixer.init()
self.quit = False
def init(self, *args):
"""User initialization.
Returns: None
"""
pass
##-------- Screens
def add_screen(self, screen):
"""Add a Screen to the stack.
screen - (Screen)
Returns: None
"""
self.data.screens.append(screen)
def rem_screen(self, screen):
"""Remove a Screen from the stack.
screen - (Screen)
Returns: None
"""
self.data.screens.remove(screen)
##--------- Startup
def start_main(self, start_game=False):
"""Runs the entire program.
Returns: None
"""
## Initialize
## Main Loop
#audio.mixer.start()
if start_game:
self.start_game()
self._gameloop()
## Tear Down
def start_game(self):
"""Starts the threads relating to the game itself.
Returns: None
"""
pass
##-------- Loop/Quitting
def _gameloop(self):
"""The main game loop.
Returns: None
"""
self.data.master_clock.init()
self.data.logic_clock.init()
self.data.render_clock.init()
self.quit = False
self.data.current_time = self.data.master_clock.ticks()
timestep = 1.0 / self.data.logic_fps
accumulator = 0
while not self.quit:
self.data.master_clock.sync()
newTime = self.data.master_clock.ticks()
self.data.delta_time = newTime - self.data.current_time
self.data.current_time = newTime
fltime._timer_sync(self.data.current_time)
accumulator += self.data.delta_time
## Process Input
event.process()
if self.quit:
break
## Update Physics/Objects
while accumulator>=timestep:
accumulator -= timestep
# Physics step
for group in self.data.spr_groups:
group.update(self.data.delta_time)
self.data.master_spr_group.update()
## Render
#if not audio.mixer.THREADED:
# audio.mixer.Mixer.tick(self.data.delta_time)
#self.data.screens[0].orientation += .01
self.data.render_clock.sync()
interpolation = accumulator / timestep
self.data.painter.draw(interpolation)
display.flip()
#print fltime.ticks_to_seconds(self.data.current_time)
def quit_game(self):
"""Exits the main loop of the program without killing everything.
Returns: None
"""
self.quit = True
self.data.clear()
def quit_all(self):
"""Kills the entire application cleanly.
Returns: None
"""
self.quit = True
sys.exit()
| Python |
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import os
import urllib
import urllib2
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext.webapp import template
from google.appengine.ext import db
class Card(db.Model):
author = db.UserProperty()
front = db.StringProperty(multiline=True)
back = db.StringProperty(multiline=True)
url = db.StringProperty(multiline=False)
class MainPage(webapp.RequestHandler):
def get(self):
url = self.request.get("url")
#url = "http://en.wikipedia.org/wiki/DevHouse"
result = urlfetch.fetch(url)
#self.response.headers['Content-Type'] = 'text/html'
#self.response.out.write(result.content)
cards = db.GqlQuery("SELECT * FROM Card")
cardout = '<div id="card_set">'
for card in cards:
cardout = cardout + '<div class="card_icon">'
ss = ''
if (len(card.front) > 50):
ss = card.front[0:50]
else:
ss = card.front
cardout += ss
cardout += '<span class="hidspan front">' + card.front + '</span>'
cardout += '<span class="hidspan back">' + card.back + '</span></div>'
cardout = cardout + '</div>'
template_values = {
'pagecontent': result.content,
'url': url,
'cardout': cardout,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class SaveCard(webapp.RequestHandler):
def post(self):
card = Card();
if users.get_current_user():
card.author = users.get_current_user()
front = self.request.get("card_front")
card.front = front
back = self.request.get("card_back")
card.back = back
url = self.request.get("url")
card.url = url
card.put()
self.redirect('/?url=' + url)
application = webapp.WSGIApplication(
[('/', MainPage),
('/savecard',SaveCard)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
#!/usr/bin/env python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
# Example:
# (r'^poicreator/', include('poicreator.foo.urls')),
# Uncomment this for admin:
# (r'^admin/', include('django.contrib.admin.urls')),
)
| Python |
#!/usr/bin/env python
# Copyright (C) 2012 Sebastien MACKE
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 2, as published by the
# Free Software Foundation
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details (http://www.gnu.org/licenses/gpl.txt).
__author__ = 'Sebastien Macke'
__email__ = 'patator@hsc.fr'
__url__ = 'http://www.hsc.fr/ressources/outils/patator/'
__git__ = 'http://code.google.com/p/patator/'
__twitter__ = 'http://twitter.com/lanjelot'
__version__ = '0.6-beta'
__license__ = 'GPLv2'
__banner__ = 'Patator v%s (%s)' % (__version__, __git__)
# README {{{
'''
INTRODUCTION
------------
* What ?
Patator is a multi-purpose brute-forcer, with a modular design and a flexible usage.
Currently it supports the following modules:
- ftp_login : Brute-force FTP
- ssh_login : Brute-force SSH
- telnet_login : Brute-force Telnet
- smtp_login : Brute-force SMTP
- smtp_vrfy : Enumerate valid users using the SMTP 'VRFY' command
- smtp_rcpt : Enumerate valid users using the SMTP 'RCPT TO' command
- finger_lookup : Enumerate valid users using Finger
- http_fuzz : Brute-force HTTP
- pop_login : Brute-force POP3
- pop_passd : Brute-force poppassd (http://netwinsite.com/poppassd/)
- imap_login : Brute-force IMAP4
- ldap_login : Brute-force LDAP
- smb_login : Brute-force SMB
- smb_lookupsid : Brute-force SMB SID-lookup
- vmauthd_login : Brute-force VMware Authentication Daemon
- mssql_login : Brute-force MSSQL
- oracle_login : Brute-force Oracle
- mysql_login : Brute-force MySQL
- mysql_queries : Brute-force MySQL queries
- pgsql_login : Brute-force PostgreSQL
- vnc_login : Brute-force VNC
- dns_forward : Brute-force DNS
- dns_reverse : Brute-force DNS (reverse lookup subnets)
- snmp_login : Brute-force SNMPv1/2 and SNMPv3
- unzip_pass : Brute-force the password of encrypted ZIP files
- keystore_pass : Brute-force the password of Java keystore files
- tcp_fuzz : Fuzz TCP services
Future modules to be implemented:
- rdp_login
The name "Patator" comes from http://www.youtube.com/watch?v=xoBkBvnTTjo
"Whatever the payload to fire, always use the same cannon"
* Why ?
Basically, I got tired of using Medusa, Hydra, Ncrack, Metasploit auxiliary modules, Nmap NSE scripts and the like because:
- they either do not work or are not reliable (got me false negatives several times in the past)
- they are not flexible enough (how to iterate over all wordlists, fuzz any module parameter)
- they lack useful features (display progress or pause during execution)
FEATURES
--------
* No false negatives, as it is the user that decides what results to ignore based on:
+ status code of response
+ size of response
+ matching string or regex in response data
+ ... see --help
* Modular design
+ not limited to network modules (eg. the unzip_pass module)
+ not limited to brute-forcing (eg. remote exploit testing, or vulnerable version probing)
* Interactive runtime
+ show progress during execution (press Enter)
+ pause/unpause execution (press p)
+ increase/decrease verbosity
+ add new actions & conditions during runtime (eg. to exclude more types of response from showing)
+ ... press h to see all available interactive commands
* Use persistent connections (ie. will test several passwords until the server disconnects)
* Multi-threaded
* Flexible user input
- Any module parameter can be fuzzed:
+ use the FILE keyword to iterate over a file
+ use the COMBO keyword to iterate over a combo file
+ use the NET keyword to iterate over every hosts of a network subnet
+ use the RANGE keyword to iterate over hexadecimal, decimal or alphabetical ranges
+ use the PROG keyword to iterate over the output of an external program
- Iteration over the joined wordlists can be done in any order
* Save every response (along with request) to seperate log files for later reviewing
INSTALL
-------
* Dependencies (best tested versions)
| Required for | URL | Version |
--------------------------------------------------------------------------------------------------
paramiko | SSH | http://www.lag.net/paramiko/ | 1.7.7.1 |
--------------------------------------------------------------------------------------------------
pycurl | HTTP | http://pycurl.sourceforge.net/ | 7.19.0 |
--------------------------------------------------------------------------------------------------
openldap | LDAP | http://www.openldap.org/ | 2.4.24 |
--------------------------------------------------------------------------------------------------
impacket | SMB | http://code.google.com/p/impacket/ | svn#765 |
--------------------------------------------------------------------------------------------------
cx_Oracle | Oracle | http://cx-oracle.sourceforge.net/ | 5.1.1 |
--------------------------------------------------------------------------------------------------
mysql-python | MySQL | http://sourceforge.net/projects/mysql-python/ | 1.2.3 |
--------------------------------------------------------------------------------------------------
psycopg | PostgreSQL | http://initd.org/psycopg/ | 2.4.5 |
--------------------------------------------------------------------------------------------------
pycrypto | VNC | http://www.dlitz.net/software/pycrypto/ | 2.3 |
--------------------------------------------------------------------------------------------------
dnspython | DNS | http://www.dnspython.org/ | 1.10.0 |
--------------------------------------------------------------------------------------------------
pysnmp | SNMP | http://pysnmp.sourceforge.net/ | 4.2.1 |
--------------------------------------------------------------------------------------------------
pyasn1 | SNMP | http://sourceforge.net/projects/pyasn1/ | 0.1.2 |
--------------------------------------------------------------------------------------------------
IPy | NETx keywords | https://github.com/haypo/python-ipy | 0.75 |
--------------------------------------------------------------------------------------------------
unzip | ZIP passwords | http://www.info-zip.org/ | 6.0 |
--------------------------------------------------------------------------------------------------
Java | keystore files | http://www.oracle.com/technetwork/java/javase/ | 6 |
--------------------------------------------------------------------------------------------------
python | | http://www.python.org/ | 2.7 |
--------------------------------------------------------------------------------------------------
* Shortcuts (optionnal)
ln -s path/to/patator.py /usr/bin/ftp_login
ln -s path/to/patator.py /usr/bin/http_fuzz
so on ...
USAGE
-----
$ python patator.py <module> -h
or
$ <module> -h (if you created the shortcuts)
There are global options and module options:
- all global options start with - or --
- all module options are of the form option=value
All module options are fuzzable:
---------
./module host=FILE0 port=FILE1 foobar=FILE2.google.FILE3 0=hosts.txt 1=ports.txt 2=foo.txt 3=bar.txt
The keywords (FILE, COMBO, NET, ...) act as place-holders. They indicate the type of wordlist
and where to replace themselves with the actual words to test.
Each keyword is numbered in order to:
- match the corresponding wordlist
- and indicate in what order to iterate over all the wordlists
For instance, this would be the classic order:
---------
$ ./module host=FILE0 user=FILE1 password=FILE2 0=hosts.txt 1=logins.txt 2=passwords.txt
10.0.0.1 root password
10.0.0.1 root 123456
10.0.0.1 root qsdfghj
... (trying all passwords before testing next login)
10.0.0.1 admin password
10.0.0.1 admin 123456
10.0.0.1 admin qsdfghj
... (trying all logins before testing next host)
10.0.0.2 root password
...
While a smarter way might be:
---------
$ ./module host=FILE2 user=FILE1 password=FILE0 2=hosts.txt 1=logins.txt 0=passwords.txt
10.0.0.1 root password
10.0.0.2 root password
10.0.0.1 admin password
10.0.0.2 admin password
10.0.0.1 root 123456
10.0.0.2 root 123456
10.0.0.1 admin 123456
...
* Keywords
Brute-force a list of hosts with a file containing combo entries (each line := login:password).
---------
./module host=FILE0 user=COMBO10 password=COMBO11 0=hosts.txt 1=combos.txt
Scan subnets to just grab version banners.
---------
./module host=NET0 0=10.0.1.0/24,10.0.2.0/24,10.0.3.128-10.0.3.255
Fuzzing a parameter by iterating over a range of values.
---------
./module param=RANGE0 0=hex:0x00-0xffff
./module param=RANGE0 0=int:0-500
./module param=RANGE0 0=lower:a-zzz
Fuzzing a parameter by iterating over the output of an external program.
---------
./module param=PROG0 0='john -stdout -i'
./module param=PROG0 0='mp64.bin ?l?l?l',$(mp64.bin --combination ?l?l?l) # http://hashcat.net/wiki/doku.php?id=maskprocessor
* Actions & Conditions
Use the -x option to do specific actions upon receiving expected results. For instance:
To ignore responses with status code 200 *AND* a size within a range.
---------
./module host=10.0.0.1 user=FILE0 -x ignore:code=200,size=57-74
To ignore responses with status code 500 *OR* containing "Internal error".
---------
./module host=10.0.0.1 user=FILE0 -x ignore:code=500 -x ignore:fgrep='Internal error'
Remember that conditions are ANDed within the same -x option, use multiple -x options to
specify ORed conditions.
* Failures
During execution, failures may happen, such as a TCP connect timeout for
instance. A failure is actually an exception that the module does not expect,
and as a result the exception is caught upstream by the controller.
Such exceptions, or failures, are not immediately reported to the user, the
controller will retry 4 more times (see --max-retries) before reporting the
failed payload with logging level "FAIL".
* Read carefully the following examples to get a good understanding of how patator works.
{{{ FTP
* Brute-force authentication. Do not report wrong passwords.
---------
ftp_login host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:mesg='Login incorrect.'
NB0. If you get errors like "500 OOPS: priv_sock_get_cmd", use -x ignore,reset,retry:code=500
in order to retry the last login/password using a new TCP connection. Odd servers like vsftpd
return this when they shut down the TCP connection (ie. max login attempts reached).
NB1. If you get errors like "too many connections from your IP address", try decreasing the number of
threads, the server may be enforcing a maximum number of concurrent connections.
* Same as before, but stop testing a user after his password is found.
---------
ftp_login ... -x free=user:code=0
* Find anonymous FTP servers on a subnet.
---------
ftp_login host=NET0 user=anonymous password=test@example.com 0=10.0.0.0/24
}}}
{{{ SSH
* Brute-force authentication with password same as login (aka single mode). Do not report wrong passwords.
---------
ssh_login host=10.0.0.1 user=FILE0 password=FILE0 0=logins.txt -x ignore:mesg='Authentication failed.'
NB. If you get errors like "Error reading SSH protocol banner ... Connection reset by peer",
try decreasing the number of threads, the server may be enforcing a maximum
number of concurrent connections (eg. MaxStartups in OpenSSH).
* Brute-force several hosts and stop testing a host after a valid password is found.
---------
ssh_login host=FILE0 user=FILE1 password=FILE2 0=hosts.txt 1=logins.txt 2=passwords.txt -x free=host:code=0
* Same as previous, but stop testing a user on a host after his password is found.
---------
ssh_login host=FILE0 user=FILE1 password=FILE2 0=hosts.txt 1=logins.txt 2=passwords.txt -x free=host+user:code=0
}}}
{{{ Telnet
* Brute-force authentication.
(a) Enter login after first prompt is detected, enter password after second prompt.
(b) The regex to detect the login and password prompts.
(c) Reconnect when we get no login prompt back (max number of tries reached or successful login).
------------ (a)
telnet_login host=10.0.0.1 inputs='FILE0\nFILE1' 0=logins.txt 1=passwords.txt
prompt_re='tux login:|Password:' -x reset:egrep!='Login incorrect.+tux login:'
(b) (c)
NB. If you get errors like "telnet connection closed", try decreasing the number of threads,
the server may be enforcing a maximum number of concurrent connections.
}}}
{{{ SMTP
* Enumerate valid users using the VRFY command.
(a) Do not report invalid recipients.
(b) Do not report when the server shuts us down with "421 too many errors",
reconnect and resume testing.
--------- (a)
smtp_vrfy host=10.0.0.1 user=FILE0 0=logins.txt -x ignore:fgrep='User unknown in local
recipient table' -x ignore,reset,retry:code=421
(b)
* Use the RCPT TO command in case the VRFY command is not available.
---------
smtp_rcpt host=10.0.0.1 user=FILE0@localhost 0=logins.txt helo='ehlo mx.fb.com' mail_from=root
* Brute-force authentication.
(a) Send a fake hostname (by default your host fqdn is sent)
------------ (a)
smtp_login host=10.0.0.1 helo='ehlo its.me.com' user=FILE0@dom.com password=FILE1 0=logins.txt 1=passwords.txt
}}}
{{{ HTTP
* Find hidden web resources.
(a) Use a specific header.
(b) Follow redirects.
(c) Do not report 404 errors.
(d) Retry on 500 errors.
--------- (a)
http_fuzz url=http://localhost/FILE0 0=words.txt header='Cookie: SESSID=A2FD8B2DA4'
follow=1 -x ignore:code=404 -x ignore,retry:code=500
(b) (c) (d)
NB. You may be able to go 10 times faster using webef (http://www.hsc.fr/ressources/outils/webef/).
It is the fastest HTTP brute-forcer I know, yet at the moment it still lacks useful features
that will prevent you from performing the following attacks.
* Brute-force phpMyAdmin logon.
(a) Use POST requests.
(b) Follow redirects using cookies sent by server.
(c) Ignore failed authentications.
--------- (a) (b) (b)
http_fuzz url=http://10.0.0.1/phpmyadmin/index.php method=POST follow=1 accept_cookie=1
body='pma_username=root&pma_password=FILE0&server=1&lang=en' 0=passwords.txt
-x ignore:fgrep='Cannot log in to the MySQL server'
(c)
* Scan subnet for directory listings.
(a) Ignore not matching reponses.
(b) Save matching responses into directory.
---------
http_fuzz url=http://NET0/FILE1 0=10.0.0.0/24 1=dirs.txt -x ignore:fgrep!='Index of'
-l /tmp/directory_listings (a)
(b)
* Brute-force Basic authentication.
(a) Single mode (login == password).
(b) Do not report failed login attempts.
---------
http_fuzz url=http://10.0.0.1/manager/html user_pass=FILE0:FILE0 0=logins.txt -x ignore:code=401
(a) (b)
* Find hidden virtual hosts.
(a) Read template from file.
(b) Fuzz both the Host and User-Agent headers.
---------
echo -e 'Host: FILE0\nUser-Agent: FILE1' > headers.txt
http_fuzz url=http://10.0.0.1/ header=@headers.txt 0=vhosts.txt 1=agents.txt
(a) (b)
* Brute-force logon using GET requests.
(a) Encode everything surrounded by the two tags _@@_ in hexadecimal.
(b) Ignore HTTP 200 responses with a content size (header+body) within given range
and that also contain the given string.
(c) Use a different delimiter string because the comma cannot be escaped.
--------- (a) (a)
http_fuzz url='http://10.0.0.1/login?username=admin&password=_@@_FILE0_@@_' -e _@@_:hex
0=words.txt -x ignore:'code=200|size=1500-|fgrep=Welcome, unauthenticated user' -X '|'
(b) (c)
* Brute-force logon that enforces two random nonces to be submitted along every POST.
(a) First, request the page that provides the nonces as hidden input fields.
(b) Use regular expressions to extract the nonces that are to be submitted along the main request.
---------
http_fuzz url=http://10.0.0.1/login method=POST body='user=admin&pass=FILE0&nonce1=_N1_&nonce2=_N2_' 0=passwords.txt accept_cookie=1
before_urls=http://10.0.0.1/index before_egrep='_N1_:<input type="hidden" name="nonce1" value="(\w+)"|_N2_:name="nonce2" value="(\w+)"'
(a) (b)
* Test the OPTIONS method against a list of URLs.
(a) Ignore URLs that only allow the HEAD and GET methods.
(b) Header end of line is '\r\n'.
(c) Use a different delimiter string because the comma cannot be escaped.
---------
http_fuzz url=FILE0 0=urls.txt method=OPTIONS -x ignore:egrep='^Allow: HEAD, GET\r$' -X '|'
(a) (b) (c)
}}}
{{{ LDAP
* Brute-force authentication.
(a) Do not report wrong passwords.
(b) Talk SSL/TLS to port 636.
---------
ldap_login host=10.0.0.1 binddn='cn=FILE0,dc=example,dc=com' 0=logins.txt bindpw=FILE1 1=passwords.txt
-x ignore:mesg='ldap_bind: Invalid credentials (49)' ssl=1 port=636
(a) (b)
}}}
{{{ SMB
* Brute-force authentication.
---------
smb_login host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:fgrep=STATUS_LOGON_FAILURE
NB. If you suddenly get STATUS_ACCOUNT_LOCKED_OUT errors for an account
although it is not the first password you test on this account, then you must
have locked it.
* Pass-the-hash.
(a) Test a list of hosts.
(b) Test every user (each line := login:rid:LM hash:NT hash).
---------
smb_login host=FILE0 0=hosts.txt user=COMBO10 password_hash=COMBO12:COMBO13 1=pwdump.txt -x ...
(a) (b)
}}}
{{{ MSSQL
* Brute-force authentication.
-----------
mssql_login host=10.0.0.1 user=sa password=FILE0 0=passwords.txt -x ignore:fgrep='Login failed for user'
}}}
{{{ Oracle
Beware, by default in Oracle, accounts are permanently locked out after 10 wrong passwords,
except for the SYS account.
* Brute-force authentication.
------------
oracle_login host=10.0.0.1 user=SYS password=FILE0 0=passwords.txt sid=ORCL -x ignore:code=ORA-01017
NB0. With Oracle 10g XE (Express Edition), you do not need to pass a SID.
NB1. If you get ORA-12516 errors, it may be because you reached the limit of
concurrent connections or db processes, try using "--rate-limit 0.5 -t 2" to be
more polite. Also you can run "alter system set processes=150 scope=spfile;"
and restart your database to get rid of this.
* Brute-force SID.
------------
oracle_login host=10.0.0.1 sid=FILE0 0=sids.txt -x ignore:code=ORA-12505
NB. Against Oracle9, it may crash (Segmentation fault) as soon as a valid SID is
found (cx_Oracle bug). Sometimes, the SID gets printed out before the crash,
so try running the same command again if it did not.
}}}
{{{ MySQL
* Brute-force authentication.
-----------
mysql_login host=10.0.0.1 user=FILE0 password=FILE0 0=logins.txt -x ignore:fgrep='Access denied for user'
}}}
{{{ PostgresSQL
* Brute-force authentication.
-----------
pgsql_login host=10.0.0.1 user=postgres password=FILE0 0=passwords.txt -x ignore:fgrep='password authentication failed'
}}}
{{{ VNC
Some VNC servers have built-in anti-bruteforce functionnality that temporarily
blacklists the attacker IP address after too many wrong passwords.
- RealVNC-4.1.3 or TightVNC-1.3.10 for example, allow 5 failed attempts and
then enforce a 10 second delay. For each subsequent failed attempt that
delay is doubled.
- RealVNC-3.3.7 or UltraVNC allow 6 failed attempts and then enforce a 10
second delay between each following attempt.
* Brute-force authentication.
(a) No need to use more than one thread.
(b) Keep retrying the same password when we are blacklisted by the server.
(c) Exit execution as soon as a valid password is found.
--------- (a)
vnc_login host=10.0.0.1 password=FILE0 0=passwords.txt --threads 1
-x retry:fgrep!='Authentication failure' --max-retries -1 -x quit:code=0
(b) (b) (c)
}}}
{{{ DNS
* Brute-force subdomains.
(a) Ignore NXDOMAIN responses (rcode 3).
-----------
dns_forward name=FILE0.google.com 0=names.txt -x ignore:code=3
(a)
* Brute-force domain with every possible TLDs.
-----------
dns_forward name=google.MOD0 0=TLD -x ignore:code=3
* Brute-force SRV records.
-----------
dns_forward name=MOD0.microsoft.com 0=SRV qtype=SRV -x ignore:code=3
* Grab the version of several hosts.
-----------
dns_forward server=FILE0 0=hosts.txt name=version.bind qtype=txt qclass=ch
* Reverse lookup several networks.
(a) Ignore names that do not contain 'google.com'.
(b) Ignore generic PTR records.
-----------
dns_reverse host=NET0 0=216.239.32.0-216.239.47.255,8.8.8.0/24 -x ignore:code=3 -x ignore:fgrep!=google.com -x ignore:fgrep=216-239-
(a) (b)
}}}
{{{ SNMP
* SNMPv1/2 : Find valid community names.
----------
snmp_login host=10.0.0.1 community=FILE0 1=names.txt -x ignore:mesg='No SNMP response received before timeout'
* SNMPv3 : Find valid usernames.
----------
snmp_login host=10.0.0.1 version=3 user=FILE0 0=logins.txt -x ignore:mesg=unknownUserName
* SNMPv3 : Find valid passwords.
----------
snmp_login host=10.0.0.1 version=3 user=myuser auth_key=FILE0 0=passwords.txt -x ignore:mesg=wrongDigest
NB0. If you get "notInTimeWindow" error messages, increase the retries option.
NB1. SNMPv3 requires passphrases to be at least 8 characters long.
}}}
{{{ Unzip
* Brute-force the ZIP file password (cracking older pkzip encryption used to be not supported in JtR).
----------
unzip_pass zipfile=path/to/file.zip password=FILE0 0=passwords.txt -x ignore:code!=0
}}}
CHANGELOG
---------
* v0.5 2013/07/05
- new modules: mysql_query, tcp_fuzz
- new RANGE and PROG keywords (supersedes the reading from stdin feature)
- switched to impacket for mssql_login
- output more intuitive
- fixed connection cache
- minor bug fixes
* v0.4 2012/11/02
- new modules: smb_lookupsid, finger_lookup, pop_login, imap_login, vmauthd_login
- improved connection cache
- improved usage, user can now act upon specific reponses (eg. stop brute-forcing host if down, or stop testing login if password found)
- improved dns brute-forcing presentation
- switched to dnspython which is not limited to the IN class (eg. can now scan for {hostname,version}.bind)
- rewrote itertools.product to avoid memory over-consumption when using large wordlists
- can now read wordlist from stdin
- added timeout option to most of the network brute-forcing modules
- added SSL and/or TLS support to a few modules
- before_egrep now allows more than one expression (ie. useful when more than one random nonce needs to be submitted)
- fixed numerous bugs
* v0.3 2011/12/16
- minor bugs fixed in http_fuzz
- option -e better implemented
- better warnings about missing dependencies
* v0.2 2011/12/01
- new smtp_login module
- several bugs fixed
* v0.1 2011/11/25 : Public release
TODO
----
* new option -e ns like in Medusa (not likely to be implemented due to design)
* replace dnspython|paramiko|IPy with a better module (scapy|libssh2|... ?)
* use impacket/enum_lookupsids to automatically get the sid
'''
# }}}
# logging {{{
import logging
logging._levelNames[logging.ERROR] = 'FAIL'
class MyLoggingFormatter(logging.Formatter):
dft_fmt = '%(asctime)s %(name)-7s %(levelname)7s - %(message)s'
dbg_fmt = '%(asctime)s %(name)-7s %(levelname)7s [%(threadName)s] %(message)s'
def __init__(self):
logging.Formatter.__init__(self, MyLoggingFormatter.dft_fmt, datefmt='%H:%M:%S')
def format(self, record):
if record.levelno == 10: # DEBUG
self._fmt = MyLoggingFormatter.dbg_fmt
else:
self._fmt = MyLoggingFormatter.dft_fmt
return logging.Formatter.format(self, record)
handler = logging.StreamHandler()
handler.setFormatter(MyLoggingFormatter())
logger = logging.getLogger('patator')
logger.setLevel(logging.INFO)
logger.addHandler(handler)
# }}}
# imports {{{
import re
import os
from sys import exc_info, exit, version_info, maxint
from time import localtime, strftime, sleep, time
from functools import reduce
from threading import Thread, active_count
from select import select
from itertools import islice
import string
import random
from binascii import hexlify
from base64 import b64encode
from datetime import timedelta, datetime
from struct import unpack
import socket
import subprocess
import hashlib
from collections import defaultdict
try:
# python3+
from queue import Queue, Empty, Full
from urllib.parse import quote, urlencode, urlparse, urlunparse, parse_qsl, quote_plus
from io import StringIO
except ImportError:
# python2.6+
from Queue import Queue, Empty, Full
from urllib import quote, urlencode, quote_plus
from urlparse import urlparse, urlunparse, parse_qsl
from cStringIO import StringIO
warnings = []
try:
from IPy import IP
has_ipy = True
except ImportError:
has_ipy = False
warnings.append('IPy')
# imports }}}
# utils {{{
def which(program):
def is_exe(fpath):
return os.path.exists(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def create_dir(top_path):
top_path = os.path.abspath(top_path)
if os.path.isdir(top_path):
files = os.listdir(top_path)
if files:
if raw_input("Directory '%s' is not empty, do you want to wipe it ? [Y/n]: " % top_path) != 'n':
for root, dirs, files in os.walk(top_path):
if dirs:
print("Directory '%s' contains sub-directories, safely aborting..." % root)
exit(0)
for f in files:
os.unlink(os.path.join(root, f))
break
else:
os.mkdir(top_path)
return top_path
def create_time_dir(top_path, desc):
now = localtime()
date, time = strftime('%Y-%m-%d', now), strftime('%H%M%S', now)
top_path = os.path.abspath(top_path)
date_path = os.path.join(top_path, date)
time_path = os.path.join(top_path, date, time + '_' + desc)
if not os.path.isdir(top_path):
os.makedirs(top_path)
if not os.path.isdir(date_path):
os.mkdir(date_path)
if not os.path.isdir(time_path):
os.mkdir(time_path)
return time_path
def pprint_seconds(seconds, fmt):
return fmt % reduce(lambda x,y: divmod(x[0], y) + x[1:], [(seconds,),60,60])
def md5hex(plain):
return hashlib.md5(plain).hexdigest()
def sha1hex(plain):
return hashlib.sha1(plain).hexdigest()
# I rewrote itertools.product to avoid memory over-consumption when using large wordlists
def product(xs, *rest):
if len(rest) == 0:
for x in xs():
yield [x]
else:
for head in xs():
for tail in product(*rest):
yield [head] + tail
def chain(*iterables):
def xs():
for iterable in iterables:
for element in iterable:
yield element
return xs
class FileIter:
def __init__(self, filename):
self.filename = filename
def __iter__(self):
return open(self.filename)
# These are examples. You can easily write your own iterator to fit your needs.
# Or using the PROG keyword, you can call an external program such as:
# - seq(1) from coreutils
# - http://hashcat.net/wiki/doku.php?id=maskprocessor
# - john -stdout -i
# For instance:
# $ ./dummy_test data=PROG0 0='seq 1 80'
# $ ./dummy_test data=PROG0 0='mp64.bin ?l?l?l',$(mp64.bin --combination ?l?l?l)
class RangeIter:
def __init__(self, typ, rng, random=None): #random.Random()):
if typ in ('hex', 'int', 'float'):
m = re.match(r'(-?.+?)-(-?.+)$', rng) # 5-50 or -5-50 or 5--50 or -5--50
if not m:
raise NotImplementedError("Unsupported range '%s'" % rng)
mn = m.group(1)
mx = m.group(2)
if typ == 'hex':
mn = int(mn, 16)
mx = int(mx, 16)
fmt = '%x'
elif typ == 'int':
mn = int(mn)
mx = int(mx)
fmt = '%d'
elif typ == 'float':
from decimal import Decimal
mn = Decimal(mn)
mx = Decimal(mx)
if mn > mx:
step = -1
else:
step = 1
elif typ == 'letters':
charset = [c for c in string.letters]
elif typ in ('lower', 'lowercase'):
charset = [c for c in string.lowercase]
elif typ in ('upper', 'uppercase'):
charset = [c for c in string.uppercase]
else:
raise NotImplementedError("Incorrect type '%s'" % typ)
def zrange(start, stop, step, fmt):
x = start
while x != stop+step:
yield fmt % x
x += step
def letterrange(first, last, charset):
for k in range(len(last)):
for x in product(*[chain(charset)]*(k+1)):
result = ''.join(x)
if first:
if first != result:
continue
else:
first = None
yield result
if result == last:
return
if typ == 'float':
precision = max(len(str(x).partition('.')[-1]) for x in (mn, mx))
fmt = '%%.%df' % precision
exp = 10**precision
step *= Decimal(1) / exp
self.generator = zrange(mn, mx, step, fmt)
self.size = int(abs(mx-mn) * exp) + 1
def random_generator():
while True:
yield fmt % (Decimal(random.randint(mn*exp, mx*exp)) / exp)
elif typ in ('hex', 'int'):
self.generator = zrange(mn, mx, step, fmt)
self.size = abs(mx-mn) + 1
def random_generator():
while True:
yield fmt % random.randint(mn, mx)
else: # letters, lower, upper
def count(f):
total = 0
i = 0
for c in f[::-1]:
z = charset.index(c) + 1
total += (len(charset)**i)*z
i += 1
return total + 1
first, last = rng.split('-')
self.generator = letterrange(first, last, charset)
self.size = count(last) - count(first) + 1
if random:
self.generator = random_generator()
self.size = maxint
def __iter__(self):
return self.generator
def __len__(self):
return self.size
# }}}
# Controller {{{
class Controller:
builtin_actions = (
('ignore', 'do not report'),
('retry', 'try payload again'),
('free', 'dismiss future similar payloads'),
('quit', 'terminate execution now'),
)
available_encodings = {
'hex': (hexlify, 'encode in hexadecimal'),
'b64': (b64encode, 'encode in base64'),
'md5': (md5hex, 'hash in md5'),
'sha1': (sha1hex, 'hash in sha1'),
'url': (quote_plus, 'url encode'),
}
def expand_key(self, arg):
yield arg.split('=', 1)
def find_file_keys(self, value):
return map(int, re.findall(r'FILE(\d)', value))
def find_net_keys(self, value):
return map(int, re.findall(r'NET(\d)', value))
def find_combo_keys(self, value):
return [map(int, t) for t in re.findall(r'COMBO(\d)(\d)', value)]
def find_module_keys(self, value):
return map(int, re.findall(r'MOD(\d)', value))
def find_range_keys(self, value):
return map(int, re.findall(r'RANGE(\d)', value))
def find_prog_keys(self, value):
return map(int, re.findall(r'PROG(\d)', value))
def usage_parser(self, name):
from optparse import OptionParser
from optparse import OptionGroup
from optparse import IndentedHelpFormatter
class MyHelpFormatter(IndentedHelpFormatter):
def format_epilog(self, epilog):
return epilog
def format_heading(self, heading):
if self.current_indent == 0 and heading == 'Options':
heading = 'Global options'
return "%*s%s:\n" % (self.current_indent, "", heading)
def format_usage(self, usage):
return '%s\nUsage: %s\n' % (__banner__, usage)
available_actions = self.builtin_actions + self.module.available_actions
available_conditions = self.module.Response.available_conditions
usage = '''%%prog <module-options ...> [global-options ...]
Examples:
%s''' % '\n '.join(self.module.usage_hints)
usage += '''
Module options:
%s ''' % ('\n'.join(' %-14s: %s' % (k, v) for k, v in self.module.available_options))
epilog = '''
Syntax:
-x actions:conditions
actions := action[,action]*
action := "%s"
conditions := condition=value[,condition=value]*
condition := "%s"
''' % ('" | "'.join(k for k, v in available_actions),
'" | "'.join(k for k, v in available_conditions))
epilog += '''
%s
%s
''' % ('\n'.join(' %-12s: %s' % (k, v) for k, v in available_actions),
'\n'.join(' %-12s: %s' % (k, v) for k, v in available_conditions))
epilog += '''
For example, to ignore all redirects to the home page:
... -x ignore:code=302,fgrep='Location: /home.html'
-e tag:encoding
tag := any unique string (eg. T@G or _@@_ or ...)
encoding := "%s"
%s''' % ('" | "'.join(k for k in self.available_encodings),
'\n'.join(' %-12s: %s' % (k, v) for k, (f, v) in self.available_encodings.items()))
epilog += '''
For example, to encode every password in base64:
... host=10.0.0.1 user=admin password=_@@_FILE0_@@_ -e _@@_:b64
Please read the README inside for more examples and usage information.
'''
parser = OptionParser(usage=usage, prog=name, epilog=epilog, version=__banner__, formatter=MyHelpFormatter())
exe_grp = OptionGroup(parser, 'Execution')
exe_grp.add_option('-x', dest='actions', action='append', default=[], metavar='arg', help='actions and conditions, see Syntax below')
exe_grp.add_option('--start', dest='start', type='int', default=0, metavar='N', help='start from offset N in the wordlist product')
exe_grp.add_option('--stop', dest='stop', type='int', default=None, metavar='N', help='stop at offset N')
exe_grp.add_option('--resume', dest='resume', metavar='r1[,rN]*', help='resume previous run')
exe_grp.add_option('-e', dest='encodings', action='append', default=[], metavar='arg', help='encode everything between two tags, see Syntax below')
exe_grp.add_option('-C', dest='combo_delim', default=':', metavar='str', help="delimiter string in combo files (default is ':')")
exe_grp.add_option('-X', dest='condition_delim', default=',', metavar='str', help="delimiter string in conditions (default is ',')")
opt_grp = OptionGroup(parser, 'Optimization')
opt_grp.add_option('--rate-limit', dest='rate_limit', type='float', default=0, metavar='N', help='wait N seconds between tests (default is 0)')
opt_grp.add_option('--max-retries', dest='max_retries', type='int', default=4, metavar='N', help='skip payload after N failures (default is 4) (-1 for unlimited)')
opt_grp.add_option('-t', '--threads', dest='num_threads', type='int', default=10, metavar='N', help='number of threads (default is 10)')
log_grp = OptionGroup(parser, 'Logging')
log_grp.add_option('-l', dest='log_dir', metavar='DIR', help="save output and response data into DIR ")
log_grp.add_option('-L', dest='auto_log', metavar='SFX', help="automatically save into DIR/yyyy-mm-dd/hh:mm:ss_SFX (DIR defaults to '/tmp/patator')")
dbg_grp = OptionGroup(parser, 'Debugging')
dbg_grp.add_option('-d', '--debug', dest='debug', action='store_true', default=False, help='enable debug messages')
parser.option_groups.extend([exe_grp, opt_grp, log_grp, dbg_grp])
return parser
def parse_usage(self, argv):
parser = self.usage_parser(argv[0])
opts, args = parser.parse_args(argv[1:])
if opts.debug:
logger.setLevel(logging.DEBUG)
if not len(args) > 0:
parser.print_usage()
print('ERROR: wrong usage. Please read the README inside for more information.')
exit(2)
return opts, args
def __init__(self, module, argv):
self.actions = {}
self.free_list = []
self.paused = False
self.start_time = 0
self.total_size = 1
self.quit_now = False
self.log_dir = None
self.thread_report = []
self.thread_progress = []
self.payload = {}
self.iter_keys = {}
self.enc_keys = []
self.module = module
opts, args = self.parse_usage(argv)
self.combo_delim = opts.combo_delim
self.condition_delim = opts.condition_delim
self.rate_limit = opts.rate_limit
self.max_retries = opts.max_retries
self.num_threads = opts.num_threads
self.start, self.stop, self.resume = opts.start, opts.stop, opts.resume
wlists = {}
kargs = []
for arg in args: # ('host=NET0', '0=10.0.0.0/24', 'user=COMBO10', 'password=COMBO11', '1=combos.txt', 'name=google.MOD2', '2=TLD')
for k, v in self.expand_key(arg):
logger.debug('k: %s, v: %s' % (k, v))
if k.isdigit():
wlists[k] = v
else:
if v.startswith('@'):
p = os.path.expanduser(v[1:])
v = open(p).read()
kargs.append((k, v))
iter_vals = [v for k, v in sorted(wlists.items())]
logger.debug('kargs: %s' % kargs) # [('host', 'NET0'), ('user', 'COMBO10'), ('password', 'COMBO11'), ('domain', 'MOD2')]
logger.debug('iter_vals: %s' % iter_vals) # ['10.0.0.0/24', 'combos.txt', 'TLD']
for k, v in kargs:
for e in opts.encodings:
meta, enc = e.split(':')
if re.search(r'{0}.+?{0}'.format(meta), v):
self.enc_keys.append((k, meta, self.available_encodings[enc][0]))
for i in self.find_file_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('FILE', iter_vals[i], [])
self.iter_keys[i][2].append(k)
else:
for i in self.find_net_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('NET', iter_vals[i], [])
self.iter_keys[i][2].append(k)
if not has_ipy:
logger.warn('IPy (https://github.com/haypo/python-ipy) is required for using NETx keywords.')
logger.warn('Please read the README inside for more information.')
exit(3)
else:
for i, j in self.find_combo_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('COMBO', iter_vals[i], [])
self.iter_keys[i][2].append((j, k))
else:
for i in self.find_module_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('MOD', iter_vals[i], [])
self.iter_keys[i][2].append(k)
else:
for i in self.find_range_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('RANGE', iter_vals[i], [])
self.iter_keys[i][2].append(k)
else:
for i in self.find_prog_keys(v):
if i not in self.iter_keys:
self.iter_keys[i] = ('PROG', iter_vals[i], [])
self.iter_keys[i][2].append(k)
else:
self.payload[k] = v
logger.debug('iter_keys: %s' % self.iter_keys) # { 0: ('NET', '10.0.0.0/24', ['host']), 1: ('COMBO', 'combos.txt', [(0, 'user'), (1, 'password')]), 2: ('MOD', 'TLD', ['name'])
logger.debug('enc_keys: %s' % self.enc_keys) # [('password', 'ENC', hexlify), ('header', 'B64', b64encode), ...
logger.debug('payload: %s' % self.payload)
self.available_actions = [k for k, _ in self.builtin_actions + self.module.available_actions]
self.module_actions = [k for k, _ in self.module.available_actions]
for x in opts.actions:
self.update_actions(x)
logger.debug('actions: %s' % self.actions)
if opts.auto_log:
self.log_dir = create_time_dir(opts.log_dir or '/tmp/patator', opts.auto_log)
elif opts.log_dir:
self.log_dir = create_dir(opts.log_dir)
if self.log_dir:
log_file = os.path.join(self.log_dir, 'RUNTIME.log')
with open(log_file, 'a') as f:
f.write('$ %s\n' % ' '.join(argv))
handler = logging.FileHandler(log_file)
handler.setFormatter(MyLoggingFormatter())
logging.getLogger('patator').addHandler(handler)
def update_actions(self, arg):
actions, conditions = arg.split(':', 1)
for action in actions.split(','):
conds = [c.split('=', 1) for c in conditions.split(self.condition_delim)]
if '=' in action:
name, opts = action.split('=')
else:
name, opts = action, None
if name not in self.available_actions:
raise NotImplementedError('Unsupported action: %s' % name)
if name not in self.actions:
self.actions[name] = []
self.actions[name].append((conds, opts))
def lookup_actions(self, resp):
actions = {}
for action, conditions in self.actions.items():
for condition, opts in conditions:
for key, val in condition:
if key[-1] == '!':
if resp.match(key[:-1], val):
break
else:
if not resp.match(key, val):
break
else:
actions[action] = opts
return actions
def check_free(self, payload):
# free_list: 'host=10.0.0.1', 'user=anonymous', 'host=10.0.0.7,user=test', ...
for m in self.free_list:
args = m.split(',', 1)
for arg in args:
k, v = arg.split('=', 1)
if payload[k] != v:
break
else:
return True
return False
def register_free(self, payload, opts):
self.free_list.append(','.join('%s=%s' % (k, payload[k]) for k in opts.split('+')))
logger.debug('free_list updated: %s' % self.free_list)
def fire(self):
logger.info('Starting %s at %s' % (__banner__, strftime('%Y-%m-%d %H:%M %Z', localtime())))
try:
self.start_threads()
self.monitor_progress()
except KeyboardInterrupt:
self.quit_now = True
except:
self.quit_now = True
logger.exception(exc_info()[1])
try:
while active_count() > 1:
sleep(.1)
self.report_progress()
except KeyboardInterrupt:
pass
hits_count = sum(p.hits_count for p in self.thread_progress)
done_count = sum(p.done_count for p in self.thread_progress)
skip_count = sum(p.skip_count for p in self.thread_progress)
fail_count = sum(p.fail_count for p in self.thread_progress)
total_time = time() - self.start_time
speed_avg = done_count / total_time
if self.total_size >= maxint:
self.total_size = -1
self.show_final()
logger.info('Hits/Done/Skip/Fail/Size: %d/%d/%d/%d/%d, Avg: %d r/s, Time: %s' % (
hits_count, done_count, skip_count, fail_count, self.total_size, speed_avg,
pprint_seconds(total_time, '%dh %dm %ds')))
if self.quit_now:
resume = []
for i, p in enumerate(self.thread_progress):
c = p.done_count + p.skip_count
if self.resume:
if i < len(self.resume):
c += self.resume[i]
resume.append(str(c))
logger.info('To resume execution, pass --resume %s' % ','.join(resume))
def push_final(self, resp): pass
def show_final(self): pass
def start_threads(self):
class Progress:
def __init__(self):
self.current = ''
self.done_count = 0
self.hits_count = 0
self.skip_count = 0
self.fail_count = 0
self.seconds = [1]*25 # avoid division by zero early bug condition
task_queues = [Queue(maxsize=10000) for _ in range(self.num_threads)]
# consumers
for num in range(self.num_threads):
report_queue = Queue(maxsize=1000)
t = Thread(target=self.consume, args=(task_queues[num], report_queue))
t.daemon = True
t.start()
self.thread_report.append(report_queue)
self.thread_progress.append(Progress())
# producer
t = Thread(target=self.produce, args=(task_queues,))
t.daemon = True
t.start()
def produce(self, task_queues):
iterables = []
for _, (t, v, _) in self.iter_keys.items():
if t in ('FILE', 'COMBO'):
size = 0
files = []
for fname in v.split(','):
fpath = os.path.expanduser(fname)
size += sum(1 for _ in open(fpath))
files.append(FileIter(fpath))
iterable = chain(*files)
elif t == 'NET':
subnets = [IP(n, make_net=True) for n in v.split(',')]
size = sum(len(s) for s in subnets)
iterable = chain(*subnets)
elif t == 'MOD':
elements, size = self.module.available_keys[v]()
iterable = chain(elements)
elif t == 'RANGE':
size = 0
ranges = []
for r in v.split(','):
typ, opt = r.split(':', 1)
if typ not in ['hex', 'int', 'float', 'letters', 'lower', 'lowercase', 'upper', 'uppercase']:
raise NotImplementedError("Incorrect range type '%s'" % typ)
it = RangeIter(typ, opt)
size += len(it)
ranges.append(it)
iterable = chain(*ranges)
elif t == 'PROG':
m = re.match(r'(.+),(\d+)$', v)
if m:
prog, size = m.groups()
else:
prog, size = v, maxint
logger.debug('prog: %s, size: %s' % (prog, size))
p = subprocess.Popen(prog.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
iterable, size = chain(p.stdout), int(size)
else:
raise NotImplementedError("Incorrect keyword '%s'" % t)
self.total_size *= size
iterables.append(iterable)
if not iterables:
iterables.append(chain(['']))
if self.stop:
self.total_size = self.stop - self.start
else:
self.total_size -= self.start
if self.resume:
self.resume = [int(i) for i in self.resume.split(',')]
self.total_size -= sum(self.resume)
logger.info('')
logger.info(self.module.Response.logformat % self.module.Response.logheader)
logger.info('-' * 70)
self.start_time = time()
count = 0
for pp in islice(product(*iterables), self.start, self.stop):
cid = count % self.num_threads
prod = [str(p).strip('\r\n') for p in pp]
if self.resume:
idx = count % len(self.resume)
off = self.resume[idx]
if count < off * len(self.resume):
#logger.debug('Skipping %d %s, resume[%d]: %s' % (count, ':'.join(prod), idx, self.resume[idx]))
count += 1
continue
while True:
if self.quit_now:
return
try:
task_queues[cid].put_nowait(prod)
break
except Full:
sleep(.1)
count += 1
for q in task_queues:
q.put(None)
def consume(self, task_queue, report_queue):
module = self.module()
def shutdown():
logger.debug('thread exits')
if hasattr(module, '__del__'):
module.__del__()
while True:
if self.quit_now:
shutdown()
return
try:
prod = task_queue.get_nowait()
except Empty:
sleep(.1)
continue
if prod is None:
shutdown()
return
payload = self.payload.copy()
for i, (t, _, keys) in self.iter_keys.items():
if t == 'FILE':
for k in keys:
payload[k] = payload[k].replace('FILE%d' % i, prod[i])
elif t == 'NET':
for k in keys:
payload[k] = payload[k].replace('NET%d' % i, prod[i])
elif t == 'COMBO':
for j, k in keys:
payload[k] = payload[k].replace('COMBO%d%d' % (i, j), prod[i].split(self.combo_delim)[j])
elif t == 'MOD':
for k in keys:
payload[k] = payload[k].replace('MOD%d' %i, prod[i])
elif t == 'RANGE':
for k in keys:
payload[k] = payload[k].replace('RANGE%d' %i, prod[i])
elif t == 'PROG':
for k in keys:
payload[k] = payload[k].replace('PROG%d' %i, prod[i])
for k, m, e in self.enc_keys:
payload[k] = re.sub(r'{0}(.+?){0}'.format(m), lambda m: e(m.group(1)), payload[k])
logger.debug('product: %s' % prod)
pp_prod = ':'.join(prod)
if self.check_free(payload):
report_queue.put(('skip', pp_prod, None, 0))
continue
try_count = 0
start_time = time()
while True:
while self.paused and not self.quit_now:
sleep(1)
if self.quit_now:
shutdown()
return
if self.rate_limit:
sleep(self.rate_limit)
if try_count <= self.max_retries or self.max_retries < 0:
actions = {}
try_count += 1
logger.debug('payload: %s [try %d/%d]' % (payload, try_count, self.max_retries+1))
try:
exec_time = time()
resp = module.execute(**payload)
resp.time = time() - exec_time
except:
e_type, e_value, _ = exc_info()
mesg = '%s %s' % (e_type, e_value.args)
#logger.exception(exc_info()[1])
logger.debug('except: %s' % mesg)
resp = self.module.Response('xxx', mesg)
if hasattr(module, 'reset'):
module.reset()
sleep(try_count * .1)
continue
else:
actions = {'fail': None}
actions.update(self.lookup_actions(resp))
report_queue.put((actions, pp_prod, resp, time() - start_time))
for name in self.module_actions:
if name in actions:
getattr(module, name)(**payload)
if 'free' in actions:
self.register_free(payload, actions['free'])
break
if 'fail' in actions:
break
if 'retry' in actions:
continue
break
def monitor_progress(self):
while active_count() > 1 and not self.quit_now:
self.report_progress()
self.monitor_interaction()
def report_progress(self):
for i, pq in enumerate(self.thread_report):
p = self.thread_progress[i]
for _ in range(pq.maxsize):
try:
actions, current, resp, seconds = pq.get_nowait()
#logger.info('actions reported: %s' % '+'.join(actions))
except Empty:
break
if actions == 'skip':
p.skip_count += 1
continue
if self.resume:
offset = p.done_count + self.resume[i]
else:
offset = p.done_count
offset = (offset * self.num_threads) + i + 1 + self.start
p.current = current
p.seconds[p.done_count % len(p.seconds)] = seconds
msg = self.module.Response.logformat % (resp.compact()+(current, offset, resp))
if 'fail' in actions:
logger.error(msg)
elif 'ignore' not in actions:
logger.info(msg)
if 'fail' in actions:
p.fail_count += 1
elif 'retry' in actions:
continue
elif 'ignore' not in actions:
p.hits_count += 1
if self.log_dir:
filename = '%d_%s' % (offset, ':'.join(map(str, resp.compact())))
with open('%s/%s.txt' % (self.log_dir, filename), 'w') as f:
f.write(resp.dump())
self.push_final(resp)
p.done_count += 1
if 'quit' in actions:
self.quit_now = True
def monitor_interaction(self):
from sys import stdin
i, _, _ = select([stdin], [], [], .1)
if not i: return
command = i[0].readline().strip()
if command == 'h':
logger.info('''Available commands:
h show help
<Enter> show progress
d/D increase/decrease debug level
p pause progress
f show verbose progress
x arg add monitor condition
a show all active conditions
q terminate execution now
''')
elif command == 'q':
self.quit_now = True
elif command == 'p':
self.paused = not self.paused
logger.info(self.paused and 'Paused' or 'Unpaused')
elif command == 'd':
logger.setLevel(logging.DEBUG)
elif command == 'D':
logger.setLevel(logging.INFO)
elif command == 'a':
logger.info(self.actions)
elif command.startswith('x'):
_, arg = command.split(' ', 1)
try:
self.update_actions(arg)
except ValueError:
logger.warn('usage: x actions:conditions')
else: # show progress
total_count = sum(p.done_count+p.skip_count for p in self.thread_progress)
speed_avg = self.num_threads / (sum(sum(p.seconds) / len(p.seconds) for p in self.thread_progress) / self.num_threads)
if self.total_size >= maxint:
etc_time = 'inf'
remain_time = 'inf'
else:
remain_seconds = (self.total_size - total_count) / speed_avg
remain_time = pprint_seconds(remain_seconds, '%02d:%02d:%02d')
etc_seconds = datetime.now() + timedelta(seconds=remain_seconds)
etc_time = etc_seconds.strftime('%H:%M:%S')
logger.info('Progress: {0:>3}% ({1}/{2}) | Speed: {3:.0f} r/s | ETC: {4} ({5} remaining) {6}'.format(
total_count * 100/self.total_size,
total_count,
self.total_size,
speed_avg,
etc_time,
remain_time,
self.paused and '| Paused' or ''))
if command == 'f':
for i, p in enumerate(self.thread_progress):
total_count = p.done_count + p.skip_count
logger.info(' {0:>3}: {1:>3}% ({2}/{3}) {4}'.format(
'#%d' % (i+1),
int(100*total_count/(1.0*self.total_size/self.num_threads)),
total_count,
self.total_size/self.num_threads,
p.current))
# }}}
# Response_Base {{{
def match_range(size, val):
if '-' in val:
size_min, size_max = val.split('-')
if not size_min and not size_max:
raise ValueError('Invalid interval')
elif not size_min: # size == -N
return size <= float(size_max)
elif not size_max: # size == N-
return size >= float(size_min)
else:
size_min, size_max = float(size_min), float(size_max)
if size_min >= size_max:
raise ValueError('Invalid interval')
return size_min <= size <= size_max
else:
return size == float(val)
class Response_Base:
available_conditions = (
('code', 'match status code'),
('size', 'match size (N or N-M or N- or -N)'),
('time', 'match time (N or N-M or N- or -N)'),
('mesg', 'match message'),
('fgrep', 'search for string in mesg'),
('egrep', 'search for regex in mesg'),
)
logformat = '%-5s %-4s %6s | %-34s | %5s | %s'
logheader = ('code', 'size', 'time', 'candidate', 'num', 'mesg')
def __init__(self, code, mesg, trace=None):
self.code = code
self.mesg = mesg
self.trace = trace
self.size = len(self.mesg)
self.time = 0
def compact(self):
return self.code, self.size, '%.3f' % self.time
def __str__(self):
return self.mesg
def match(self, key, val):
return getattr(self, 'match_'+key)(val)
def match_code(self, val):
return val == str(self.code)
def match_size(self, val):
return match_range(self.size, val)
def match_time(self, val):
return match_range(self.time, val)
def match_mesg(self, val):
return val == self.mesg
def match_fgrep(self, val):
return val in str(self)
def match_egrep(self, val):
return re.search(val, str(self))
def dump(self):
return self.trace or str(self)
# }}}
# TCP_Cache {{{
class TCP_Connection:
def __init__(self, fp, banner=None):
self.fp = fp
self.banner = banner
def close(self):
self.fp.close()
class TCP_Cache:
available_actions = (
('reset', 'close current connection in order to reconnect next time'),
)
available_options = (
('persistent', 'use persistent connections [1|0]'),
)
def __init__(self):
self.cache = {} # {'10.0.0.1:22': ('root', conn1), '10.0.0.2:22': ('admin', conn2),
self.curr = None
def __del__(self):
for _, (_, c) in self.cache.items():
c.close()
self.cache.clear()
def bind(self, host, port, *args, **kwargs):
hp = '%s:%s' % (host, port)
key = ':'.join(args)
if hp in self.cache:
k, c = self.cache[hp]
if key == k:
self.curr = hp, k, c
return c.fp, c.banner
else:
c.close()
del self.cache[hp]
self.curr = None
conn = self.connect(host, port, *args, **kwargs)
self.cache[hp] = (key, conn)
self.curr = hp, key, conn
return conn.fp, conn.banner
def reset(self, **kwargs):
if self.curr:
hp, _, c = self.curr
c.close()
del self.cache[hp]
self.curr = None
# }}}
# FTP {{{
from ftplib import FTP, Error as FTP_Error
try:
from ftplib import FTP_TLS # New in python 2.7
except ImportError:
logger.warn('TLS support to FTP was implemented in python 2.7')
class FTP_login(TCP_Cache):
'''Brute-force FTP'''
usage_hints = (
"""%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt"""
""" -x ignore:mesg='Login incorrect.' -x ignore,reset,retry:code=500""",
)
available_options = (
('host', 'target host'),
('port', 'target port [21]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('tls', 'use TLS [0|1]'),
('timeout', 'seconds to wait for a response [10]'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, tls, timeout):
if tls == '0':
fp = FTP(timeout=int(timeout))
else:
fp = FTP_TLS(timeout=int(timeout))
banner = fp.connect(host, int(port))
return TCP_Connection(fp, banner)
def execute(self, host, port='21', tls='0', user=None, password=None, timeout='10', persistent='1'):
fp, resp = self.bind(host, port, tls, timeout=timeout)
try:
if user is not None:
resp = fp.sendcmd('USER ' + user)
if password is not None:
resp = fp.sendcmd('PASS ' + password)
logger.debug('No error: %s' % resp)
self.reset()
except FTP_Error as e:
resp = str(e)
logger.debug('FTP_Error: %s' % resp)
if persistent == '0':
self.reset()
code, mesg = resp.split(' ', 1)
return self.Response(code, mesg)
# }}}
# SSH {{{
try:
import paramiko
l = logging.getLogger('paramiko.transport')
l.setLevel(logging.CRITICAL)
l.addHandler(handler)
except ImportError:
warnings.append('paramiko')
class SSH_login(TCP_Cache):
'''Brute-force SSH'''
usage_hints = (
"""%prog host=10.0.0.1 user=root password=FILE0 0=passwords.txt -x ignore:mesg='Authentication failed.'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [22]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('auth_type', 'auth type to use [password|keyboard-interactive]'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, user):
fp = paramiko.Transport('%s:%s' % (host, int(port)))
fp.start_client()
return TCP_Connection(fp, fp.remote_version)
def execute(self, host, port='22', user=None, password=None, auth_type='password', persistent='1'):
fp, banner = self.bind(host, port, user)
try:
if user is not None and password is not None:
if auth_type == 'password':
fp.auth_password(user, password, fallback=False)
elif auth_type == 'keyboard-interactive':
fp.auth_interactive(user, lambda a,b,c: [password] if len(c) == 1 else [])
else:
raise NotImplementedError("Incorrect auth_type '%s'" % auth_type)
logger.debug('No error')
code, mesg = '0', banner
self.reset()
except paramiko.AuthenticationException as e:
logger.debug('AuthenticationException: %s' % e)
code, mesg = '1', str(e)
if persistent == '0':
self.reset()
return self.Response(code, mesg)
# }}}
# Telnet {{{
from telnetlib import Telnet
class Telnet_login(TCP_Cache):
'''Brute-force Telnet'''
usage_hints = (
"""%prog host=10.0.0.1 inputs='FILE0\\nFILE1' 0=logins.txt 1=passwords.txt persistent=0"""
""" prompt_re='Username:|Password:' -x ignore:egrep='Login incorrect.+Username:'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [23]'),
('inputs', 'list of values to input'),
('prompt_re', 'regular expression to match prompts [\w+]'),
('timeout', 'seconds to wait for a response and for prompt_re to match received data [20]'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, timeout):
self.prompt_count = 0
fp = Telnet(host, int(port), int(timeout))
return TCP_Connection(fp)
def execute(self, host, port='23', inputs=None, prompt_re='\w+:', timeout='20', persistent='1'):
fp, _ = self.bind(host, port, timeout=timeout)
trace = ''
timeout = int(timeout)
if self.prompt_count == 0:
_, _, raw = fp.expect([prompt_re], timeout=timeout)
logger.debug('raw banner: %s' % repr(raw))
trace += raw
self.prompt_count += 1
if inputs is not None:
for val in inputs.split(r'\n'):
logger.debug('input: %s' % val)
cmd = val + '\n' #'\r\x00'
fp.write(cmd)
trace += cmd
_, _, raw = fp.expect([prompt_re], timeout=timeout)
logger.debug('raw %d: %s' % (self.prompt_count, repr(raw)))
trace += raw
self.prompt_count += 1
if persistent == '0':
self.reset()
mesg = repr(raw)[1:-1] # strip enclosing single quotes
return self.Response(0, mesg, trace)
# }}}
# SMTP {{{
from smtplib import SMTP, SMTP_SSL, SMTPAuthenticationError, SMTPHeloError, SMTPException
class SMTP_Base(TCP_Cache):
available_options = TCP_Cache.available_options
available_options += (
('timeout', 'seconds to wait for a response [10]'),
('host', 'target host'),
('port', 'target port [25]'),
('ssl', 'use SSL [0|1]'),
('helo', 'helo or ehlo command to send after connect [skip]'),
('starttls', 'send STARTTLS [0|1]'),
('user', 'usernames to test'),
)
Response = Response_Base
def connect(self, host, port, ssl, helo, starttls, timeout):
if ssl == '0':
if not port: port = 25
fp = SMTP(timeout=int(timeout))
else:
if not port: port = 465
fp = SMTP_SSL(timeout=int(timeout))
resp = fp.connect(host, int(port))
if helo:
cmd, name = helo.split(' ', 1)
if cmd.lower() == 'ehlo':
resp = fp.ehlo(name)
else:
resp = fp.helo(name)
if not starttls == '0':
resp = fp.starttls()
return TCP_Connection(fp, resp)
class SMTP_vrfy(SMTP_Base):
'''Enumerate valid users using SMTP VRFY'''
usage_hints = (
'''%prog host=10.0.0.1 user=FILE0 0=logins.txt [helo='ehlo its.me.com']'''
''' -x ignore:fgrep='User unknown' -x ignore,reset,retry:code=421''',
)
def execute(self, host, port='', ssl='0', helo='', starttls='0', user=None, timeout='10', persistent='1'):
fp, resp = self.bind(host, port, ssl, helo, starttls, timeout=timeout)
if user is not None:
resp = fp.verify(user)
if persistent == '0':
self.reset()
code, mesg = resp
return self.Response(code, mesg)
class SMTP_rcpt(SMTP_Base):
'''Enumerate valid users using SMTP RCPT TO'''
usage_hints = (
'''%prog host=10.0.0.1 user=FILE0@localhost 0=logins.txt [helo='ehlo its.me.com']'''
''' [mail_from=bar@example.com] -x ignore:fgrep='User unknown' -x ignore,reset,retry:code=421''',
)
available_options = SMTP_Base.available_options
available_options += (
('mail_from', 'sender email [test@example.org]'),
)
def execute(self, host, port='', ssl='0', helo='', starttls='0', mail_from='test@example.org', user=None, timeout='10', persistent='1'):
fp, resp = self.bind(host, port, ssl, helo, starttls, timeout=timeout)
if mail_from:
resp = fp.mail(mail_from)
if user:
resp = fp.rcpt(user)
fp.rset()
if persistent == '0':
self.reset()
code, mesg = resp
return self.Response(code, mesg)
class SMTP_login(SMTP_Base):
'''Brute-force SMTP'''
usage_hints = (
'''%prog host=10.0.0.1 user=f.bar@dom.com password=FILE0 0=passwords.txt [helo='ehlo its.me.com']'''
''' -x ignore:fgrep='Authentication failed' -x ignore,reset,retry:code=421''',
)
available_options = SMTP_Base.available_options
available_options += (
('password', 'passwords to test'),
)
def execute(self, host, port='', ssl='0', helo='', starttls='0', user=None, password=None, timeout='10', persistent='1'):
fp, resp = self.bind(host, port, ssl, helo, starttls, timeout=timeout)
try:
if user is not None and password is not None:
resp = fp.login(user, password)
logger.debug('No error: %s' % resp)
self.reset()
except (SMTPHeloError,SMTPAuthenticationError,SMTPException) as resp:
logger.debug('SMTPError: %s' % resp)
if persistent == '0':
self.reset()
code, mesg = resp
return self.Response(code, mesg)
# }}}
# Finger {{{
class Controller_Finger(Controller):
user_list = []
def push_final(self, resp):
if hasattr(resp, 'lines'):
for l in resp.lines:
if l not in self.user_list:
self.user_list.append(l)
def show_final(self):
print('\n'.join(self.user_list))
class Finger_lookup:
'''Enumerate valid users using Finger'''
usage_hints = (
"""%prog host=10.0.0.1 user=FILE0 0=words.txt -x ignore:fgrep='no such user'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [79]'),
('user', 'usernames to test'),
('timeout', 'seconds to wait for a response [5]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='79', user='', timeout='5'):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(int(timeout))
s.connect((host, int(port)))
if user:
s.send(user)
s.send('\r\n')
data = ''
while True:
raw = s.recv(1024)
if not raw:
break
data += raw
s.close()
logger.debug('recv: %s' % repr(data))
data = data.strip()
mesg = repr(data)
resp = self.Response(0, mesg, data)
resp.lines = [l.strip('\r\n') for l in data.split('\n')]
return resp
# }}}
# LDAP {{{
if not which('ldapsearch'):
warnings.append('openldap')
# Because python-ldap-2.4.4 did not allow using a PasswordPolicyControl
# during bind authentication (cf. http://article.gmane.org/gmane.comp.python.ldap/1003),
# I chose to wrap around ldapsearch with "-e ppolicy".
class LDAP_login:
'''Brute-force LDAP'''
usage_hints = (
"""%prog host=10.0.0.1 binddn='cn=Directory Manager' bindpw=FILE0 0=passwords.txt"""
""" -x ignore:mesg='ldap_bind: Invalid credentials (49)'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [389]'),
('binddn', 'usernames to test'),
('bindpw', 'passwords to test'),
('basedn', 'base DN for search'),
('ssl', 'use SSL/TLS [0|1]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='389', binddn='', bindpw='', basedn='', ssl='0'):
uri = 'ldap%s://%s:%s' % ('s' if ssl != '0' else '', host, port)
cmd = ['ldapsearch', '-H', uri, '-e', 'ppolicy', '-D', binddn, '-w', bindpw, '-b', basedn, '-s', 'one']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'LDAPTLS_REQCERT': 'never'})
out = p.stdout.read()
err = p.stderr.read()
code = p.wait()
mesg = repr((out + err).strip())[1:-1]
trace = '[out]\n%s\n[err]\n%s' % (out, err)
return self.Response(code, mesg, trace)
# }}}
# SMB {{{
try:
from impacket import smb as impacket_smb
from impacket.dcerpc import dcerpc, transport, lsarpc
except ImportError:
warnings.append('impacket')
class SMB_Connection(TCP_Connection):
def close(self):
self.fp.get_socket().close()
class SMB_login(TCP_Cache):
'''Brute-force SMB'''
usage_hints = (
"""%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt"""
""" -x ignore:fgrep='unknown user name or bad password'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [139]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('password_hash', "LM/NT hashes to test, at least one hash must be provided ('lm:nt' or ':nt' or 'lm:')"),
('domain', 'domain to test'),
)
available_options += TCP_Cache.available_options
class Response(Response_Base):
logformat = '%-8s %-4s %6s | %-34s | %5s | %s'
# ripped from medusa smbnt.c
error_map = {
0xffff: 'UNKNOWN_ERROR_CODE',
0x0000: 'STATUS_SUCCESS',
0x000d: 'STATUS_INVALID_PARAMETER',
0x005e: 'STATUS_NO_LOGON_SERVERS',
0x006d: 'STATUS_LOGON_FAILURE',
0x006e: 'STATUS_ACCOUNT_RESTRICTION',
0x006f: 'STATUS_INVALID_LOGON_HOURS',
0x0002: 'STATUS_INVALID_LOGON_HOURS (LM Authentication)',
0x0070: 'STATUS_INVALID_WORKSTATION',
0x0002: 'STATUS_INVALID_WORKSTATION (LM Authentication)',
0x0071: 'STATUS_PASSWORD_EXPIRED',
0x0072: 'STATUS_ACCOUNT_DISABLED',
0x015b: 'STATUS_LOGON_TYPE_NOT_GRANTED',
0x018d: 'STATUS_TRUSTED_RELATIONSHIP_FAILURE',
0x0193: 'STATUS_ACCOUNT_EXPIRED',
0x0002: 'STATUS_ACCOUNT_EXPIRED_OR_DISABLED (LM Authentication)',
0x0224: 'STATUS_PASSWORD_MUST_CHANGE',
0x0002: 'STATUS_PASSWORD_MUST_CHANGE (LM Authentication)',
0x0234: 'STATUS_ACCOUNT_LOCKED_OUT (No LM Authentication Code)',
0x0001: 'AS400_STATUS_LOGON_FAILURE',
0x0064: 'The machine you are logging onto is protected by an authentication firewall.',
}
def connect(self, host, port):
# if port == 445, impacket will use <host> instead of '*SMBSERVER' as the remote_name
fp = impacket_smb.SMB('*SMBSERVER', host, sess_port=int(port))
return SMB_Connection(fp)
def execute(self, host, port='139', user=None, password=None, password_hash=None, domain='', persistent='1'):
fp, _ = self.bind(host, port)
try:
if user is None:
fp.login('', '') # to get computer name
fp.login_standard('', '') # to get workgroup or domain (Primary Domain)
else:
if password is None:
lmhash, nthash = password_hash.split(':')
fp.login(user, '', domain, lmhash, nthash)
else:
fp.login(user, password, domain)
logger.debug('No error')
code, mesg = '0', '%s\\%s (%s)' % (fp.get_server_domain(), fp.get_server_name(), fp.get_server_os())
self.reset()
except impacket_smb.SessionError as e:
code = '%04x%04x' % (e.error_class, e.error_code)
error_class = e.error_classes.get(e.error_class, None) # -> ("ERRNT", nt_msgs)
if error_class:
class_str = error_class[0] # "ERRNT"
error_tuple = error_class[1].get(e.error_code, None) # -> ("STATUS_LOGON_FAILURE","Logon failure: unknown user name or bad password.") or None
if error_tuple:
mesg = '%s %s' % error_tuple
else:
mesg = '%s' % class_str
else:
mesg = self.error_map.get(e.error_code & 0x0000fffff, '')
if persistent == '0':
self.reset()
return self.Response(code, mesg)
class DCE_Connection(TCP_Connection):
def __init__(self, fp, smbt):
self.smbt = smbt
TCP_Connection.__init__(self, fp)
def close(self):
self.smbt.get_socket().close()
class SMB_lookupsid(TCP_Cache):
'''Brute-force SMB SID-lookup'''
usage_hints = (
'''%prog host=10.0.0.1 sid=S-1-5-21-1234567890-1234567890-1234567890 rid=RANGE0 0=int:500-2000 -x ignore:code=1''',
)
available_options = (
('host', 'target host'),
('port', 'target port [139]'),
('sid', 'SID to test'),
('rid', 'RID to test'),
('user', 'username to use if auth required'),
('password', 'password to use if auth required'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, user, password):
smbt = transport.SMBTransport(host, int(port), r'\lsarpc', user, password)
dce = dcerpc.DCERPC_v5(smbt)
dce.connect()
dce.bind(lsarpc.MSRPC_UUID_LSARPC)
fp = lsarpc.DCERPCLsarpc(dce)
return DCE_Connection(fp, smbt)
# http://msdn.microsoft.com/en-us/library/windows/desktop/hh448528%28v=vs.85%29.aspx
SID_NAME_USER = [0, 'User', 'Group', 'Domain', 'Alias', 'WellKnownGroup', 'DeletedAccount', 'Invalid', 'Unknown', 'Computer', 'Label']
def execute(self, host, port='139', user='', password='', sid=None, rid=None, persistent='1'):
fp, _ = self.bind(host, port, user, password)
if rid:
sid = '%s-%s' % (sid, rid)
op2 = fp.LsarOpenPolicy2('\\', access_mask=0x02000000)
res = fp.LsarLookupSids(op2['ContextHandle'], [sid])
if res['ErrorCode'] == 0:
code, names = 0, []
for d in res.formatDict():
if 'types' in d: # http://code.google.com/p/impacket/issues/detail?id=10
names.append(','.join('%s\\%s (%s)' % (d['domain'], n, self.SID_NAME_USER[t]) for n, t in zip(d['names'], d['types'])))
else:
names.append(','.join('%s\\%s' % (d['domain'], n) for n in d['names']))
else:
code, names = 1, ['unknown'] # STATUS_SOME_NOT_MAPPED
if persistent == '0':
self.reset()
return self.Response(code, ', '.join(names))
# }}}
# POP {{{
from poplib import POP3, POP3_SSL, error_proto as pop_error
class POP_Connection(TCP_Connection):
def close(self):
self.fp.quit()
class POP_login(TCP_Cache):
'''Brute-force POP3'''
usage_hints = (
'''%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:code=-ERR''',
)
available_options = (
('host', 'target host'),
('port', 'target port [110]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('ssl', 'use SSL [0|1]'),
('timeout', 'seconds to wait for a response [10]'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, ssl, timeout):
if ssl == '0':
if not port: port = 110
fp = POP3(host, int(port), timeout=int(timeout))
else:
if not port: port = 995
fp = POP3_SSL(host, int(port)) # timeout=int(timeout)) # no timeout option in python2
return POP_Connection(fp, fp.welcome)
def execute(self, host, port='', ssl='0', user=None, password=None, timeout='10', persistent='1'):
fp, resp = self.bind(host, port, ssl, timeout=timeout)
try:
if user is not None:
resp = fp.user(user)
if password is not None:
resp = fp.pass_(password)
logger.debug('No error: %s' % resp)
self.reset()
except pop_error as e:
logger.debug('pop_error: %s' % e)
resp = str(e)
if persistent == '0':
self.reset()
code, mesg = resp.split(' ', 1)
return self.Response(code, mesg)
class POP_passd:
'''Brute-force poppassd (http://netwinsite.com/poppassd/)'''
usage_hints = (
'''%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:code=500''',
)
available_options = (
('host', 'target host'),
('port', 'target port [106]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='106', user=None, password=None, timeout='10'):
fp = LineReceiver()
resp = fp.connect(host, int(port), int(timeout))
trace = resp + '\r\n'
try:
if user is not None:
cmd = 'USER %s' % user
resp = fp.sendcmd(cmd)
trace += '%s\r\n%s\r\n' % (cmd, resp)
if password is not None:
cmd = 'PASS %s' % password
resp = fp.sendcmd(cmd)
trace += '%s\r\n%s\r\n' % (cmd, resp)
except LineReceiver_Error as e:
resp = str(e)
logger.debug('LineReceiver_Error: %s' % resp)
trace += '%s\r\n%s\r\n' % (cmd, resp)
finally:
fp.close()
code, mesg = fp.parse(resp)
return self.Response(code, mesg, trace)
# }}}
# IMAP {{{
from imaplib import IMAP4, IMAP4_SSL
class IMAP_login:
'''Brute-force IMAP4'''
usage_hints = (
'''%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt''',
)
available_options = (
('host', 'target host'),
('port', 'target port [143]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('ssl', 'use SSL [0|1]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='', ssl='0', user=None, password=None):
if ssl == '0':
if not port: port = 143
fp = IMAP4(host, port)
else:
if not port: port = 993
fp = IMAP4_SSL(host, port)
code, resp = 0, fp.welcome
try:
if user is not None and password is not None:
r = fp.login(user, password)
resp = ', '.join(r[1])
except IMAP4.error as e:
logger.debug('imap_error: %s' % e)
code, resp = 1, str(e)
return self.Response(code, resp)
# }}}
# VMauthd {{{
from ssl import wrap_socket
class LineReceiver_Error(Exception): pass
class LineReceiver:
def connect(self, host, port, timeout, ssl=False):
self.sock = socket.create_connection((host, port), timeout)
banner = self.getresp()
if ssl:
self.sock = wrap_socket(self.sock)
return banner # welcome banner
def close(self):
self.sock.close()
def sendcmd(self, cmd):
self.sock.sendall(cmd + '\r\n')
return self.getresp()
def getresp(self):
resp = self.sock.recv(1024)
while not resp.endswith('\n'):
resp += self.sock.recv(1024)
resp = resp.rstrip()
code, _ = self.parse(resp)
if not code.isdigit():
raise Exception('Unexpected response: %s' % resp)
if code[0] not in ('1', '2', '3'):
raise LineReceiver_Error(resp)
return resp
def parse(self, resp):
i = resp.rfind('\n') + 1
code = resp[i:i+3]
mesg = resp[i+4:]
return code, mesg
class VMauthd_login(TCP_Cache):
'''Brute-force VMware Authentication Daemon'''
usage_hints = (
'''%prog host=10.0.0.1 user=root password=FILE0 0=passwords.txt''',
)
available_options = (
('host', 'target host'),
('port', 'target port [902]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('ssl', 'use SSL [1|0]'),
('timeout', 'seconds to wait for a response [10]'),
)
available_options += TCP_Cache.available_options
Response = Response_Base
def connect(self, host, port, ssl, timeout):
fp = LineReceiver()
banner = fp.connect(host, int(port), int(timeout), ssl != '0')
return TCP_Connection(fp, banner)
def execute(self, host, port='902', user=None, password=None, ssl='1', timeout='10', persistent='1'):
fp, resp = self.bind(host, port, ssl, timeout=timeout)
trace = resp + '\r\n'
try:
if user is not None:
cmd = 'USER %s' % user
resp = fp.sendcmd(cmd)
trace += '%s\r\n%s\r\n' % (cmd, resp)
if password is not None:
cmd = 'PASS %s' % password
resp = fp.sendcmd(cmd)
trace += '%s\r\n%s\r\n' % (cmd, resp)
except LineReceiver_Error as e:
resp = str(e)
logger.debug('LineReceiver_Error: %s' % resp)
trace += '%s\r\n%s\r\n' % (cmd, resp)
if persistent == '0':
self.reset()
code, mesg = fp.parse(resp)
return self.Response(code, mesg, trace)
# }}}
# MySQL {{{
try:
import _mysql
except ImportError:
warnings.append('mysql-python')
class MySQL_login:
'''Brute-force MySQL'''
usage_hints = (
"""%prog host=10.0.0.1 user=FILE0 password=FILE1 0=logins.txt 1=passwords.txt -x ignore:fgrep='Access denied for user'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [3306]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='3306', user='anony', password='', timeout='10'):
try:
fp = _mysql.connect(host=host, port=int(port), user=user, passwd=password, connect_timeout=int(timeout))
resp = '0', fp.get_server_info()
except _mysql.Error as resp:
logger.debug('MysqlError: %s' % resp)
code, mesg = resp
return self.Response(code, mesg)
class MySQL_query(TCP_Cache):
'''Brute-force MySQL queries'''
usage_hints = (
'''%prog host=10.0.0.1 user=root password=s3cr3t query="select length(load_file('/home/adam/FILE0'))" 0=files.txt -x ignore:size=0''',
)
available_options = (
('host', 'target host'),
('port', 'target port [3306]'),
('user', 'username to use'),
('password', 'password to use'),
('query', 'SQL query to execute'),
)
available_actions = ()
Response = Response_Base
def connect(self, host, port, user, password):
fp = _mysql.connect(host=host, port=int(port), user=user, passwd=password) # db=db
return TCP_Connection(fp)
def execute(self, host, port='3306', user='', password='', query='select @@version'):
fp, _ = self.bind(host, port, user, password)
fp.query(query)
rs = fp.store_result()
rows = rs.fetch_row(10, 0)
code, mesg = '0', '\n'.join(', '.join(map(str, r)) for r in filter(any, rows))
return self.Response(code, mesg)
# }}}
# MSSQL {{{
# I did not use pymssql because neither version 1.x nor 2.0.0b1_dev were multithreads safe (they all segfault)
try:
from impacket import tds
from impacket.tds import TDS_ERROR_TOKEN, TDS_LOGINACK_TOKEN
except ImportError:
warnings.append('impacket')
class MSSQL_login:
'''Brute-force MSSQL'''
usage_hints = (
"""%prog host=10.0.0.1 user=sa password=FILE0 0=passwords.txt -x ignore:fgrep='Login failed for user'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [1433]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('windows_auth', 'use Windows auth [0|1]'),
('domain', 'domain to test []'),
('password_hash', "LM/NT hashes to test ('lm:nt' or ':nt')"),
#('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='1433', user='', password='', windows_auth='0', domain='', password_hash=None): #, timeout='10'):
fp = tds.MSSQL(host, int(port))
fp.connect()
if windows_auth == '0':
r = fp.login(None, user, password, None, None, False)
else:
r = fp.login(None, user, password, domain, password_hash, True)
if not r:
key = fp.replies[TDS_ERROR_TOKEN][0]
code = key['Number']
mesg = key['MsgText'].decode('utf-16le')
else:
key = fp.replies[TDS_LOGINACK_TOKEN][0]
code = '0'
mesg = '%s (%d%d %d%d)' % (key['ProgName'].decode('utf-16le'), key['MajorVer'], key['MinorVer'], key['BuildNumHi'], key['BuildNumLow'])
fp.disconnect()
return self.Response(code, mesg)
# }}}
# Oracle {{{
try:
import cx_Oracle
except ImportError:
warnings.append('cx_Oracle')
class Oracle_login:
'''Brute-force Oracle'''
usage_hints = (
"""%prog host=10.0.0.1 sid=FILE0 0=sids.txt -x ignore:code=ORA-12505""",
"""%prog host=10.0.0.1 user=SYS password=FILE0 0=passwords.txt -x ignore:code=ORA-01017""",
)
available_options = (
('host', 'hostnames or subnets to target'),
('port', 'ports to target [1521]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('sid', 'sid or service names to test'),
)
available_actions = ()
class Response(Response_Base):
logformat = '%-9s %-4s %6s | %-34s | %5s | %s'
def execute(self, host, port='1521', user='', password='', sid=''):
dsn = cx_Oracle.makedsn(host, port, sid)
try:
fp = cx_Oracle.connect(user, password, dsn, threaded=True)
code, mesg = '0', fp.version
except cx_Oracle.DatabaseError as e:
code, mesg = e.args[0].message[:-1].split(': ', 1)
return self.Response(code, mesg)
# }}}
# PostgreSQL {{{
try:
import psycopg2
except ImportError:
warnings.append('psycopg')
class Pgsql_login:
'''Brute-force PostgreSQL'''
usage_hints = (
"""%prog host=10.0.0.1 user=postgres password=FILE0 0=passwords.txt -x ignore:fgrep='password authentication failed for user'""",
)
available_options = (
('host', 'target host'),
('port', 'target port [5432]'),
('user', 'usernames to test'),
('password', 'passwords to test'),
('database', 'databases to test [postgres]'),
('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port='5432', user=None, password=None, database='postgres', ssl='disable', timeout='10'):
try:
psycopg2.connect(host=host, port=int(port), user=user, password=password, database=database, sslmode=ssl, connect_timeout=int(timeout))
code, mesg = '0', 'OK'
except psycopg2.OperationalError as e:
logger.debug('OperationalError: %s' % e)
code, mesg = '1', str(e)[:-1]
return self.Response(code, mesg)
# }}}
# HTTP {{{
try:
import pycurl
except ImportError:
warnings.append('pycurl')
class Response_HTTP(Response_Base):
logformat = '%-4s %-13s %6s | %-32s | %5s | %s'
logheader = ('code', 'size:clen', 'time', 'candidate', 'num', 'mesg')
def __init__(self, code, response, trace=None, content_length=-1):
self.content_length = content_length
Response_Base.__init__(self, code, response, trace)
def compact(self):
return self.code, '%d:%d' % (self.size, self.content_length), '%.3f' % self.time
def __str__(self):
lines = re.findall('^(HTTP/.+)$', self.mesg, re.M)
if not lines:
return 'Unexpected HTTP response'
else:
return lines[-1]
def match_clen(self, val):
return match_range(self.content_length, val)
def match_fgrep(self, val):
return val in self.mesg
def match_egrep(self, val):
return re.search(val, self.mesg, re.M)
available_conditions = Response_Base.available_conditions
available_conditions += (
('clen', 'match Content-Length header (N or N-M or N- or -N)'),
)
class HTTP_fuzz(TCP_Cache):
'''Brute-force HTTP'''
usage_hints = [
"""%prog url=http://10.0.0.1/FILE0 0=paths.txt -x ignore:code=404 -x ignore,retry:code=500""",
"""%prog url=http://10.0.0.1/manager/html user_pass=COMBO00:COMBO01 0=combos.txt"""
""" -x ignore:code=401""",
"""%prog url=http://10.0.0.1/phpmyadmin/index.php method=POST"""
""" body='pma_username=root&pma_password=FILE0&server=1&lang=en' 0=passwords.txt follow=1"""
""" accept_cookie=1 -x ignore:fgrep='Cannot log in to the MySQL server'""",
]
available_options = (
('url', 'target url (scheme://host[:port]/path?query)'),
#('host', 'target host'),
#('port', 'target port'),
#('scheme', 'scheme [http | https]'),
#('path', 'web path [/]'),
#('query', 'query string'),
('body', 'body data'),
('header', 'use custom headers'),
('method', 'method to use [GET | POST | HEAD | ...]'),
('user_pass', 'username and password for HTTP authentication (user:pass)'),
('auth_type', 'type of HTTP authentication [basic | digest | ntlm]'),
('follow', 'follow any Location redirect [0|1]'),
('max_follow', 'redirection limit [5]'),
('accept_cookie', 'save received cookies to issue them in future requests [0|1]'),
('http_proxy', 'HTTP proxy to use (host:port)'),
('ssl_cert', 'client SSL certificate file (cert+key in PEM format)'),
('timeout_tcp', 'seconds to wait for a TCP handshake [10]'),
('timeout', 'seconds to wait for a HTTP response [20]'),
('before_urls', 'comma-separated URLs to query before the main request'),
('before_egrep', 'extract data from the before_urls response to place in the main request'),
('after_urls', 'comma-separated URLs to query after the main request'),
('max_mem', 'store no more than N bytes of request+response data in memory [-1 (unlimited)]'),
)
available_options += TCP_Cache.available_options
Response = Response_HTTP
def connect(self, host, port, scheme):
fp = pycurl.Curl()
fp.setopt(pycurl.SSL_VERIFYPEER, 0)
fp.setopt(pycurl.SSL_VERIFYHOST, 0)
fp.setopt(pycurl.HEADER, 1)
fp.setopt(pycurl.USERAGENT, 'Mozilla/5.0')
fp.setopt(pycurl.NOSIGNAL, 1)
return TCP_Connection(fp)
def execute(self, url=None, host=None, port='', scheme='http', path='/', params='', query='', fragment='', body='',
header='', method='GET', user_pass='', auth_type='basic',
follow='0', max_follow='5', accept_cookie='0', http_proxy='', ssl_cert='', timeout_tcp='10', timeout='20', persistent='1',
before_urls='', before_egrep='', after_urls='', max_mem='-1'):
if url:
scheme, host, path, params, query, fragment = urlparse(url)
if ':' in host:
host, port = host.split(':')
del url
fp, _ = self.bind(host, port, scheme)
fp.setopt(pycurl.FOLLOWLOCATION, int(follow))
fp.setopt(pycurl.MAXREDIRS, int(max_follow))
fp.setopt(pycurl.CONNECTTIMEOUT, int(timeout_tcp))
fp.setopt(pycurl.TIMEOUT, int(timeout))
fp.setopt(pycurl.PROXY, http_proxy)
def noop(buf): pass
fp.setopt(pycurl.WRITEFUNCTION, noop)
def debug_func(t, s):
if max_mem > 0 and trace.tell() > max_mem:
return 0
if t in (pycurl.INFOTYPE_HEADER_OUT, pycurl.INFOTYPE_DATA_OUT):
trace.write(s)
elif t in (pycurl.INFOTYPE_HEADER_IN, pycurl.INFOTYPE_DATA_IN):
trace.write(s)
response.write(s)
max_mem = int(max_mem)
response, trace = StringIO(), StringIO()
fp.setopt(pycurl.DEBUGFUNCTION, debug_func)
fp.setopt(pycurl.VERBOSE, 1)
if user_pass:
fp.setopt(pycurl.USERPWD, user_pass)
if auth_type == 'basic':
fp.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
elif auth_type == 'digest':
fp.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_DIGEST)
elif auth_type == 'ntlm':
fp.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_NTLM)
else:
raise NotImplementedError("Incorrect auth_type '%s'" % auth_type)
if ssl_cert:
fp.setopt(pycurl.SSLCERT, ssl_cert)
if accept_cookie == '1':
fp.setopt(pycurl.COOKIEFILE, '')
# warning: do not pass a Cookie: header into HTTPHEADER if using COOKIEFILE as it will
# produce requests with more than one Cookie: header
# and the server will process only one of them (eg. Apache only reads the last one)
def perform_fp(fp, method, url, header='', body=''):
#logger.debug('perform: %s' % url)
fp.setopt(pycurl.URL, url)
if method == 'GET':
fp.setopt(pycurl.HTTPGET, 1)
elif method == 'POST':
fp.setopt(pycurl.POST, 1)
fp.setopt(pycurl.POSTFIELDS, body)
elif method == 'HEAD':
fp.setopt(pycurl.NOBODY, 1)
else:
fp.setopt(pycurl.CUSTOMREQUEST, method)
headers = [h.strip('\r') for h in header.split('\n') if h]
fp.setopt(pycurl.HTTPHEADER, headers)
fp.perform()
if before_urls:
for before_url in before_urls.split(','):
perform_fp(fp, 'GET', before_url)
if before_egrep:
for be in before_egrep.split('|'):
mark, regex = be.split(':', 1)
val = re.search(regex, response.getvalue(), re.M).group(1)
header = header.replace(mark, val)
query = query.replace(mark, val)
body = body.replace(mark, val)
path = quote(path)
query = urlencode(parse_qsl(query, True))
body = urlencode(parse_qsl(body, True))
if port:
host = '%s:%s' % (host, port)
url = urlunparse((scheme, host, path, params, query, fragment))
perform_fp(fp, method, url, header, body)
if after_urls:
for after_url in after_urls.split(','):
perform_fp(fp, 'GET', after_url)
http_code = fp.getinfo(pycurl.HTTP_CODE)
content_length = fp.getinfo(pycurl.CONTENT_LENGTH_DOWNLOAD)
if persistent == '0':
self.reset()
return self.Response(http_code, response.getvalue(), trace.getvalue(), content_length)
# }}}
# VNC {{{
try:
from Crypto.Cipher import DES
except ImportError:
warnings.append('pycrypto')
class VNC_Error(Exception): pass
class VNC:
def connect(self, host, port, timeout):
self.fp = socket.create_connection((host, port), timeout=timeout)
resp = self.fp.recv(99) # banner
logger.debug('banner: %s' % repr(resp))
self.version = resp[:11].decode('ascii')
if len(resp) > 12:
raise VNC_Error('%s %s' % (self.version, resp[12:].decode('ascii', 'ignore')))
return self.version
def login(self, password):
logger.debug('Remote version: %s' % self.version)
major, minor = self.version[6], self.version[10]
if (major, minor) in [('3', '8'), ('4', '1')]:
proto = b'RFB 003.008\n'
elif (major, minor) == ('3', '7'):
proto = b'RFB 003.007\n'
else:
proto = b'RFB 003.003\n'
logger.debug('Client version: %s' % proto[:-1])
self.fp.sendall(proto)
sleep(0.5)
resp = self.fp.recv(99)
logger.debug('Security types supported: %s' % repr(resp))
if minor in ('7', '8'):
code = ord(resp[0:1])
if code == 0:
raise VNC_Error('Session setup failed: %s' % resp.decode('ascii', 'ignore'))
self.fp.sendall(b'\x02') # always use classic VNC authentication
resp = self.fp.recv(99)
else: # minor == '3':
code = ord(resp[3:4])
if code != 2:
raise VNC_Error('Session setup failed: %s' % resp.decode('ascii', 'ignore'))
resp = resp[-16:]
if len(resp) != 16:
raise VNC_Error('Unexpected challenge size (No authentication required? Unsupported authentication type?)')
logger.debug('challenge: %s' % repr(resp))
pw = password.ljust(8, '\x00')[:8] # make sure it is 8 chars long, zero padded
key = self.gen_key(pw)
logger.debug('key: %s' % repr(key))
des = DES.new(key, DES.MODE_ECB)
enc = des.encrypt(resp)
logger.debug('enc: %s' % repr(enc))
self.fp.sendall(enc)
resp = self.fp.recv(99)
logger.debug('resp: %s' % repr(resp))
code = ord(resp[3:4])
mesg = resp[8:].decode('ascii', 'ignore')
if code == 1:
return code, mesg or 'Authentication failure'
elif code == 0:
return code, mesg or 'OK'
else:
raise VNC_Error('Unknown response: %s (code: %s)' % (repr(resp), code))
def gen_key(self, key):
newkey = []
for ki in range(len(key)):
bsrc = ord(key[ki])
btgt = 0
for i in range(8):
if bsrc & (1 << i):
btgt = btgt | (1 << 7-i)
newkey.append(btgt)
if version_info[0] == 2:
return ''.join(chr(c) for c in newkey)
else:
return bytes(newkey)
class VNC_login:
'''Brute-force VNC'''
usage_hints = (
"""%prog host=10.0.0.1 password=FILE0 0=passwords.txt -t 1 -x retry:fgrep!='Authentication failure' --max-retries -1 -x quit:code=0""",
)
available_options = (
('host', 'target host'),
('port', 'target port [5900]'),
('password', 'passwords to test'),
('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port=None, password=None, timeout='10'):
v = VNC()
try:
code, mesg = 0, v.connect(host, int(port or 5900), int(timeout))
if password is not None:
code, mesg = v.login(password)
except VNC_Error as e:
logger.debug('VNC_Error: %s' % e)
code, mesg = 2, str(e)
return self.Response(code, mesg)
# }}}
# DNS {{{
try:
import dns.rdatatype
import dns.message
import dns.query
import dns.reversename
except ImportError:
warnings.append('dnspython')
def dns_query(server, timeout, protocol, qname, qtype, qclass):
request = dns.message.make_query(qname, qtype, qclass)
if protocol == 'tcp':
response = dns.query.tcp(request, server, timeout=timeout, one_rr_per_rrset=True)
else:
response = dns.query.udp(request, server, timeout=timeout, one_rr_per_rrset=True)
if response.flags & dns.flags.TC:
response = dns.query.tcp(request, server, timeout=timeout, one_rr_per_rrset=True)
return response
def generate_tld():
from itertools import product
from string import ascii_lowercase
gtld = [
'aero', 'arpa', 'asia', 'biz', 'cat', 'com', 'coop', 'edu',
'gov', 'info', 'int', 'jobs', 'mil', 'mobi', 'museum', 'name',
'net', 'org', 'pro', 'tel', 'travel']
cctld = [''.join(i) for i in product(*[ascii_lowercase]*2)]
tld = gtld + cctld
return tld, len(tld)
def generate_srv():
common = [
'_gc._tcp', '_kerberos._tcp', '_kerberos._udp', '_ldap._tcp',
'_test._tcp', '_sips._tcp', '_sip._udp', '_sip._tcp', '_aix._tcp', '_aix._udp',
'_finger._tcp', '_ftp._tcp', '_http._tcp', '_nntp._tcp', '_telnet._tcp',
'_whois._tcp', '_h323cs._tcp', '_h323cs._udp', '_h323be._tcp', '_h323be._udp',
'_h323ls._tcp', '_h323ls._udp', '_sipinternal._tcp', '_sipinternaltls._tcp',
'_sip._tls', '_sipfederationtls._tcp', '_jabber._tcp', '_xmpp-server._tcp', '_xmpp-client._tcp',
'_imap.tcp', '_certificates._tcp', '_crls._tcp', '_pgpkeys._tcp', '_pgprevokations._tcp',
'_cmp._tcp', '_svcp._tcp', '_crl._tcp', '_ocsp._tcp', '_PKIXREP._tcp',
'_smtp._tcp', '_hkp._tcp', '_hkps._tcp', '_jabber._udp', '_xmpp-server._udp',
'_xmpp-client._udp', '_jabber-client._tcp', '_jabber-client._udp',
'_adsp._domainkey', '_policy._domainkey', '_domainkey', '_ldap._tcp.dc._msdcs', '_ldap._udp.dc._msdcs']
def distro():
import os
import re
files = ['/usr/share/nmap/nmap-protocols', '/usr/share/nmap/nmap-services', '/etc/protocols', '/etc/services']
ret = []
for f in files:
if not os.path.isfile(f):
logger.warn("File '%s' is missing, there will be less records to test" % f)
continue
for line in open(f):
match = re.match(r'([a-zA-Z0-9]+)\s', line)
if not match: continue
for w in re.split(r'[^a-z0-9]', match.group(1).strip().lower()):
ret.extend(['_%s.%s' % (w, i) for i in ('_tcp', '_udp')])
return ret
srv = set(common + distro())
return srv, len(srv)
class HostInfo:
def __init__(self):
self.name = set()
self.ip = set()
self.alias = set()
def __str__(self):
line = ''
if self.name:
line = ' '.join(self.name)
if self.ip:
if line: line += ' / '
line += ' '.join(map(str, self.ip))
if self.alias:
if line: line += ' / '
line += ' '.join(self.alias)
return line
class Controller_DNS(Controller):
records = defaultdict(list)
hostmap = defaultdict(HostInfo)
# show_final {{{
def show_final(self):
''' Expected output:
Records -----
ftp.example.com. IN A 10.0.1.1
www.example.com. IN A 10.0.1.1
prod.example.com. IN CNAME www.example.com.
ipv6.example.com. IN AAAA dead:beef::
dev.example.com. IN A 10.0.1.2
svn.example.com. IN A 10.0.2.1
websrv1.example.com. IN CNAME prod.example.com.
blog.example.com. IN CNAME example.wordpress.com.
'''
print('Records ' + '-'*42)
for name, infos in sorted(self.records.items()):
for qclass, qtype, rdata in infos:
print('%34s %4s %-7s %s' % (name, qclass, qtype, rdata))
''' Expected output:
Hostmap ------
ipv6.example.com dead:beef::
ftp.example.com 10.0.1.1
www.example.com 10.0.1.1
prod.example.com
websrv1.example.com
dev.example.com 10.0.1.2
svn.example.com 10.0.2.1
example.wordpress.com ?
blog.example.com
Domains ---------------------------
example.com 8
Networks --------------------------
dead:beef::
10.0.1.x
10.0.2.1
'''
ipmap = defaultdict(HostInfo)
noips = defaultdict(list)
'''
hostmap = {
'www.example.com': {'ip': ['10.0.1.1'], 'alias': ['prod.example.com']},
'ftp.example.com': {'ip': ['10.0.1.1'], 'alias': []},
'prod.example.com': {'ip': [], 'alias': ['websrv1.example.com']},
'ipv6.example.com': {'ip': ['dead:beef::'], 'alias': []},
'dev.example.com': {'ip': ['10.0.1.2'], 'alias': []},
'example.wordpress.com': {'ip': [], 'alias': ['blog.example.com']},
ipmap = {'10.0.1.1': {'name': ['www.example.com', 'ftp.example.com'], 'alias': ['prod.example.com', 'websrv1.example.com']}, ...
noips = {'example.wordpress.com': ['blog.example.com'],
'''
for name, hinfo in self.hostmap.items():
for ip in hinfo.ip:
ip = IP(ip)
ipmap[ip].name.add(name)
ipmap[ip].alias.update(hinfo.alias)
for name, hinfo in self.hostmap.items():
if not hinfo.ip and hinfo.alias:
found = False
for ip, v in ipmap.items():
if name in v.alias:
for alias in hinfo.alias:
ipmap[ip].alias.add(alias)
found = True
if not found: # orphan CNAME hostnames (with no IP address) may be still valid virtual hosts
noips[name].extend(hinfo.alias)
print('Hostmap ' + '-'*42)
for ip, hinfo in sorted(ipmap.items()):
for name in hinfo.name:
print('%34s %s' % (name, ip))
for alias in hinfo.alias:
print('%34s' % alias)
for k, v in noips.items():
print('%34s ?' % k)
for alias in v:
print('%34s' % alias)
print('Domains ' + '-'*42)
domains = {}
for ip, hinfo in ipmap.items():
for name in hinfo.name.union(hinfo.alias):
if name.count('.') > 1:
i = 1
else:
i = 0
d = '.'.join(name.split('.')[i:])
if d not in domains: domains[d] = 0
domains[d] += 1
for domain, count in sorted(domains.items(), key=lambda a:a[0].split('.')[-1::-1]):
print('%34s %d' % (domain, count))
print('Networks ' + '-'*41)
nets = {}
for ip in set(ipmap):
if not ip.version() == 4:
nets[ip] = [ip]
else:
n = ip.make_net('255.255.255.0')
if n not in nets: nets[n] = []
nets[n].append(ip)
for net, ips in sorted(nets.items()):
if len(ips) == 1:
print(' '*34 + ' %s' % ips[0])
else:
print(' '*34 + ' %s.x' % '.'.join(str(net).split('.')[:-1]))
# }}}
def push_final(self, resp):
if hasattr(resp, 'rrs'):
for rr in resp.rrs:
name, qclass, qtype, data = rr
info = (qclass, qtype, data)
if info not in self.records[name]:
self.records[name].append(info)
if not qclass == 'IN':
continue
if qtype == 'PTR':
data = data[:-1]
self.hostmap[data].ip.add(name)
else:
if qtype in ('A', 'AAAA'):
name = name[:-1]
self.hostmap[name].ip.add(data)
elif qtype == 'CNAME':
name, data = name[:-1], data[:-1]
self.hostmap[data].alias.add(name)
class DNS_reverse:
'''Reverse lookup subnets'''
usage_hints = [
"""%prog host=NET0 0=192.168.0.0/24 -x ignore:code=3""",
"""%prog host=NET0 0=216.239.32.0-216.239.47.255,8.8.8.0/24 -x ignore:code=3 -x ignore:fgrep!=google.com -x ignore:fgrep=216-239-""",
]
available_options = (
('host', 'IP addresses to reverse lookup'),
('server', 'name server to query (directly asking a zone authoritative NS may return more results) [8.8.8.8]'),
('timeout', 'seconds to wait for a response [5]'),
('protocol', 'send queries over udp or tcp [udp]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, server='8.8.8.8', timeout='5', protocol='udp'):
response = dns_query(server, int(timeout), protocol, dns.reversename.from_address(host), qtype='PTR', qclass='IN')
code = response.rcode()
status = dns.rcode.to_text(code)
rrs = [[host, c, t, d] for _, _, c, t, d in [rr.to_text().split(' ', 4) for rr in response.answer]]
mesg = '%s %s' % (status, ''.join('[%s]' % ' '.join(rr) for rr in rrs))
resp = self.Response(code, mesg)
resp.rrs = rrs
return resp
class DNS_forward:
'''Forward lookup names'''
usage_hints = [
"""%prog name=FILE0.google.com 0=names.txt -x ignore:code=3""",
"""%prog name=google.MOD0 0=TLD -x ignore:code=3""",
"""%prog name=MOD0.microsoft.com 0=SRV qtype=SRV -x ignore:code=3""",
]
available_options = (
('name', 'domain names to lookup'),
('server', 'name server to query (directly asking the zone authoritative NS may return more results) [8.8.8.8]'),
('timeout', 'seconds to wait for a response [5]'),
('protocol', 'send queries over udp or tcp [udp]'),
('qtype', 'type to query [ANY]'),
('qclass', 'class to query [IN]'),
)
available_actions = ()
available_keys = {
'TLD': generate_tld,
'SRV': generate_srv,
}
Response = Response_Base
def execute(self, name, server='8.8.8.8', timeout='5', protocol='udp', qtype='ANY', qclass='IN'):
response = dns_query(server, int(timeout), protocol, name, qtype=qtype, qclass=qclass)
code = response.rcode()
status = dns.rcode.to_text(code)
rrs = [[n, c, t, d] for n, _, c, t, d in [rr.to_text().split(' ', 4) for rr in response.answer + response.additional + response.authority]]
mesg = '%s %s' % (status, ''.join('[%s]' % ' '.join(rr) for rr in rrs))
resp = self.Response(code, mesg)
resp.rrs = rrs
return resp
# }}}
# SNMP {{{
try:
from pysnmp.entity.rfc3413.oneliner import cmdgen
except ImportError:
warnings.append('pysnmp')
class SNMP_login:
'''Brute-force SNMP v1/2/3'''
usage_hints = (
"""%prog host=10.0.0.1 version=2 community=FILE0 1=names.txt -x ignore:mesg='No SNMP response received before timeout'""",
"""%prog host=10.0.0.1 version=3 user=FILE0 0=logins.txt -x ignore:mesg=unknownUserName""",
"""%prog host=10.0.0.1 version=3 user=myuser auth_key=FILE0 0=passwords.txt -x ignore:mesg=wrongDigest""",
)
available_options = (
('host', 'target host'),
('port', 'target port [161]'),
('version', 'SNMP version to use [2|3|1]'),
#('security_name', 'SNMP v1/v2 username, for most purposes it can be any arbitrary string [test-agent]'),
('community', 'SNMPv1/2c community names to test [public]'),
('user', 'SNMPv3 usernames to test [myuser]'),
('auth_key', 'SNMPv3 pass-phrases to test [my_password]'),
#('priv_key', 'SNMP v3 secret key for encryption'), # see http://pysnmp.sourceforge.net/docs/4.x/index.html#UsmUserData
#('auth_protocol', ''),
#('priv_protocol', ''),
('timeout', 'seconds to wait for a response [1]'),
('retries', 'number of successive request retries [2]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port=None, version='2', community='public', user='myuser', auth_key='my_password', timeout='1', retries='2'):
if version in ('1', '2'):
security_model = cmdgen.CommunityData('test-agent', community, 0 if version == '1' else 1)
elif version == '3':
security_model = cmdgen.UsmUserData(user, auth_key) # , priv_key)
if len(auth_key) < 8:
return self.Response('1', 'SNMPv3 requires passphrases to be at least 8 characters long')
else:
raise NotImplementedError("Incorrect SNMP version '%s'" % version)
errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator().getCmd(
security_model,
cmdgen.UdpTransportTarget((host, int(port or 161)), timeout=int(timeout), retries=int(retries)),
(1,3,6,1,2,1,1,1,0)
)
code = '%d-%d' % (errorStatus, errorIndex)
if not errorIndication:
mesg = '%s' % varBinds
else:
mesg = '%s' % errorIndication
return self.Response(code, mesg)
# }}}
# Unzip {{{
if not which('unzip'):
warnings.append('unzip')
class Unzip_pass:
'''Brute-force the password of encrypted ZIP files'''
usage_hints = [
"""%prog zipfile=path/to/file.zip password=FILE0 0=passwords.txt -x ignore:code!=0""",
]
available_options = (
('zipfile', 'ZIP files to test'),
('password', 'passwords to test'),
)
available_actions = ()
Response = Response_Base
def execute(self, zipfile, password):
zipfile = os.path.abspath(zipfile)
cmd = ['unzip', '-t', '-q', '-P', password, zipfile]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.stdout.read()
err = p.stderr.read()
code = p.wait()
mesg = repr(out.strip())[1:-1]
trace = '[out]\n%s\n[err]\n%s' % (out, err)
return self.Response(code, mesg, trace)
# }}}
# Keystore {{{
if not which('keytool'):
warnings.append('java')
class Keystore_pass:
'''Brute-force the password of Java keystore files'''
usage_hints = [
"""%prog keystore=path/to/keystore.jks password=FILE0 0=passwords.txt -x ignore:fgrep='password was incorrect'""",
]
available_options = (
('keystore', 'keystore files to test'),
('password', 'passwords to test'),
('storetype', 'type of keystore to test'),
)
available_actions = ()
Response = Response_Base
def execute(self, keystore, password, storetype='jks'):
keystore = os.path.abspath(keystore)
cmd = ['keytool', '-list', '-keystore', keystore, '-storepass', password, '-storetype', storetype]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out = p.stdout.read()
err = p.stderr.read()
code = p.wait()
mesg = repr(out.strip())[1:-1]
trace = '[out]\n%s\n[err]\n%s' % (out, err)
return self.Response(code, mesg, trace)
# }}}
# Umbraco {{{
import hmac
class Umbraco_crack:
'''Crack Umbraco HMAC-SHA1 password hashes'''
usage_hints = (
"""%prog hashlist=@umbraco_users.pw password=FILE0 0=rockyou.txt""",
)
available_options = (
('hashlist', 'hashes to crack'),
('password', 'password to test'),
)
available_actions = ()
Response = Response_Base
def execute(self, password, hashlist):
p = password.encode('utf-16-le')
h = b64encode(hmac.new(p, p, digestmod=hashlib.sha1).digest())
if h not in hashlist:
code, mesg = 1, 'fail'
else:
cracked = [line.rstrip() for line in hashlist.split('\n') if h in line]
code, mesg = 0, ' '.join(cracked)
return self.Response(code, mesg)
# }}}
# TCP Fuzz {{{
class TCP_fuzz:
'''Fuzz TCP services'''
usage_hints = (
'''%prog host=10.0.0.1 data=RANGE0 0=hex:0x00-0xffffff''',
)
available_options = (
('host', 'target host'),
('port', 'target port'),
('timeout', 'seconds to wait for a response [10]'),
)
available_actions = ()
Response = Response_Base
def execute(self, host, port, data='', timeout='2'):
fp = socket.create_connection((host, port), int(timeout))
fp.send(data.decode('hex'))
resp = fp.recv(1024)
fp.close()
code = 0
mesg = resp.encode('hex')
return self.Response(code, mesg)
# }}}
# Dummy Test {{{
class Dummy_test:
'''Testing module'''
usage_hints = (
"""%prog data=RANGE0 0=hex:0x00-0xffff""",
"""%prog data=PROG0 0='seq 0 80'""",
"""%prog data=PROG0 0='mp64.bin -i ?l?l?l',$(mp64.bin --combination -i ?l?l?l)""",
)
available_options = (
('data', 'data to test'),
)
available_actions = ()
Response = Response_Base
def execute(self, data):
code = 0
mesg = data
#sleep(.01)
return self.Response(code, mesg)
# }}}
# modules {{{
modules = [
('ftp_login', (Controller, FTP_login)),
('ssh_login', (Controller, SSH_login)),
('telnet_login', (Controller, Telnet_login)),
('smtp_login', (Controller, SMTP_login)),
('smtp_vrfy', (Controller, SMTP_vrfy)),
('smtp_rcpt', (Controller, SMTP_rcpt)),
('finger_lookup', (Controller_Finger, Finger_lookup)),
('http_fuzz', (Controller, HTTP_fuzz)),
('pop_login', (Controller, POP_login)),
('pop_passd', (Controller, POP_passd)),
('imap_login', (Controller, IMAP_login)),
('ldap_login', (Controller, LDAP_login)),
('smb_login', (Controller, SMB_login)),
('smb_lookupsid', (Controller, SMB_lookupsid)),
('vmauthd_login', (Controller, VMauthd_login)),
('mssql_login', (Controller, MSSQL_login)),
('oracle_login', (Controller, Oracle_login)),
('mysql_login', (Controller, MySQL_login)),
('mysql_query', (Controller, MySQL_query)),
#'rdp_login',
('pgsql_login', (Controller, Pgsql_login)),
('vnc_login', (Controller, VNC_login)),
('dns_forward', (Controller_DNS, DNS_forward)),
('dns_reverse', (Controller_DNS, DNS_reverse)),
('snmp_login', (Controller, SNMP_login)),
('unzip_pass', (Controller, Unzip_pass)),
('keystore_pass', (Controller, Keystore_pass)),
('umbraco_crack', (Controller, Umbraco_crack)),
('tcp_fuzz', (Controller, TCP_fuzz)),
('dummy_test', (Controller, Dummy_test)),
]
dependencies = {
'paramiko': [('ssh_login',), 'http://www.lag.net/paramiko/', '1.7.7.1'],
'pycurl': [('http_fuzz',), 'http://pycurl.sourceforge.net/', '7.19.0'],
'openldap': [('ldap_login',), 'http://www.openldap.org/', '2.4.24'],
'impacket': [('smb_login','smb_lookupsid','mssql_login'), 'http://oss.coresecurity.com/projects/impacket.html', 'svn#765'],
'cx_Oracle': [('oracle_login',), 'http://cx-oracle.sourceforge.net/', '5.1.1'],
'mysql-python': [('mysql_login',), 'http://sourceforge.net/projects/mysql-python/', '1.2.3'],
'psycopg': [('pgsql_login',), 'http://initd.org/psycopg/', '2.4.5'],
'pycrypto': [('vnc_login',), 'http://www.dlitz.net/software/pycrypto/', '2.3'],
'dnspython': [('dns_reverse', 'dns_forward'), 'http://www.dnspython.org/', '1.10.0'],
'IPy': [('dns_reverse', 'dns_forward'), 'https://github.com/haypo/python-ipy', '0.75'],
'pysnmp': [('snmp_login',), 'http://pysnmp.sf.net/', '4.2.1'],
'unzip': [('unzip_pass',), 'http://www.info-zip.org/', '6.0'],
'java': [('keystore_pass',), 'http://www.oracle.com/technetwork/java/javase/', '6'],
'python': [('ftp_login',), 'http://www.python.org/', '2.7'],
}
# }}}
# main {{{
if __name__ == '__main__':
from sys import argv
from os.path import basename
def show_usage():
print(__banner__)
print('''Usage: patator.py module --help
Available modules:
%s''' % '\n'.join(' + %-13s : %s' % (k, v[1].__doc__) for k, v in modules))
exit(2)
available = dict(modules)
name = basename(argv[0]).lower()
if name not in available:
if len(argv) == 1:
show_usage()
name = basename(argv[1]).lower()
if name not in available:
show_usage()
argv = argv[1:]
# dependencies
abort = False
for w in set(warnings):
mods, url, ver = dependencies[w]
if name in mods:
print('ERROR: %s %s (%s) is required to run %s.' % (w, ver, url, name))
abort = True
if abort:
print('Please read the README inside for more information.')
exit(3)
# start
ctrl, module = available[name]
powder = ctrl(module, [name] + argv[1:])
powder.fire()
# }}}
# vim: ts=2 sw=2 sts=2 et fdm=marker bg=dark
| Python |
"""
Example job for the process pool
"""
import datetime
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.plugin import IPlugin
from twisted.python import usage
from zope.interface import implements
from fjork import ifjork
from fjork import protocols
class Options(usage.Options):
optParameters = [["port", "p", 1235, "The port number to listen on."]]
class ExampleJob(object):
implements(ifjork.IFjork)
def fjork(self, *args, **kwargs):
print "ExampleJob: fjorking..."
print "args:", args
print "kwargs:", kwargs
return "<p>How are you today? (%s)</p>"%(datetime.datetime.now(),)
class ExampleJobServiceMaker(object):
implements(IPlugin, IServiceMaker)
tapname = "fjorkex"
description = "An example fjork"
options = Options
def makeService(self, options):
"""
Construct a TCPServer from a factory defined in myproject.
"""
print "Fjork is ready!"
return internet.TCPServer(int(options["port"]),
protocols.FjorkClientFactory(ExampleJob))
job = ExampleJobServiceMaker()
| Python |
"""
Example job for the process pool
"""
from twisted.application.service import IServiceMaker
#from twisted.application import internet
from twisted.plugin import IPlugin
from twisted.python import usage
from zope.interface import implements
from fjork import ifjork
#from fjork import pool
#from fjork import protocols
from fjork import server
class Options(usage.Options):
optParameters = [["port", "p", None, "The port number to listen on."]]
class FjorkServiceMaker(object):
implements(IPlugin, IServiceMaker, ifjork.IFjorkService)
tapname = "fjork"
description = "Fjork Service"
options = Options
def makeService(self, options):
"""
Construct a TCPServer from a factory defined in myproject.
"""
from fjork import settings
settings.load()
port = options["port"]
if port is None:
port = settings.PORT
port = int(port)
return server.FjorkServer(port)
fjork = FjorkServiceMaker()
| Python |
"""
Example job for the process pool
"""
import datetime
from twisted.application.service import IServiceMaker
from twisted.application import internet
from twisted.plugin import IPlugin
from twisted.python import usage
from zope.interface import implements
from fjork import ifjork
from fjork import protocols
class Options(usage.Options):
optParameters = [["port", "p", 1235, "The port number to listen on."]]
class ExampleJob(object):
implements(ifjork.IFjork)
def fjork(self, *args, **kwargs):
print "ExampleJob: fjorking..."
print "args:", args
print "kwargs:", kwargs
return "<p>As of (%s) I'm doing fine!</p>"%(datetime.datetime.now(),)
class ExampleJobServiceMaker(object):
implements(IPlugin, IServiceMaker)
tapname = "fjorkex2"
description = "An example fjork"
options = Options
def makeService(self, options):
"""
Construct a TCPServer from a factory defined in myproject.
"""
print "Fjork is ready!"
return internet.TCPServer(int(options["port"]),
protocols.FjorkClientFactory(ExampleJob))
job = ExampleJobServiceMaker()
| Python |
#-*- test-case-name: fjork.test.test_settings -*-
"""
The settings.py module loads a yaml/json document
which is used as a configuration file
for the fjork service.
Between the ---- markers is an example
of a valid yaml file:
-----------------------------------
# this is a comment
host: localhost
port: 8483
webwares:
- /tmp/tomato_9000
session_options: {
expires: 60,
type: MEMCACHE
}
-----------------------------------
"""
import exceptions
import os
import sys
from twisted.python import filepath
import yaml
FJORK_ROOT=filepath.FilePath(__file__).parent().parent()
DEBUG=False
HOSTNAME=None
PORT=None
POOL=None
WEBKIT = False
TEST_BIN = FJORK_ROOT.child("bin").child("fjorkChild.py"),
TEMPLATE_DIR = FJORK_ROOT.child("templates").path,
class FjorkSettingsError(exceptions.Exception):
"""Configuration file missing or unable to load all required settings"""
def load(path=None):
if not path:
path = os.path.join(os.curdir, "fjork.conf")
if not os.path.exists(path):
raise FjorkSettingsError("Missing config file: %s"%(path,))
config_file = open(path, "r")
config = yaml.safe_load(config_file.read())
settings = {}
for key,value in config.iteritems():
setting = key.upper()
settings[setting] = value
print "settings:", settings
globals().update(settings)
return settings
load()
| Python |
import collections
from timeit import default_timer
from twisted.python import log
from fjork import settings
def logFunctionTime(function):
if settings.DEBUG:
def timedFunction(*args, **kwargs):
start = default_timer()
result = function(*args, **kwargs)
end = default_timer() - start
log.msg(
'%s.%s executed in %f seconds' % (
function.__module__, function.__name__, end
)
)
return result
return timedFunction
else:
return function
def logMethodTime(method):
if settings.DEBUG:
def timedMethod(self, *args, **kwargs):
start = default_timer()
result = method(self, *args, **kwargs)
end = default_timer() - start
log.msg(
'%s.%s.%s executed in %f seconds' % (
method.__module__,
self.__class__.__name__,
method.__name__,
end
)
)
return result
return timedMethod
else:
return method
def roundrobin(*iterables):
pending = collections.deque(iter(i) for i in iterables)
while pending:
task = pending.popleft()
try:
yield task.next()
except StopIteration:
continue
pending.append(task)
| Python |
#-*- test-case-name: fjork.test.test_server -*-
"""
Defines the Fjork Server
"""
from twisted.application import internet, service
from twisted.internet import defer, reactor
from twisted.python import log
from twisted.web import server
from fjork import pool
from fjork import settings
from fjork.web import Root
class FjorkServer(service.MultiService):
def __init__(self, port):
self.pool = pool.Pool()
service.MultiService.__init__(self)
webServerFactory = server.Site(Root(self.pool))
webServer = internet.TCPServer(port, webServerFactory)
webServer.setName("TooBusyBeingAwesome")
webServer.setServiceParent(self)
def _cbProcessPoolStarted(self, result):
log.msg("Fjork is ready for eBusiness")
service.MultiService.startService(self)
return result
def _ebProcessPoolError(self, failure):
log.err("failure starting service:", failure)
return failure
def startService(self):
log.msg("starting services:")
self.pool.setProcesses(settings.POOL)
d = defer.Deferred()
d.addCallback(self._cbProcessPoolStarted)
d.addErrback(self._ebProcessPoolError)
reactor.callWhenRunning(self.pool.start, d)
return d
def stopService(self):
print "Shutting down pool:"
self.pool.shutdown()
print "Shutting down service:"
return service.MultiService.stopService(self)
| Python |
# __init__.py
| Python |
# __init__.py
| Python |
#-*- test-case-name: fjork.test.test_pool -*-
"""pool.py
Queues and runs requests through the pool
"""
import os
from twisted.internet import defer
from twisted.internet import error, reactor
from twisted.python import log
from zope import interface
from fjork import ifjork
from fjork import protocols
from fjork import settings
class Pool(object):
interface.implements(ifjork.IPool)
def __init__(self):
self.running = {}
self.ready = []
self.queuedRequests = []
self.maxRequests = 0
self.processes = {}
def setProcesses(self, processes):
log.msg("setting up processes:", processes)
self.processes = processes
self.maxRequests = len(self.processes)
for address in self.processes.keys():
self.ready.append(address)
def queue(self, d, request, path):
log.msg("queuing:", d, request, path)
self.queuedRequests.append((d, request, path))
if len(self.running) < self.maxRequests:
log.msg("starting processing ...")
self.process(self.ready.pop())
def process(self, address):
d, request, path = self.queuedRequests.pop()
log.msg("processing:", d, request, path)
nd = defer.Deferred()
nd.addCallback(self.processCompleted, address)
nd.addErrback(self.processFailed)
nd.chainDeferred(d)
self.running[address] = (nd, request, path)
if settings.WEBKIT is True:
factory = protocols.WebkitServerFactory(nd, request)
else:
factory = protocols.FjorkServerFactory(nd, request)
log.msg("address:", address)
host = self.processes[address]["host"]
port = self.processes[address]["port"]
log.msg("host:", host, "port:", port)
reactor.connectTCP(host, port, factory)
log.msg("finished connectTCP!")
def processCompleted(self, response, address):
log.msg("pool:", "processCompleted:", response)
del self.running[address]
self.ready.append(address)
while self.queuedRequests and self.ready:
self.process(self.ready.pop())
return response
def processFailed(self, failure):
log.err("pool.processFailed - failure:", failure)
return failure
def shutdown(self):
for address, processDescription in self.processes.items():
process = processDescription["process"]
try:
process.signalProcess(15) # SIGTERM should allow process to terminate nicely.
except error.ProcessExitedAlready, e:
log.msg("Process exited already: %s"%(e,))
def _cbProcessReady(self, address):
log.msg("process %s is ready!"%(address,))
return address
def _ebProcessError(self, failure):
log.err("process failed: %s"%(str(failure),))
return failure
def start(self, startServiceDeferred):
log.msg("starting processes...")
dl = []
for processName, processDescription in self.processes.iteritems():
log.msg("new process:", processName, processDescription)
d = defer.Deferred()
d.addCallback(self._cbProcessReady)
d.addErrback(self._ebProcessError)
dl.append(d)
address = "%s:%s"%(processDescription["host"], processDescription["port"])
p = protocols.FjorkProcessProtocol(address, d)
args = [processDescription["executable"],
]
args.extend(processDescription["args"])
log.msg("process %s starting: %s"%(processName, args))
process = reactor.spawnProcess(p,
processDescription["executable"],
args,
os.environ,
processDescription.get("path", None) and processDescription["path"] or settings.FJORK_ROOT.path,
)
self.processes[processName]["process"] = process
dl = defer.DeferredList(dl)
dl.addCallback(
# finally start the service
self.connect,
self.processes,
startServiceDeferred
)
return dl
def connect(self, result, processAddresses, startServiceDeferred):
startServiceDeferred.callback(result)
| Python |
#-*- test-case-name: fjork.test.test_web -*-
#import urlparse
#import simplejson as json
from twisted.python import log
from twisted.internet import defer
from twisted.web import http, resource, server, static
from twisted.web import proxy
from fjork import settings
from fjork import utils
staticResource = static.File(
settings.FJORK_ROOT.child('fjork').child('static').path
)
class Root(resource.Resource):
@utils.logMethodTime
def __init__(self, pool):
resource.Resource.__init__(self)
self.pool = pool
self.putChild('static', staticResource)
@utils.logMethodTime
def getChild(self, path, request):
log.msg("getChild:", path, request)
if ".psp" in path:
return proxy.ReverseProxyResource("localhost", 8080, "/" + path)
if path == "":
return self
return resource.Resource.getChild(self, path, request)
def _cbOk(self, content, request):
log.msg("web._cbOk:", content, request)
request.setResponseCode(http.OK)
if settings.WEBKIT is True:
index = content.find("<html>")
request.write(content[index:])
else:
request.write(
"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Fjork</title>
</head>
<body>
%s
</body>
</html>"""%(content)
)
request.finish()
def _cbErr(self, failure, request):
log.err("web._cbErr: %s"%(failure,))
request.setResponseCode(http.INTERNAL_SERVER_ERROR)
@utils.logMethodTime
def render_GET(self, request):
log.msg("render_GET:")
d = defer.Deferred()
# this deferred will be called back if the other side disconnects
# d = request.notifyFinish()
self.pool.queue(d, request, "/")
d.addCallback(self._cbOk, request)
d.addErrback(self._cbErr, request)
return server.NOT_DONE_YET
| Python |
"""
Defines Fjork interfaces
"""
from zope import interface
class IFjorkClientProtocol(interface.Interface):
"""
Basic line receiver that handles a few simple messages
"""
class IFjorkClientFactory(interface.Interface):
"""
"""
class IFjorkServerProtocol(interface.Interface):
"""
"""
class IFjorkServerFactory(interface.Interface):
"""
"""
class IFjorkService(interface.Interface):
"""
"""
class IFjork(interface.Interface):
"""
"""
class IPool(interface.Interface):
"""
"""
def queue(*args):
"""Accepts request specific number of arguments.
These arguments are passed to the pool member
responsible for processing a request.
"""
def process():
"""runs the next request in a seperate process
"""
def processCompleted():
"""when a process completes a request this callback fires
to queue the next request.
"""
class IFjorkJob(interface.Interface):
"""
"""
def fjork(**arguments):
"""
"""
| Python |
"""
"""
import marshal
import cStringIO
import struct
import simplejson
from twisted.internet import protocol
from twisted.python import log
from zope import interface
from fjork import ifjork
class FjorkClientProtocol(protocol.Protocol):
"""Fjork clients are basically just
line receivers that handle several basic
messages:
- run
- shutdown
- status
"""
interface.implements(ifjork.IFjorkClientProtocol)
FORMAT = simplejson
LTYPE = "L"
NBYTES = len(struct.pack(LTYPE, 0))
def __init__(self):
log.msg("creating fjork client protocol")
self.data = cStringIO.StringIO()
self.messageLength = None
def connectionMade(self):
log.msg("connection made")
def connectionLost(self, reason):
log.msg("lost connection")
def dataReceived(self, data):
log.msg("receiving data: %s bytes"%(len(data),))
log.msg("data:", data)
self.data.write(data)
if self.messageLength is None:
if len(self.data.getvalue()) >= self.NBYTES:
bytes = self.data.getvalue()[:self.NBYTES]
length = struct.unpack(self.LTYPE, bytes)[0]
self.messageLength = length
log.msg("messageLength:", self.messageLength)
if self.messageLength is not None:
if len(self.data.getvalue()) > self.messageLength:
serializedData = self.data.getvalue()[self.NBYTES:]
data = self.FORMAT.loads(serializedData)
message = data["message"].upper()
if message == "RUN":
result = self.run()
self.transport.write(result)
self.transport.loseConnection()
elif message == "SHUTDOWN":
self.shutdown()
else:
log.msg("Undefined message type: %s"%(message,))
def run(self):
"""Runs the specified Job"""
j = self.factory.job()
return j.fjork()
def shutdown(self):
"""Shutdowns the process"""
def status(self):
"""Returns info about this process
- uptime
- memory usage
"""
class WebkitClientProtocol(FjorkClientProtocol):
interface.implements(ifjork.IFjorkClientProtocol)
FORMAT = marshal
def dataReceived(self, data):
log.msg("receiving data: %s bytes"%(len(data),))
log.msg("data:", data)
self.data.write(data)
if self.messageLength is None:
if len(self.data.getvalue()) >= self.NBYTES:
bytes = self.data.getvalue()[:self.NBYTES]
self.messageLength = self.FORMAT.loads(bytes)
log.msg("messageLength:", self.messageLength)
if self.messageLength is not None:
if len(self.data.getvalue()) > self.messageLength:
serializedData = self.data.getvalue()[self.NBYTES:]
data = self.FORMAT.loads(serializedData)
message = data["message"].upper()
if message == "RUN":
result = self.run()
self.transport.write(result)
self.transport.loseConnection()
elif message == "SHUTDOWN":
self.shutdown()
else:
log.msg("Undefined message type: %s"%(message,))
class FjorkClientFactory(protocol.ClientFactory):
"""Fjork Factory
"""
interface.implements(ifjork.IFjorkClientFactory)
protocol = FjorkClientProtocol
def __init__(self, job):
self.job = job
class WebkitClientFactory(FjorkClientFactory):
interface.implements(ifjork.IFjorkClientFactory)
protocol = WebkitClientProtocol
class FjorkServerProtocol(FjorkClientProtocol):
"""Fjork clients are basically just
line receivers that handle several basic
messages:
- run
- shutdown
- status
"""
interface.implements(ifjork.IFjorkServerProtocol)
def __init__(self):
log.msg("fjork server protocol instantiated:")
self.data = cStringIO.StringIO()
self.messageLength = None
def connectionMade(self):
"""Sends message to subprocess"""
log.msg("connection made")
message = {"message":"RUN",
#"request":self.factory.request,
"request":"/"}
data = self.FORMAT.dumps(message)
size = len(data)
binary = ""
binary += struct.pack(self.LTYPE, size)
binary += struct.pack("%ss"%(size), data)
self.transport.write(binary)
def connectionLost(self, reason):
"""Calls back application with result"""
log.msg("lost connection")
self.factory.deferred.callback(self.data.getvalue())
def dataReceived(self, data):
"""Receives results from subprocess"""
log.msg("receiving from child process - data: %s"%(data,))
self.data.write(data)
class WebkitServerProtocol(FjorkServerProtocol):
interface.implements(ifjork.IFjorkServerProtocol)
FORMAT = marshal
def connectionMade(self):
"""Sends message to subprocess"""
log.msg("connection made")
# here's the real twisted request, how do we pack this into a pile
# of crap understood by webware?
# realTwistedRequest = self.factory.request
message = {"message":"RUN",
"request":"/",
"format":"CGI",
"environ":{},
}
data = self.FORMAT.dumps(message)
size = len(data)
message = ""
message += self.FORMAT.dumps(size)
message += data
self.transport.write(message)
class FjorkServerFactory(protocol.ClientFactory):
"""Fjork Factory
Even though i'm currently calling this a 'server' it
is really just a client protocol running on
the server side.
"""
interface.implements(ifjork.IFjorkServerFactory)
protocol = FjorkServerProtocol
def __init__(self, deferred, request):
self.deferred = deferred
self.request = request
class WebkitServerFactory(FjorkServerFactory):
interface.implements(ifjork.IFjorkServerFactory)
protocol = WebkitServerProtocol
class FjorkProcessProtocol(protocol.ProcessProtocol):
def __init__(self, address, deferred):
self.address = address
self.deferred = deferred
self.buffer = cStringIO.StringIO()
self.childProcessReady = False
def connectionMade(self):
log.msg("process protocol:", "connectionMade")
def outReceived(self, data):
log.msg("process protocol:", "outReceived", data)
if not self.childProcessReady:
self.buffer.write(data)
if "Fjork is ready!" in self.buffer.getvalue():
self.childProcessReady = True
self.deferred.callback(self.address)
def errReceived(self, data):
log.msg("process protocol:", "errReceived", data)
def inConnectionLost(self):
log.msg("process protocol:", "inConnectionLost")
def outConnectionLost(self):
log.msg("process protocol:", "outConnectionLost")
def errConnectionLost(self):
log.msg("process protocol:", "errConnectionLost")
def processExited(self, reason):
"""Called when child process exits:
reason should be either:
- twisted.internet.error.ProcessDone
- twisted.internet.error.ProcessTerminated
"""
# exitCode = reason.value.exitCode
# error = 'FjorkProcess.processExited: %s\n' % (exitCode,)
# log.msg(error)
# self.deferred.errback(reason)
pass
def processEnded(self, reason):
"""Called when the child process exits and all file descriptors
associated with it have been closed:
reason should be either:
- twisted.internet.error.ProcessDone
- twisted.internet.error.ProcessTerminated
"""
exitCode = reason.value.exitCode
error = 'FjorkProcess.processEnded: %s\n' % (exitCode,)
log.msg(error)
self.deferred.errback(reason)
| Python |
# __init__.py
| Python |
#!/usr/bin/env python
import sys
class fabrica_t:
def __init__(self, id, esquina, horario_apertura, horario_cierre):
self.id = id
self.esquina = esquina
self.horario_apertura = horario_apertura
self.horario_cierre = horario_cierre
self.juguetes = []
def agregarJuguete(self, j):
self.juguetes.append(j)
| Python |
#!/usr/bin/env python
import sys
import heapq
from prueba import *
def hacer_algo(var):
if(var == True):
print "Es Verdad"
else:
return
print "TERMINE"
fabrica_1 = fabrica_t("2580","14","0","30")
fabrica_2 = fabrica_t("2581","2562","27","75")
"""
if(fabrica_1 > fabrica_2):
print "fabrica 1 es mayor"
else:
print "ahora fabrica 2 es mayor"
l = []
l.append(fabrica_1)
l.append(fabrica_2)
heapq.heapify(l)
while len(l) != 0:
print heapq.heappop(l)
"""
capacidad = 4
n = 4
V = [0,1,4,3]
W = [0,1,3,2]
A = [[0 for x in xrange(capacidad + 1)] for x in xrange(n)]
for i in range(n):
for j in range(1,capacidad + 1):
if(W[i] > j):
A[i][j] = A[i - 1][j]
else:
A[i][j] = max(A[i - 1][j], V[i] + A[i - 1][j - W[i]])
print A
| Python |
#!/usr/bin/env python
import sys
from juguete import *
class fabrica_t:
def __init__(self, id, esquina, horario_apertura, horario_cierre):
self.id = id
self.esquina = esquina
self.horario_apertura = horario_apertura
self.horario_cierre = horario_cierre
self.juguetes = []
def insertarJuguete(self, id, valor, peso):
# Creo un juguete
j = juguete_t(id, valor, peso)
# Agrego el juguete a la lista
self.juguetes.append(j)
| Python |
#!/usr/bin/env python
import sys
import heapq
import math
from mapa import *
def darFormatoHora(n):
horas = n/60
minutos = n - (horas * 60)
if(horas < 10):
h = "0{0}".format(horas)
else:
h = "{0}".format(horas)
if(minutos < 10):
m = "0{0}".format(minutos)
else:
m = "{0}".format(minutos)
return "{0}:{1}".format(h,m)
def distanciaEntreVertices(a,b):
# print "Calculando distancia desde [{0}] a [{1}]".format(a.id, b.id)
# Calcula distancia desde un
# vertice A y otro B
x = b.x - a.x
y = b.y - a.y
# print "Las coordenadas son x={0} y={1}".format(x, y)
# print "Distancia {0}".format(math.sqrt(math.pow(x,2) + math.pow(y,2)))
# print "Presione una tecla para continuar..."
# raw_input()
return math.sqrt(math.pow(x,2) + math.pow(y,2))
class grafo_t:
def __init__(self):
self.vertices = [None]
self.poloNorte = None
def agregarVertice(self, id, x, y, latitud, longitud):
# Creo un vertice
v = vertice_t(id, x, y, latitud, longitud)
# Lo agrego a la lista
self.vertices.append(v)
def agregarArista(self, id, origen, destino):
# Busco el vertice de origen
v = self.vertices[origen]
# Busco el vertice destino
w = self.vertices[destino]
# Las calles son doble mano
v.agregarVecino(w)
w.agregarVecino(v)
def ubicarPoloNorte(self, idEsquinaPoloNorte):
# Busco el vertice donde se ubica el Polo Norte
v = self.vertices[idEsquinaPoloNorte]
if(v == None):
return False
self.poloNorte = v
return True
# Camino Optimo
def calcularCaminoOptimo(self,vertice_id):
# Identifico el destino
destino = self.vertices[vertice_id]
if(destino == None):
print "Error: la esquina con id {0} no existe".format(vertice_id)
return
# Defino una distancia infinita
INFINITO = sys.float_info.max
# Declaro un vector de distancias
# inicializado en infinto
Distancia = [INFINITO for x in xrange(len(self.vertices))]
# Declaro un vector de padres
# inicializado en -1
Padres = [-1 for x in xrange(len(self.vertices))]
# Declaro un vector de visitados
# inicializado en False
Visitados = [False for x in xrange(len(self.vertices))]
# Obtengo el indice del Polo Norte
indicePolo = self.vertices.index(self.poloNorte)
# Configuro la distancia al Polo Norte en 0
Distancia[indicePolo] = 0
# Declaro un heap de minima
h = []
# Declaro un tuple para agregar al heap
# y la prioridad es la distancia
origen = [Distancia[indicePolo], self.poloNorte]
# Agrego el tuple al heap
# para ser procesado
heapq.heappush(h, origen)
# Proceso todos los nodos de la cola
while len(h) != 0:
# Extraigo el de menor distancia
u_tuple = heapq.heappop(h)
u = u_tuple[1]
indice_u = self.vertices.index(u)
if(Visitados[indice_u]):
continue
# Lo marco como visitado
Visitados[indice_u] = True
# Proceso todos los vertices adyacentes
for vecino in u.vecinos:
alt = Distancia[indice_u] + distanciaEntreVertices(u,vecino)
indice_v = self.vertices.index(vecino)
if(alt < Distancia[indice_v]):
Distancia[indice_v] = alt
Padres[indice_v] = indice_u
if(Visitados[indice_v] == False):
v_tuple = [Distancia[indice_v], vecino]
heapq.heappush(h, v_tuple)
if(u == destino):
# print "Se porceso el nodo destino, deberia terminar"
break
# Obtengo el indice
indice_destino = self.vertices.index(destino)
metros = Distancia[indice_destino]
if(metros == sys.float_info.max):
print "Distancia es infinita"
return
print "Distancia: {0} metros".format(int(metros))
# Mostrar el camino
camino= []
indice_padre = indice_destino
while indice_padre != -1:
v = self.vertices[indice_padre]
if(v == None):
print "Error: la esquina con id {0} no existe".format(str(indice_padre))
camino.append(v)
indice_padre = Padres[indice_padre]
for w in reversed(camino):
print "{0}, {1}".format(w.latitud, w.longitud)
| Python |
#!/usr/bin/env python
import sys
import heapq
import math
from gestor import *
""" *********************************************************
UTILS
********************************************************* """
def obtenerComandoConParams(texto):
partes = texto.split(' ')
return partes
def obtenerParams(texto):
partes = texto.split(',')
return partes
# Defino constantes
CANT_ARGS = 6
INPUT_CAPACIDAD = 1
INPUT_POLO_NORTE = 2
INPUT_ARCHIVO_FABRICAS = 3
INPUT_ARCHIVO_JUGUETES = 4
INPUT_ARCHIVO_MAPA = 5
""" *********************************************************
MAIN
********************************************************* """
if len(sys.argv) < CANT_ARGS:
print 'ERROR: Faltan argumentos'
quit()
# Leo la capacidad del trineo
capacidad = sys.argv[INPUT_CAPACIDAD]
esquina_polo_norte = sys.argv[INPUT_POLO_NORTE]
arch_fabricas = sys.argv[INPUT_ARCHIVO_FABRICAS]
arch_juguetes = sys.argv[INPUT_ARCHIVO_JUGUETES]
arch_mapa = sys.argv[INPUT_ARCHIVO_MAPA]
# Creo un gestor
gestor = gestor_t()
# Defino la capacidad del trineo
gestor.definirCapacidadTrineo(capacidad)
# Abro el archivo del mapa
fmapa = open(arch_mapa,'r')
# Leo la cantidad de esquinas
# convierto la cantidad a int
cantidad_esquinas = int(fmapa.readline().rstrip())
# Leo "cantidad_esquinas" veces para almacenar las esquinas
for x in range(cantidad_esquinas):
linea = fmapa.readline()
campos = linea.split(',')
# Defino los campos
ESQUINA_ID = 0
ESQUINA_COORD_X = 1
ESQUINA_COORD_Y = 2
ESQUINA_LATITUD = 3
ESQUINA_LONGITUD = 4
gestor.agregarEsquina(campos[ESQUINA_ID], campos[ESQUINA_COORD_X], campos[ESQUINA_COORD_Y], campos[ESQUINA_LATITUD], campos[ESQUINA_LONGITUD].rstrip())
# Leo la cantidad de calles
# convierto la cantidad a int
cantidad_calles = int(fmapa.readline().rstrip())
# Leo "cantidad_calles" veces para procesar las calles
for x in range(int(cantidad_calles)):
linea = fmapa.readline()
campos = linea.split(',')
# Defino los campos
CALLE_ID = 0
CALLE_ESQUINA_INICIAL = 1
CALLE_ESQUINA_FINAL = 2
gestor.agregarCalle(campos[CALLE_ID], campos[CALLE_ESQUINA_INICIAL], campos[CALLE_ESQUINA_FINAL].rstrip())
# Cierro el archivo del mapa
fmapa.close()
# Ubico el Polo Norte
if gestor.agregarPoloNorte(esquina_polo_norte) == False:
print "ERROR: La esquina {0} ingresada para el Polo Norte no existe".format(esquina_polo_norte)
quit()
# Abro el archivo fabricas
ffab = open(arch_fabricas,'r')
for line in ffab:
campos = line.split(',')
# Defino los campos
FABRICA_ID = 0
FABRICA_ESQUINA_ID = 1
FABRICA_HORARIO_ENTRADA = 2
FABRICA_HORARIO_SALIDA = 3
gestor.agregarFabrica(campos[FABRICA_ID], campos[FABRICA_ESQUINA_ID], campos[FABRICA_HORARIO_ENTRADA], campos[FABRICA_HORARIO_SALIDA].rstrip())
# Cierro el archivo de fabricas
ffab.close()
# Abro el archivo de juguetes
fjug = open(arch_juguetes,'r')
for line in fjug:
campos = line.split(',')
# Defino los campos
JUGUETE_FABRICA_ID = 0
JUGUETE_ID = 1
JUGUETE_VALOR = 2
JUGUETE_PESO = 3
gestor.agregarJuguete(campos[JUGUETE_FABRICA_ID], campos[JUGUETE_ID], campos[JUGUETE_VALOR], campos[JUGUETE_PESO].rstrip())
# Cierro el archivo de juguetes
fjug.close()
# Procesar comando
try:
entrada = raw_input()
while entrada != None:
# Defino los campos
COMANDO = 0
PARAMETROS = 1
FABRICA_ID = 0
comandoConParams = obtenerComandoConParams(entrada)
comando = comandoConParams[COMANDO]
if(comando == "listar_fabricas"):
imprimir_resultado = True
gestor.listarFabricas(imprimir_resultado)
elif(comando == "valuar_juguetes"):
params = obtenerParams(comandoConParams[PARAMETROS])
gestor.valuarJuguetes(params[FABRICA_ID], True)
elif(comando == "valuar_juguetes_total"):
gestor.valuarJuguetesTotal()
elif(comando == "camino_optimo"):
param = obtenerParams(comandoConParams[PARAMETROS])
gestor.obtenerCaminoOptimo(param[FABRICA_ID])
entrada = raw_input()
except EOFError:
quit()
| Python |
#!/usr/bin/env python
class juguete_t:
def __init__(self, id, valor, peso):
self.id = id
self.valor = valor
self.peso = peso
| Python |
#!/usr/bin/env python
from grafo import *
from fabrica import *
class gestor_t:
def __init__(self):
self.grafo = grafo_t()
self.fabricas = []
self.fabricas_lista = []
self.capacidadTrineo = 0
self.lista_optima = []
def definirCapacidadTrineo(self, capacidad):
# Convierto el valor a int
self.capacidadTrineo = int(capacidad)
def agregarEsquina(self, id, x, y, latitud, longitud):
# Convierto los valores a int y a float
id = int(id)
x= float(x)
y = float(y)
latitud = float(latitud)
longitud = float(longitud)
self.grafo.agregarVertice(id, x, y, latitud, longitud)
def agregarCalle(self, id, origen, destino):
# Convierto los valores a int
id = int(id)
origen = int(origen)
destino = int(destino)
self.grafo.agregarArista(id, origen, destino)
def agregarPoloNorte(self, id_esquina):
# Convierto el id a int
id_esquina = int(id_esquina)
if( not self.grafo.ubicarPoloNorte(id_esquina)):
return False
return True
def agregarFabrica(self, id, esquina_id, horario_entrada, horario_salida):
# Convierto los valores a int
id = int(id)
esquina_id = int(esquina_id)
horario_entrada = int(horario_entrada)
horario_salida = int(horario_salida)
# Creo una fabrica
f = fabrica_t(id, esquina_id, horario_entrada, horario_salida)
# Agrego la fabrica a la lista
self.fabricas.append(f)
# Agrego como elementos de la lista item
# para que la funcion sort nativa ordene
# por estos campos
item = []
item.append(horario_salida)
item.append(horario_entrada)
item.append(id)
# Agrego el item a la lista de fabricas
self.fabricas_lista.append(item)
def agregarJuguete(self, fabrica_id, id, valor, peso):
# Convierto los valores a int
fabrica_id = int(fabrica_id)
id = int(id)
valor = int(valor)
peso = int(peso)
# Agrego el juguete a la fabrica
self.fabricas[fabrica_id].insertarJuguete(id, valor, peso)
# Listar Fabricas
def listarFabricas(self, imprimir_resultado):
# Ordeno las fabricas por
# horario de cierre
# horario de apertura
# id
self.fabricas_lista.sort()
# Declaro una lista para guardar las
# mejores opciones
self.lista_optima = []
for i in range(len(self.fabricas_lista) - 1):
if(i == 0):
f1 = self.fabricas_lista[i]
self.lista_optima.append(f1)
i = i + 1
f2 = self.fabricas_lista[i]
else:
f2 = self.fabricas_lista[i]
# Comparo si el horario de apertura
# de f2 es mayor o igual
# al horario de cierre de f1
if(f2[1] >= f1[0]):
self.lista_optima.append(f2)
f1 = f2
# Tengo las mejores opciones
if(imprimir_resultado):
print "Cantidad: {0}".format(len(self.lista_optima))
for item in self.lista_optima:
id = item[2]
print "{0}, {1}, {2}".format(id,darFormatoHora(item[1]),darFormatoHora(item[0]))
# Valuar juguetes
def valuarJuguetes(self, fabrica_id, imprimir_resultado):
fabrica_id = int(fabrica_id)
f = self.fabricas[fabrica_id]
if(f == None):
print "Error: la fabrica con id {0} no existe".format(fabrica_id)
return
# Obtengo la cantidad de juguetes
n = len(f.juguetes)
# Genero un vector W de peso y V de valor
W = []
V = []
# El elemento nulo pesa 0
# y su valor es 0
W.append(0)
V.append(0)
# Agrego los pesos y los valores
# Convierto las variables a int
for i in range(n):
W.append(int(f.juguetes[i].peso))
V.append(int(f.juguetes[i].valor))
# Declaro una matriz A
# para guardar la mejor opcion
# inicializada en 0
A = [[0 for x in xrange(self.capacidadTrineo + 1)] for x in xrange(n + 1)]
for i in xrange(1, n + 1):
for j in xrange(1, self.capacidadTrineo + 1):
if(W[i] > j):
A[i][j] = A[i - 1][j]
else:
A[i][j] = max(A[i - 1][j], V[i] + A[i - 1][j - W[i]])
if(imprimir_resultado):
print "Total: {0} Sonrisas".format(A[n][self.capacidadTrineo])
# Devuelvo el valor total de sonrisas
return A[n][self.capacidadTrineo]
# Valuar juguetes Total
def valuarJuguetesTotal(self):
cont = 0
# Si la lista optima no esta generada,
# la genero
if(len(self.lista_optima) == 0):
imprimir_resultado = False
self.listarFabricas(imprimir_resultado)
for f in self.lista_optima:
sonrisas = None
sonrisas = self.valuarJuguetes(f[2],False)
if(sonrisas != None):
cont = cont + sonrisas
print "Total: {0} Sonrisas".format(cont)
# Camino Optimo
def obtenerCaminoOptimo(self, fabrica_id):
fabrica_id = int(fabrica_id)
# Busco la fabrica destino
fabrica_destino = self.fabricas[fabrica_id]
if(fabrica_destino == None):
print "Error: la fabrica con id {0} no existe".format(fabrica_id)
return
# Busco el vertice destino
self.grafo.calcularCaminoOptimo(fabrica_destino.esquina)
| Python |
#!/usr/bin/env python
import sys
from fabrica import *
class heap_t:
def __init__(self):
self.vector = []
self.cant = 0
def comparar(self, a, b):
if(a == None):
return 1
if(b == None):
return -1
if(a.horario_cierre < b.horario_cierre):
return 1
elif(a.horario_cierre > b.horario_cierre):
return -1
else:
if(a.horario_apertura < b.horario_apertura):
return 1
elif(a.horario_apertura > b.horario_apertura):
return -1
else:
if(a.id < b.id):
return 1
else:
return -1
def encolar(self, elemento):
i = len(self.vector)
self.vector.append(elemento)
self.upHeap(elemento,i)
def swap(self, posA, posB):
aux = self.vector[posA]
self.vector[posA] = self.vector[posB]
self.vector[posB] = aux
def upHeap(self, hijo, pos_hijo):
if(pos_hijo == 0):
return
while pos_hijo > 0:
pos_padre = (pos_hijo - 1) / 2
padre = self.vector[pos_padre]
if(self.comparar(hijo,padre) > 0):
# swap
self.swap(pos_hijo,pos_padre)
pos_hijo = pos_padre
else:
return
def estaVacio(self):
return len(self.vector) == 0
def desencolar(self):
if(self.estaVacio()):
return None
e = self.vector[0]
print e.id
if(self.estaVacio()):
return e
cant = len(self.vector)
print cant
ultimo = self.vector[cant - 1]
self.vector[0] = ultimo
self.downHeap()
return e
def obtenerPosHijoMayor(self, i):
posHijoIzq = (i * 2) + 1
posHijoDer = (i * 2) + 2
der = None
if(posHijoIzq < len(self.vector)):
der = self.vector[posHijoIzq]
izq = None
if(posHijoDer < len(self.vector)):
izq = self.vector[posHijoIzq]
if(self.comparar(izq,der) > 0):
return posHijoIzq
else:
return posHijoDer
def downHeap(self):
pos_padre = 0
padre = self.vector[0]
while (pos_padre < len(self.vector)):
pos_hijo = self.obtenerPosHijoMayor(pos_padre)
hijo = self.vector[pos_hijo]
if(self.comparar(hijo,padre) > 0):
self.swap(pos_padre, pos_hijo)
pos_padre = pos_hijo
else:
return
| Python |
#!/usr/bin/env python
class vertice_t:
def __init__(self, id, x, y, latitud, longitud):
self.id = id
self.x = x
self.y = y
self.latitud = latitud
self.longitud = longitud
self.vecinos = []
def agregarVecino(self, v):
if(v in self.vecinos):
return
self.vecinos.append(v)
| Python |
#!/usr/bin/env python
import sys
import heapq
import math
from mapa import *
def darFormatoHora(n):
horas = n/60
minutos = n - (horas * 60)
if(horas < 10):
h = "0{0}".format(horas)
else:
h = "{0}".format(horas)
if(minutos < 10):
m = "0{0}".format(minutos)
else:
m = "{0}".format(minutos)
return "{0}:{1}".format(h,m)
def distanciaEntreVertices(a,b):
# print "Calculando distancia desde [{0}] a [{1}]".format(a.id, b.id)
# Calcula distancia desde un
# vertice A y otro B
x = b.x - a.x
y = b.y - a.y
# print "Las coordenadas son x={0} y={1}".format(x, y)
# print "Distancia {0}".format(math.sqrt(math.pow(x,2) + math.pow(y,2)))
# print "Presione una tecla para continuar..."
# raw_input()
return math.sqrt(math.pow(x,2) + math.pow(y,2))
class grafo_t:
def __init__(self):
self.vertices = [None]
self.poloNorte = None
def agregarVertice(self, id, x, y, latitud, longitud):
# Creo un vertice
v = vertice_t(id, x, y, latitud, longitud)
# Lo agrego a la lista
self.vertices.append(v)
def agregarArista(self, id, origen, destino):
# Busco el vertice de origen
v = self.vertices[origen]
# Busco el vertice destino
w = self.vertices[destino]
# Las calles son doble mano
v.agregarVecino(w)
w.agregarVecino(v)
def ubicarPoloNorte(self, idEsquinaPoloNorte):
# Busco el vertice donde se ubica el Polo Norte
v = self.vertices[idEsquinaPoloNorte]
if(v == None):
return False
self.poloNorte = v
return True
# Camino Optimo
def calcularCaminoOptimo(self,vertice_id):
# Identifico el destino
destino = self.vertices[vertice_id]
if(destino == None):
print "Error: la esquina con id {0} no existe".format(vertice_id)
return
# Defino una distancia infinita
INFINITO = sys.float_info.max
# Declaro un vector de distancias
# inicializado en infinto
Distancia = [INFINITO for x in xrange(len(self.vertices))]
# Declaro un vector de padres
# inicializado en -1
Padres = [-1 for x in xrange(len(self.vertices))]
# Declaro un vector de visitados
# inicializado en False
Visitados = [False for x in xrange(len(self.vertices))]
# Obtengo el indice del Polo Norte
indicePolo = self.vertices.index(self.poloNorte)
# Configuro la distancia al Polo Norte en 0
Distancia[indicePolo] = 0
# Declaro un heap de minima
h = []
# Declaro un tuple para agregar al heap
# y la prioridad es la distancia
origen = [Distancia[indicePolo], self.poloNorte]
# Agrego el tuple al heap
# para ser procesado
heapq.heappush(h, origen)
# Proceso todos los nodos de la cola
while len(h) != 0:
# Extraigo el de menor distancia
u_tuple = heapq.heappop(h)
u = u_tuple[1]
indice_u = self.vertices.index(u)
if(Visitados[indice_u]):
continue
# Lo marco como visitado
Visitados[indice_u] = True
# Proceso todos los vertices adyacentes
for vecino in u.vecinos:
alt = Distancia[indice_u] + distanciaEntreVertices(u,vecino)
indice_v = self.vertices.index(vecino)
if(alt < Distancia[indice_v]):
Distancia[indice_v] = alt
Padres[indice_v] = indice_u
if(Visitados[indice_v] == False):
v_tuple = [Distancia[indice_v], vecino]
heapq.heappush(h, v_tuple)
if(u == destino):
# print "Se porceso el nodo destino, deberia terminar"
break
# Obtengo el indice
indice_destino = self.vertices.index(destino)
metros = Distancia[indice_destino]
if(metros == sys.float_info.max):
print "Distancia es infinita"
return
print "Distancia: {0} metros".format(int(metros))
# Mostrar el camino
camino= []
indice_padre = indice_destino
while indice_padre != -1:
v = self.vertices[indice_padre]
if(v == None):
print "Error: la esquina con id {0} no existe".format(str(indice_padre))
camino.append(v)
indice_padre = Padres[indice_padre]
for w in reversed(camino):
print "{0}, {1}".format(w.latitud, w.longitud)
| Python |
#!/usr/bin/env python
import sys
import heapq
import math
from gestor import *
""" *********************************************************
UTILS
********************************************************* """
def obtenerComandoConParams(texto):
partes = texto.split(' ')
return partes
def obtenerParams(texto):
partes = texto.split(',')
return partes
# Defino constantes
CANT_ARGS = 6
INPUT_CAPACIDAD = 1
INPUT_POLO_NORTE = 2
INPUT_ARCHIVO_FABRICAS = 3
INPUT_ARCHIVO_JUGUETES = 4
INPUT_ARCHIVO_MAPA = 5
""" *********************************************************
MAIN
********************************************************* """
if len(sys.argv) < CANT_ARGS:
print 'ERROR: Faltan argumentos'
quit()
# Leo la capacidad del trineo
capacidad = sys.argv[INPUT_CAPACIDAD]
esquina_polo_norte = sys.argv[INPUT_POLO_NORTE]
arch_fabricas = sys.argv[INPUT_ARCHIVO_FABRICAS]
arch_juguetes = sys.argv[INPUT_ARCHIVO_JUGUETES]
arch_mapa = sys.argv[INPUT_ARCHIVO_MAPA]
# Creo un gestor
gestor = gestor_t()
# Defino la capacidad del trineo
gestor.definirCapacidadTrineo(capacidad)
# Abro el archivo del mapa
fmapa = open(arch_mapa,'r')
# Leo la cantidad de esquinas
# convierto la cantidad a int
cantidad_esquinas = int(fmapa.readline().rstrip())
# Leo "cantidad_esquinas" veces para almacenar las esquinas
for x in range(cantidad_esquinas):
linea = fmapa.readline()
campos = linea.split(',')
# Defino los campos
ESQUINA_ID = 0
ESQUINA_COORD_X = 1
ESQUINA_COORD_Y = 2
ESQUINA_LATITUD = 3
ESQUINA_LONGITUD = 4
gestor.agregarEsquina(campos[ESQUINA_ID], campos[ESQUINA_COORD_X], campos[ESQUINA_COORD_Y], campos[ESQUINA_LATITUD], campos[ESQUINA_LONGITUD].rstrip())
# Leo la cantidad de calles
# convierto la cantidad a int
cantidad_calles = int(fmapa.readline().rstrip())
# Leo "cantidad_calles" veces para procesar las calles
for x in range(int(cantidad_calles)):
linea = fmapa.readline()
campos = linea.split(',')
# Defino los campos
CALLE_ID = 0
CALLE_ESQUINA_INICIAL = 1
CALLE_ESQUINA_FINAL = 2
gestor.agregarCalle(campos[CALLE_ID], campos[CALLE_ESQUINA_INICIAL], campos[CALLE_ESQUINA_FINAL].rstrip())
# Cierro el archivo del mapa
fmapa.close()
# Ubico el Polo Norte
if gestor.agregarPoloNorte(esquina_polo_norte) == False:
print "ERROR: La esquina {0} ingresada para el Polo Norte no existe".format(esquina_polo_norte)
quit()
# Abro el archivo fabricas
ffab = open(arch_fabricas,'r')
for line in ffab:
campos = line.split(',')
# Defino los campos
FABRICA_ID = 0
FABRICA_ESQUINA_ID = 1
FABRICA_HORARIO_ENTRADA = 2
FABRICA_HORARIO_SALIDA = 3
gestor.agregarFabrica(campos[FABRICA_ID], campos[FABRICA_ESQUINA_ID], campos[FABRICA_HORARIO_ENTRADA], campos[FABRICA_HORARIO_SALIDA].rstrip())
# Cierro el archivo de fabricas
ffab.close()
# Abro el archivo de juguetes
fjug = open(arch_juguetes,'r')
for line in fjug:
campos = line.split(',')
# Defino los campos
JUGUETE_FABRICA_ID = 0
JUGUETE_ID = 1
JUGUETE_VALOR = 2
JUGUETE_PESO = 3
gestor.agregarJuguete(campos[JUGUETE_FABRICA_ID], campos[JUGUETE_ID], campos[JUGUETE_VALOR], campos[JUGUETE_PESO].rstrip())
# Cierro el archivo de juguetes
fjug.close()
# Procesar comando
try:
entrada = raw_input()
while entrada != None:
# Defino los campos
COMANDO = 0
PARAMETROS = 1
FABRICA_ID = 0
comandoConParams = obtenerComandoConParams(entrada)
comando = comandoConParams[COMANDO]
if(comando == "listar_fabricas"):
imprimir_resultado = True
gestor.listarFabricas(imprimir_resultado)
elif(comando == "valuar_juguetes"):
params = obtenerParams(comandoConParams[PARAMETROS])
gestor.valuarJuguetes(params[FABRICA_ID], True)
elif(comando == "valuar_juguetes_total"):
gestor.valuarJuguetesTotal()
elif(comando == "camino_optimo"):
param = obtenerParams(comandoConParams[PARAMETROS])
gestor.obtenerCaminoOptimo(param[FABRICA_ID])
entrada = raw_input()
except EOFError:
quit()
| Python |
#!/usr/bin/env python
import sys
import heapq
from prueba import *
def hacer_algo(var):
if(var == True):
print "Es Verdad"
else:
return
print "TERMINE"
fabrica_1 = fabrica_t("2580","14","0","30")
fabrica_2 = fabrica_t("2581","2562","27","75")
"""
if(fabrica_1 > fabrica_2):
print "fabrica 1 es mayor"
else:
print "ahora fabrica 2 es mayor"
l = []
l.append(fabrica_1)
l.append(fabrica_2)
heapq.heapify(l)
while len(l) != 0:
print heapq.heappop(l)
"""
capacidad = 4
n = 4
V = [0,1,4,3]
W = [0,1,3,2]
A = [[0 for x in xrange(capacidad + 1)] for x in xrange(n)]
for i in range(n):
for j in range(1,capacidad + 1):
if(W[i] > j):
A[i][j] = A[i - 1][j]
else:
A[i][j] = max(A[i - 1][j], V[i] + A[i - 1][j - W[i]])
print A
| Python |
#!/usr/bin/env python
from grafo import *
from fabrica import *
class gestor_t:
def __init__(self):
self.grafo = grafo_t()
self.fabricas = []
self.fabricas_lista = []
self.capacidadTrineo = 0
self.lista_optima = []
def definirCapacidadTrineo(self, capacidad):
# Convierto el valor a int
self.capacidadTrineo = int(capacidad)
def agregarEsquina(self, id, x, y, latitud, longitud):
# Convierto los valores a int y a float
id = int(id)
x= float(x)
y = float(y)
latitud = float(latitud)
longitud = float(longitud)
self.grafo.agregarVertice(id, x, y, latitud, longitud)
def agregarCalle(self, id, origen, destino):
# Convierto los valores a int
id = int(id)
origen = int(origen)
destino = int(destino)
self.grafo.agregarArista(id, origen, destino)
def agregarPoloNorte(self, id_esquina):
# Convierto el id a int
id_esquina = int(id_esquina)
if( not self.grafo.ubicarPoloNorte(id_esquina)):
return False
return True
def agregarFabrica(self, id, esquina_id, horario_entrada, horario_salida):
# Convierto los valores a int
id = int(id)
esquina_id = int(esquina_id)
horario_entrada = int(horario_entrada)
horario_salida = int(horario_salida)
# Creo una fabrica
f = fabrica_t(id, esquina_id, horario_entrada, horario_salida)
# Agrego la fabrica a la lista
self.fabricas.append(f)
# Agrego como elementos de la lista item
# para que la funcion sort nativa ordene
# por estos campos
item = []
item.append(horario_salida)
item.append(horario_entrada)
item.append(id)
# Agrego el item a la lista de fabricas
self.fabricas_lista.append(item)
def agregarJuguete(self, fabrica_id, id, valor, peso):
# Convierto los valores a int
fabrica_id = int(fabrica_id)
id = int(id)
valor = int(valor)
peso = int(peso)
# Agrego el juguete a la fabrica
self.fabricas[fabrica_id].insertarJuguete(id, valor, peso)
# Listar Fabricas
def listarFabricas(self, imprimir_resultado):
# Ordeno las fabricas por
# horario de cierre
# horario de apertura
# id
self.fabricas_lista.sort()
# Declaro una lista para guardar las
# mejores opciones
self.lista_optima = []
for i in range(len(self.fabricas_lista) - 1):
if(i == 0):
f1 = self.fabricas_lista[i]
self.lista_optima.append(f1)
i = i + 1
f2 = self.fabricas_lista[i]
else:
f2 = self.fabricas_lista[i]
# Comparo si el horario de apertura
# de f2 es mayor o igual
# al horario de cierre de f1
if(f2[1] >= f1[0]):
self.lista_optima.append(f2)
f1 = f2
# Tengo las mejores opciones
if(imprimir_resultado):
print "Cantidad: {0}".format(len(self.lista_optima))
for item in self.lista_optima:
id = item[2]
print "{0}, {1}, {2}".format(id,darFormatoHora(item[1]),darFormatoHora(item[0]))
# Valuar juguetes
def valuarJuguetes(self, fabrica_id, imprimir_resultado):
fabrica_id = int(fabrica_id)
f = self.fabricas[fabrica_id]
if(f == None):
print "Error: la fabrica con id {0} no existe".format(fabrica_id)
return
# Obtengo la cantidad de juguetes
n = len(f.juguetes)
# Genero un vector W de peso y V de valor
W = []
V = []
# El elemento nulo pesa 0
# y su valor es 0
W.append(0)
V.append(0)
# Agrego los pesos y los valores
# Convierto las variables a int
for i in range(n):
W.append(int(f.juguetes[i].peso))
V.append(int(f.juguetes[i].valor))
# Declaro una matriz A
# para guardar la mejor opcion
# inicializada en 0
A = [[0 for x in xrange(self.capacidadTrineo + 1)] for x in xrange(n + 1)]
for i in xrange(1, n + 1):
for j in xrange(1, self.capacidadTrineo + 1):
if(W[i] > j):
A[i][j] = A[i - 1][j]
else:
A[i][j] = max(A[i - 1][j], V[i] + A[i - 1][j - W[i]])
if(imprimir_resultado):
print "Total: {0} Sonrisas".format(A[n][self.capacidadTrineo])
# Devuelvo el valor total de sonrisas
return A[n][self.capacidadTrineo]
# Valuar juguetes Total
def valuarJuguetesTotal(self):
cont = 0
# Si la lista optima no esta generada,
# la genero
if(len(self.lista_optima) == 0):
imprimir_resultado = False
self.listarFabricas(imprimir_resultado)
for f in self.lista_optima:
sonrisas = None
sonrisas = self.valuarJuguetes(f[2],False)
if(sonrisas != None):
cont = cont + sonrisas
print "Total: {0} Sonrisas".format(cont)
# Camino Optimo
def obtenerCaminoOptimo(self, fabrica_id):
fabrica_id = int(fabrica_id)
# Busco la fabrica destino
fabrica_destino = self.fabricas[fabrica_id]
if(fabrica_destino == None):
print "Error: la fabrica con id {0} no existe".format(fabrica_id)
return
# Busco el vertice destino
self.grafo.calcularCaminoOptimo(fabrica_destino.esquina)
| Python |
#!/usr/bin/env python
import sys
class fabrica_t:
def __init__(self, id, esquina, horario_apertura, horario_cierre):
self.id = id
self.esquina = esquina
self.horario_apertura = horario_apertura
self.horario_cierre = horario_cierre
self.juguetes = []
def agregarJuguete(self, j):
self.juguetes.append(j)
| Python |
#!/usr/bin/env python
import sys
from fabrica import *
class heap_t:
def __init__(self):
self.vector = []
self.cant = 0
def comparar(self, a, b):
if(a == None):
return 1
if(b == None):
return -1
if(a.horario_cierre < b.horario_cierre):
return 1
elif(a.horario_cierre > b.horario_cierre):
return -1
else:
if(a.horario_apertura < b.horario_apertura):
return 1
elif(a.horario_apertura > b.horario_apertura):
return -1
else:
if(a.id < b.id):
return 1
else:
return -1
def encolar(self, elemento):
i = len(self.vector)
self.vector.append(elemento)
self.upHeap(elemento,i)
def swap(self, posA, posB):
aux = self.vector[posA]
self.vector[posA] = self.vector[posB]
self.vector[posB] = aux
def upHeap(self, hijo, pos_hijo):
if(pos_hijo == 0):
return
while pos_hijo > 0:
pos_padre = (pos_hijo - 1) / 2
padre = self.vector[pos_padre]
if(self.comparar(hijo,padre) > 0):
# swap
self.swap(pos_hijo,pos_padre)
pos_hijo = pos_padre
else:
return
def estaVacio(self):
return len(self.vector) == 0
def desencolar(self):
if(self.estaVacio()):
return None
e = self.vector[0]
print e.id
if(self.estaVacio()):
return e
cant = len(self.vector)
print cant
ultimo = self.vector[cant - 1]
self.vector[0] = ultimo
self.downHeap()
return e
def obtenerPosHijoMayor(self, i):
posHijoIzq = (i * 2) + 1
posHijoDer = (i * 2) + 2
der = None
if(posHijoIzq < len(self.vector)):
der = self.vector[posHijoIzq]
izq = None
if(posHijoDer < len(self.vector)):
izq = self.vector[posHijoIzq]
if(self.comparar(izq,der) > 0):
return posHijoIzq
else:
return posHijoDer
def downHeap(self):
pos_padre = 0
padre = self.vector[0]
while (pos_padre < len(self.vector)):
pos_hijo = self.obtenerPosHijoMayor(pos_padre)
hijo = self.vector[pos_hijo]
if(self.comparar(hijo,padre) > 0):
self.swap(pos_padre, pos_hijo)
pos_padre = pos_hijo
else:
return
| Python |
#!/usr/bin/env python
import sys
from juguete import *
class fabrica_t:
def __init__(self, id, esquina, horario_apertura, horario_cierre):
self.id = id
self.esquina = esquina
self.horario_apertura = horario_apertura
self.horario_cierre = horario_cierre
self.juguetes = []
def insertarJuguete(self, id, valor, peso):
# Creo un juguete
j = juguete_t(id, valor, peso)
# Agrego el juguete a la lista
self.juguetes.append(j)
| Python |
#!/usr/bin/env python
class juguete_t:
def __init__(self, id, valor, peso):
self.id = id
self.valor = valor
self.peso = peso
| Python |
#!/usr/bin/env python
class vertice_t:
def __init__(self, id, x, y, latitud, longitud):
self.id = id
self.x = x
self.y = y
self.latitud = latitud
self.longitud = longitud
self.vecinos = []
def agregarVecino(self, v):
if(v in self.vecinos):
return
self.vecinos.append(v)
| Python |
#!/usr/bin/env python
import cgi
import urllib
import webapp2
import jinja2
import os
from google.appengine.ext import db
from google.appengine.api import users
jinja_environment = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)) )
MAX_NEW_CARDS = 10
class Card(db.Model):
"""Models and individual language flashcard, with entries for foreign
language text, pronunciation text, native language text, and a reference
to an audio file. Each card uses 'level,' an integer to represent its
history of correct and incorrect guesses. Cards are initialized with value
0 meaning not yet shown. The higher the value, the more successful the user's
history, and the less frequently the card will be shown."""
forLang = db.StringProperty(multiline = True)
pronunciation = db.StringProperty(multiline = True)
natLang = db.StringProperty(multiline = True)
audio = db.StringProperty()
level = db.IntegerProperty()
# Will eventually add much more: time added, example sentences + audio
class MainHandler(webapp2.RequestHandler):
def get(self):
template_values = {}
template = jinja_environment.get_template('templates/index.html')
self.response.out.write(template.render(template_values))
class StartHandler(webapp2.RequestHandler):
def post(self):
createOrReview = self.request.get("createReview")
if createOrReview == "create":
template_values = {}
template = jinja_environment.get_template('templates/newCard.html')
self.response.out.write(template.render(template_values))
else:
template_values = {}
template = jinja_environment.get_template('templates/cardSettings.html')
self.response.out.write(template.render(template_values))
class SetUpHandler(webapp2.RequestHandler):
def post(self):
frontSettings = self.request.get_all("stimulus")
backSettings = self.request.get_all("response")
# Extract the next card to display:
nextCard = db.GqlQuery("SELECT * "
"FROM Card "
"WHERE level = 0 "
"LIMIT 1")
# To do: switch 'fForLang' etc., to actual values extracted from db
fForLang = ('<span id="fForLang">%s<br /></span>' % nextCard[0].forLang if
'forLang' in frontSettings else '')
fPronunciation = ('<span id="fPronunciation">%s<br /></span>'
% nextCard[0].pronunciation if 'pronunciation' in
frontSettings else '')
fNatLang = ('<span id="fNatLang">%s<br /></span>' % nextCard[0].natLang if
'natLang' in frontSettings else '')
fAudio = ("""<span>
<audio id="fAudio" controls="controls">
<source src="OGG FILE SRC" />
<source src="MP3 FILE SRC" />
Your jankity ol' browser doesn't support the audio
element.
</audio>
</span><br />"""
if 'audio' in frontSettings else '')
bForLang = ('<span id="bForLang">%s<br /></span>' % nextCard[0].forLang if
'forLang' in backSettings else '')
bPronunciation = ('<span id="bPronunciation">%s<br /></span>'
% nextCard[0].pronunciation if 'pronunciation' in
backSettings else '')
bNatLang = ('<span id="bNatLang">%s<br /></span>' % nextCard[0].natLang if
'natLang' in backSettings else '')
bAudio = ("""<span>
<audio id="fAudio" controls="controls">
<source src="OGG FILE SRC" />
<source src="MP3 FILE SRC" />
Your jankity ol' browser doesn't support the audio element
.
</audio>
</span><br />"""
if 'audio' in backSettings else '')
template_values = { 'fForLang': fForLang,
'fPronunciation': fPronunciation,
'fNatLang': fNatLang,
'fAudio': fAudio,
'bForLang': bForLang,
'bPronunciation': bPronunciation,
'bNatLang': bNatLang,
'bAudio': bAudio }
template = jinja_environment.get_template('templates/card.html')
self.response.out.write(template.render(template_values))
class WriteHandler(webapp2.RequestHandler):
def post(self):
card = Card()
card.forLang = self.request.get('forLang')
card.pronunciation = self.request.get('pronunciation')
card.natLang = self.request.get('natLang')
card.level = 0
card.put()
template_values = {}
template = jinja_environment.get_template('templates/newCard.html')
self.response.out.write(template.render(template_values))
# """In the order that the cards were created, (or from a predefined order if
# a stock deck), cards will be promoted from level 0 to 1, indicating the
# first time to be shown. If the user gets the card correct, level is
# incremented--by 1 if the difficulty was so-so, by 2 if easy, if hard, level
# remains unchanged. If a card is missed it gets demoted by 2 (or to a min
# value of 1). Within a session, once a card is promoted it is not shown again#.
# At the end of the session, new (level = 0) cards are promoted to level = 1,
# such that there are a total of MAX_NEW_CARDS at level 1."""
# def post(self):
# difficulty = self.request.get('difficulty')
class MissedHandler(webapp2.RequestHandler):
def post(self):
self.response.out.write("Missed me. <em>Suckah!</em>")
class HardHandler(webapp2.RequestHandler):
def post(self):
self.response.out.write("So hard!")
class SoSoHandler(webapp2.RequestHandler):
def post(self):
self.response.out.write("Meh.")
class EasyHandler(webapp2.RequestHandler):
def post(self):
self.response.out.write("It's a piece of cake.")
app = webapp2.WSGIApplication([('/', MainHandler),
('/start', StartHandler),
('/setup', SetUpHandler),
('/write', WriteHandler),
('/missed', MissedHandler),
('/hard', HardHandler),
('/soSo', SoSoHandler),
('/easy', EasyHandler)
],
debug=True)
def main():
run_wsgi_app(app)
if __name__ == "__main__":
main()
| Python |
__author__ = 'skird'
from algo.shortestpathfinder import ShortestPathFinder
class TransportScheduleGraph:
def __init__(self, vertices_list):
"""
:param vertices_list - list of vertices of graph
"""
self.__finder = ShortestPathFinder(vertices_list)
@staticmethod
def __append_edge(path, edge):
if path > edge[1]:
return None
return edge[2]
def add_route(self, from_vertex, to_vertex, time_leave, time_come) -> None:
"""
:param from_vertex starting point of route
:param to_vertex ending point of route
:param time_leave start time of route
:param time_come end time of route
:rtype None
:return None
"""
if from_vertex not in self.__finder:
raise KeyError("from_vertex does not exist")
if to_vertex not in self.__finder:
raise KeyError("to_vertex does not exist")
self.__finder.add_edge(from_vertex, (to_vertex, time_leave, time_come))
def find_way(self, from_vertex, to_vertex, start_time=0):
"""
:param from_vertex
:param to_vertex
:param start_time
:rtype pair of arrival time and route to destination - the list of used transport represented by tuple
of (interjacent_destination, boarding_time, arrival_time)
:returns pair of arrival time and list of used transport
"""
return self.__finder.find_shortest_path(from_vertex, to_vertex,
initial_path_weight=start_time,
append_edge=TransportScheduleGraph.__append_edge) | Python |
__author__ = 'skird'
class Dijkstra:
@staticmethod
def find_shortest_paths(graph, from_vertices, *,
initial_path_weight=0,
comparator=lambda w1, w2: w1 < w2,
append_edge=lambda path, edge: path + edge[1],
edge_destination=lambda edge: edge[0]) -> dict:
"""
:param graph: Iterable, indexable container each element of which is iterable list of edges
:param from_vertices: List of vertices to find path from
:param initial_path_weight: Initial value of weight for starting vertices.
It is considered by neutral element for append_edge function
:param comparator: Function used to compare two paths' weights
:param append_edge: Function evaluating weight of path with one appended edge. It may return None if appending
edge to this path is not allowed (this should be decided in determenistic way, of course)
:param edge_destination: Function used to determine destination of edge. Should return valid index in graph.
By default it is assumed that edge is a pair of destination and its weight
:return Dict mapping each vertex to its shortest path if it exists
:rtype : dict
For weight function there are following restrictions:
- There are no negative edges, so weight of append_edge(path, edge) is not less then weight of path
- All shortest path are equally good, so if weight of path1 is equal to weight of path2 then
append_edge(path1, edge) is equal append_edge(path2, edge)
"""
gray = list(from_vertices)
dist = dict()
for v in from_vertices:
dist[v] = initial_path_weight
while len(gray) > 0:
v = Dijkstra.__find_nearest(gray, dist, comparator)
gray.remove(v)
for edge in graph[v]:
Dijkstra.__relax_edge(v, edge, gray, dist, comparator, edge_destination, append_edge)
return dist
@staticmethod
def __find_nearest(gray, dist, comparator):
(min_dist, ans) = (None, None)
for v in gray:
if min_dist is None or comparator(dist[v], min_dist):
(min_dist, ans) = (dist[v], v)
return ans
@staticmethod
def __relax_edge(v, edge, gray, dist, comparator, edge_destination, append_edge) -> None:
to = edge_destination(edge)
w = append_edge(dist[v], edge)
if w is None:
return
if to not in dist:
gray.append(to)
dist[to] = w
else:
if comparator(w, dist[to]):
dist[to] = w | Python |
from algo.dijkstra import Dijkstra
__author__ = 'skird'
class ShortestPathFinder:
def __init__(self, vertices_list):
"""
TODO: doc
"""
self.__comparator = lambda w1, w2: w1 < w2
self.__appender = lambda path, edge: path + edge[1]
self.__get_destination = lambda edge: edge[0]
self.__start_vertex = 0
self.__graph = {v: list() for v in vertices_list}
def __contains__(self, item):
return item in self.__graph
def __compare_routes(self, first, second):
return self.__comparator(first[0], second[0])
def __append_edge(self, path, edge):
new_weight = self.__appender(path[0], edge)
if new_weight is None:
return None
return self.__appender(path[0], edge), edge, self.__edge_destination(path[1])
def __edge_destination(self, edge):
if edge is None:
return self.__start_vertex
return self.__get_destination(edge)
def add_edge(self, from_vertex, edge):
"""
TODO: doc
"""
if from_vertex not in self.__graph:
raise KeyError('starting vertex not in graph')
if self.__get_destination(edge) not in self.__graph:
raise KeyError('ending vertex not in graph')
self.__graph[from_vertex].append(edge)
def add_edges(self, edges):
"""
TODO: doc
"""
for edge in edges:
self.add_edge(edge[0], edge[1])
def erase_edge(self, from_vertex, edge):
if from_vertex not in self.__graph or edge not in self.__graph[from_vertex]:
return
self.__graph[from_vertex].remove(edge)
def find_shortest_path(self, from_vertex, to_vertex, *,
initial_path_weight=0,
comparator=lambda w1, w2: w1 < w2,
append_edge=lambda path, edge: path + edge[1],
edge_destination=lambda edge: edge[0]):
"""
TODO: doc
"""
self.__comparator = comparator
self.__appender = append_edge
self.__get_destination = edge_destination
self.__start_vertex = from_vertex
dist = Dijkstra.find_shortest_paths(self.__graph, [from_vertex],
initial_path_weight=(initial_path_weight, None, None),
comparator=self.__compare_routes, append_edge=self.__append_edge,
edge_destination=self.__edge_destination)
if to_vertex not in dist:
return None, None
route = list()
current = to_vertex
while current != from_vertex:
route.append(dist[current][1])
current = dist[current][2]
return dist[to_vertex][0], list(reversed(route)) | Python |
__author__ = 'skird'
import unittest
from algo.shortestpathfinder import ShortestPathFinder
class ShortestPathFinderIntegration(unittest.TestCase):
def setUp(self):
pass
def test_on_simple_graph(self):
finder = ShortestPathFinder(['a', 'b', 'c', 'd'])
finder.add_edge('a', ('b', 5))
finder.add_edge('a', ('c', 3))
finder.add_edges([('b', ('d', 7)), ('c', ('d', 10))])
self.assertRaises(KeyError, finder.add_edge, 'x', ('a', 5))
self.assertRaises(KeyError, finder.add_edge, 'b', ('x', 1))
self.assertRaises(KeyError, finder.add_edge, 'w', ('z', 13))
self.assertRaises(KeyError, finder.add_edges, [('b', ('a', 100)), ('z', ('a', 1))])
weight, path = finder.find_shortest_path('a', 'd')
self.assertEqual(weight, 12)
self.assertListEqual(path, [('b', 5), ('d', 7)])
weight, path = finder.find_shortest_path('a', 'a')
self.assertEqual(weight, 0)
self.assertListEqual(path, [])
weight, path = finder.find_shortest_path('d', 'a')
self.assertIsNone(weight)
self.assertIsNone(path)
finder.erase_edge('a', ('b', 5))
weight, path = finder.find_shortest_path('a', 'd')
self.assertEqual(weight, 13)
self.assertListEqual(path, [('c', 3), ('d', 10)])
finder.erase_edge('a', ('b', 5)) # remove edge twice (do nothing)
weight, path = finder.find_shortest_path('a', 'd')
self.assertEqual(weight, 13)
self.assertListEqual(path, [('c', 3), ('d', 10)])
| Python |
__author__ = 'skird'
import unittest
from algo.transport_scheduling import TransportScheduleGraph
class TransportSchedulingIntegrationTest(unittest.TestCase):
def test_simple_graphs(self):
graph = TransportScheduleGraph(['Sheremetievo', 'Dolgoprudnaya', 'Novodachnaya',
'Lianozovo', 'Timiryazevskaya', 'Savelovsky terminal'])
graph.add_route('Dolgoprudnaya', 'Lianozovo', 100, 150)
graph.add_route('Sheremetievo', 'Savelovsky terminal', 50, 400) # express train!
graph.add_route('Lianozovo', 'Timiryazevskaya', 150, 200)
graph.add_route('Timiryazevskaya', 'Savelovsky terminal', 200, 250)
graph.add_route('Novodachnaya', 'Lianozovo', 250, 300)
graph.add_route('Lianozovo', 'Timiryazevskaya', 400, 450) # waiting for express in Beskudnikovo
graph.add_route('Timiryazevskaya', 'Savelovsky terminal', 450, 500)
arrive, path = graph.find_way('Novodachnaya', 'Timiryazevskaya', 200)
self.assertEqual(arrive, 450)
self.assertListEqual(path, [('Lianozovo', 250, 300), ('Timiryazevskaya', 400, 450)])
arrive, path = graph.find_way('Novodachnaya', 'Timiryazevskaya', 250)
self.assertEqual(arrive, 450)
self.assertListEqual(path, [('Lianozovo', 250, 300), ('Timiryazevskaya', 400, 450)])
arrive, path = graph.find_way('Novodachnaya', 'Timiryazevskaya', 251)
self.assertEqual(arrive, None)
self.assertEqual(path, None)
arrive, path = graph.find_way('Dolgoprudnaya', 'Timiryazevskaya', 100)
self.assertEqual(arrive, 200)
self.assertListEqual(path, [('Lianozovo', 100, 150), ('Timiryazevskaya', 150, 200)])
arrive, path = graph.find_way('Dolgoprudnaya', 'Timiryazevskaya', 110)
self.assertEqual(arrive, None)
self.assertEqual(path, None)
graph.add_route('Novodachnaya', 'Dolgoprudnaya', 80, 90) # on foot ;)
arrive, path = graph.find_way('Novodachnaya', 'Timiryazevskaya', 80)
self.assertEqual(arrive, 200)
self.assertListEqual(path, [('Dolgoprudnaya', 80, 90), ('Lianozovo', 100, 150), ('Timiryazevskaya', 150, 200)])
arrive, path = graph.find_way('Novodachnaya', 'Timiryazevskaya', 90)
self.assertEqual(arrive, 450)
self.assertListEqual(path, [('Lianozovo', 250, 300), ('Timiryazevskaya', 400, 450)])
self.assertRaises(KeyError, graph.add_route, 'Savelovo', 'Savelovsky Terminal', 100, 500)
self.assertRaises(KeyError, graph.add_route, 'Novodachnaya', 'Mark', -1, 1)
self.assertRaises(KeyError, graph.add_route, 'Savelovo', 'Golitsino', 0, 10 ** 5)
| Python |
__author__ = 'skird' | Python |
__author__ = 'skird'
from algo.dijkstra import Dijkstra
import itertools
import unittest
import random
class DijkstraIntegrationTest(unittest.TestCase):
def setUp(self):
pass
def __make_weighted_list_graph(self, n, edges) -> list:
graph = [list() for _ in range(n)]
for edge in edges:
graph[edge[0]].append((edge[1], edge[2]))
return graph
def __make_weighted_dict_graph(self, n, edges) -> dict:
graph = dict()
for i in range(n):
graph[i] = list()
for edge in edges:
graph[edge[0]].append((edge[1], edge[2]))
return graph
def __make_dict_graph(self, n, edges) -> dict:
graph = dict()
for i in range(n):
graph[i] = list()
for edge in edges:
graph[edge[0]].append(edge[1])
return graph
def __make_list_graph(self, n, edges) -> list:
graph = [list() for _ in range(n)]
for edge in edges:
graph[edge[0]].append(edge[1])
return graph
def test_with_integer_weights(self) -> None:
tests = list()
answers = list()
tests.append(self.__make_weighted_list_graph(3, {(0, 1, 2), (0, 2, 5), (1, 2, 2)}))
answers.append({0: 0, 1: 2, 2: 4})
tests.append(self.__make_weighted_dict_graph(5, {(0, 1, 1), (1, 2, 1), (2, 3, 1), (3, 4, 1), (0, 2, 3),
(2, 4, 3), (1, 4, 4)}))
answers.append({0: 0, 1: 1, 2: 2, 3: 3, 4: 4})
tests.append(self.__make_weighted_list_graph(10, {}))
answers.append(dict({0: 0}))
for (index, test) in enumerate(tests):
ret = Dijkstra.find_shortest_paths(test, [0])
self.assertDictEqual(ret, answers[index])
def test_with_no_weights(self) -> None:
tests = list()
answers = list()
tests.append((self.__make_list_graph(3, {(0, 1), (0, 2), (1, 2)}), [0]))
answers.append({0: 0, 1: 1, 2: 1})
tests.append((self.__make_dict_graph(5, {(0, 1), (1, 2), (1, 3), (3, 1), (3, 0), (3, 4), (4, 2)}), [0]))
answers.append({0: 0, 1: 1, 2: 2, 3: 2, 4: 3})
tests.append((self.__make_dict_graph(5, {(0, 1), (1, 2), (1, 3), (3, 1), (3, 0), (3, 4), (4, 2)}), [0, 4]))
answers.append({0: 0, 1: 1, 2: 1, 3: 2, 4: 0})
tests.append((self.__make_list_graph(3, {}), [1, 2]))
answers.append(dict({1: 0, 2: 0}))
for (index, test) in enumerate(tests):
ret = Dijkstra.find_shortest_paths(test[0], test[1],
append_edge=lambda path, edge: path + 1,
edge_destination=lambda edge: edge)
self.assertDictEqual(ret, answers[index])
class DijkstraStressTest(unittest.TestCase):
def setUp(self):
pass
def __make_graph_from_bit_field(self, size, bit_field) -> list:
graph = [list() for _ in range(size)]
for i in range(size):
for j in range(size):
if bit_field[i * size + j] == 1:
graph[i].append(j)
return graph
def __make_random_weighted_graph_from_bit_field(self, size, bit_field) -> list:
graph = [list() for _ in range(size)]
for i in range(size):
for j in range(size):
if bit_field[i * size + j] == 1:
graph[i].append((j, random.randrange(100)))
return graph
def __generate_random_weighted_graph(self, size) -> list:
max_weight = 100
p = random.random()
graph = [list() for _ in range(size)]
for i in range(size):
for j in range(size):
if random.random() < p:
graph[i].append((j, random.randrange(max_weight)))
return graph
def __dummy_shortest_paths_unweighted(self, graph, from_vertex) -> dict:
n = len(graph)
dist = [[n for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in graph[i]:
dist[i][j] = 1
dist[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
answer = dict()
for i in range(n):
if dist[from_vertex][i] < n:
answer[i] = dist[from_vertex][i]
return answer
def __dummy_shortest_paths_weighted(self, graph, from_vertex) -> dict:
n = len(graph)
dist = [[None for _ in range(n)] for _ in range(n)]
for i in range(n):
for edge in graph[i]:
dist[i][edge[0]] = edge[1]
dist[i][i] = 0
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] is not None and dist[k][j] is not None and \
(dist[i][j] is None or dist[i][j] > dist[i][k] + dist[k][j]):
dist[i][j] = dist[i][k] + dist[k][j]
answer = dict()
for i in range(n):
if dist[from_vertex][i] is not None:
answer[i] = dist[from_vertex][i]
return answer
def test_on_all_small_graphs(self) -> None:
graph_size = 3
for bit_field in itertools.product({0, 1}, repeat=graph_size ** 2):
test = self.__make_graph_from_bit_field(graph_size, bit_field)
ret = Dijkstra.find_shortest_paths(test, [0], append_edge=lambda path, edge: path + 1,
edge_destination=lambda edge: edge)
self.assertDictEqual(ret, self.__dummy_shortest_paths_unweighted(test, 0))
for bit_field in itertools.product({0, 1}, repeat=graph_size ** 2):
test = self.__make_random_weighted_graph_from_bit_field(graph_size, bit_field)
ret = Dijkstra.find_shortest_paths(test, [0])
self.assertDictEqual(ret, self.__dummy_shortest_paths_weighted(test, 0))
def test_on_random_graphs(self) -> None:
test_number = 30
graph_size = 50
for it in range(test_number):
size = random.randrange(1, graph_size + 1)
test = self.__generate_random_weighted_graph(size)
ret = Dijkstra.find_shortest_paths(test, [0], append_edge=lambda path, edge: path + edge[1],
edge_destination=lambda edge: edge[0])
self.assertDictEqual(ret, self.__dummy_shortest_paths_weighted(test, 0))
# access to private methods of Dijkstra:
# noinspection PyProtectedMember
class DijkstraRelaxEdgeTest(unittest.TestCase):
def setUp(self) -> None:
pass
def test_on_simple_graph(self) -> None:
gray = list()
dist = {0: 0}
compare = lambda a, b: a < b
destination = lambda edge: edge
append_edge = lambda path, edge: path + 1
Dijkstra._Dijkstra__relax_edge(0, 1, gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1])
self.assertDictEqual(dist, {0: 0, 1: 1})
Dijkstra._Dijkstra__relax_edge(1, 0, gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1])
self.assertDictEqual(dist, {0: 0, 1: 1})
Dijkstra._Dijkstra__relax_edge(1, 2, gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1, 2])
self.assertDictEqual(dist, {0: 0, 1: 1, 2: 2})
Dijkstra._Dijkstra__relax_edge(0, 2, gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1, 2])
self.assertDictEqual(dist, {0: 0, 1: 1, 2: 1})
def test_on_timetable_graph(self) -> None:
class Distance:
def __init__(self, value):
self.dist = value
def __lt__(self, other):
assert isinstance(other, Distance)
return (self.dist is not None) and (other.dist is None or self.dist < other.dist)
#def __repr__(self):
# return str(self.dist) if self.dist is not None else "Infinity"
def __eq__(self, other):
return self.dist == other.dist
gray = list()
dist = {0: Distance(0)}
compare = lambda a, b: a < b
destination = lambda edge: edge[0]
def append_edge(path, edge):
assert isinstance(path, Distance)
if path.dist is None or path.dist > edge[1]:
return Distance(None)
return Distance(edge[2])
Dijkstra._Dijkstra__relax_edge(0, (1, 0, 1), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1])
self.assertDictEqual(dist, {0: Distance(0), 1: Distance(1)})
Dijkstra._Dijkstra__relax_edge(0, (2, -1, 1), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1, 2])
self.assertDictEqual(dist, {0: Distance(0), 1: Distance(1), 2: Distance(None)})
Dijkstra._Dijkstra__relax_edge(1, (2, 3, 4), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1, 2])
self.assertDictEqual(dist, {0: Distance(0), 1: Distance(1), 2: Distance(4)})
Dijkstra._Dijkstra__relax_edge(0, (2, 2, 2), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [1, 2])
self.assertDictEqual(dist, {0: Distance(0), 1: Distance(1), 2: Distance(2)})
def test_on_max_edge_graph(self) -> None:
gray = [0, 1, 2, 3]
dist = {0: -5, 1: 100, 2: 100, 3: 1}
compare = lambda x, y: x < y
destination = lambda edge: edge[0]
append_edge = lambda path, edge: max(path, edge[1])
Dijkstra._Dijkstra__relax_edge(0, (1, 5), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [0, 1, 2, 3])
self.assertDictEqual(dist, {0: -5, 1: 5, 2: 100, 3: 1})
Dijkstra._Dijkstra__relax_edge(1, (2, 101), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [0, 1, 2, 3])
self.assertDictEqual(dist, {0: -5, 1: 5, 2: 100, 3: 1})
Dijkstra._Dijkstra__relax_edge(1, (2, 3), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [0, 1, 2, 3])
self.assertDictEqual(dist, {0: -5, 1: 5, 2: 5, 3: 1})
Dijkstra._Dijkstra__relax_edge(0, (2, 3), gray, dist, compare, destination, append_edge)
self.assertListEqual(gray, [0, 1, 2, 3])
self.assertDictEqual(dist, {0: -5, 1: 5, 2: 3, 3: 1})
# access to private methods of Dijkstra:
# noinspection PyProtectedMember
class DijkstraFindNearestTest(unittest.TestCase):
def setUp(self) -> None:
pass
def test_on_simple_graph(self) -> None:
gray = [0, 2, 7, 3]
dist = {0: 34, 1: 3, 2: 49, 3: -1, 4: 0, 7: 12, 100: 35}
self.assertEqual(Dijkstra._Dijkstra__find_nearest(gray, dist, lambda x, y: x < y), 3)
self.assertEqual(Dijkstra._Dijkstra__find_nearest(gray, dist, lambda x, y: x > y), 2)
def test_with_custom_labels(self) -> None:
gray = ["Andrey", "Leo", "Vasily", "Vladimir"]
dist = {"Andrey": "vampire", "Leo": "elf", "Vasily": "gray unicorn", "Vladimir": "orc", "Masha": "nobody"}
self.assertEqual(Dijkstra._Dijkstra__find_nearest(gray, dist, lambda x, y: x < y), "Leo")
self.assertEqual(Dijkstra._Dijkstra__find_nearest(gray, dist, lambda x, y: x > y), "Andrey")
self.assertEqual(Dijkstra._Dijkstra__find_nearest(gray, dist, lambda x, y: len(x) > len(y)), "Vasily")
| Python |
__author__ = 'Алексей'
from dijkstra import Dijkstra
class PublicTransport:
class Edge:
def __init__(self, time_depart, to_vertex, time_arrive):
self.time_depart = time_depart
self.time_arrive = time_arrive
self.destination = to_vertex
def __init__(self, graphSize, inf_time, cmp_time = lambda t1, t2: t1 < t2):
"""
:param graphSize: size of Graph
:param inf_time: Time which is more then all other for cmp_time
:param cmp_time: compares two times
"""
self.graph = []
self.inf_time = inf_time
self.cmp_time = cmp_time
for i in range(graphSize):
self.graph.append([])
def __add_edge_to_path__(self, path, edge):
if self.cmp_time(edge.time_depart, path):
return self.inf_time
else:
return edge.time_arrive
def add_edge(self, from_vertex, to_vertex, time_depart, time_arrive):
"""
:param from_vertex: Number of departure vertex
:param to_vertex: Number of arrival vertex
:param time_depart: Time of department
:param time_arrive: Time of arrival
"""
self.graph[from_vertex].append(self.Edge(time_depart, to_vertex, time_arrive))
def solve(self, start_vertex, start_time):
"""
:param start_vertex: Vertex, where you start moving
:param start_time: Time when you appear there
"""
self.result = Dijkstra(self.graph, start_vertex, start_time, self.cmp_time, self.__add_edge_to_path__)
def get_times(self):
"""
:return: list of shortest times to get to all vertices, None if impossible to get
"""
res = self.result.get_path_values()
for i in range(len(res)):
if res[i] == self.inf_time:
res[i] = None
return res
def get_path_to_vertex(self, finish_vertex):
"""
:param finish_vertex: number of finish vertex. It's time must be non-None in get_times method
:return: list of vertices you need to visit from start vertex to finish vertex in right order.
"""
return self.result.get_path_to_vertex(finish_vertex) | Python |
__author__ = 'Алексей'
import heapq
class Dijkstra:
def __vertex_element_generator__(self, cmp):
class DijkstraVertex:
def __init__(self, vertex, path):
self.vertex = vertex
self.path = path
def __lt__(self, other):
return cmp(self.path, other.path)
return DijkstraVertex
def __init__(self, graph, start_vertex, start_value=0,
cmp=lambda w1, w2: w1 < w2,
sum_path_edge=lambda p, e: p + e.weight,
destination_by_edge=lambda edge: edge.destination):
"""
Class constructor get all needed information about graph and calculate all shortest paths
from start vertex with complexity O(E * log(V)), where V is number of vertices, E is total number of edges
Use get_path_values and get_path_to_vertex methods to get a result in needed form
:param graph: list of lists of edges. Edge is by default structure (weight, destination)
:param start_vertex: number of start vertex
:param start_value: weight of path from vertex to itself
:param cmp: cmp(weight1, weight2) Compares weights of two paths.
Returns true if weight1 < weight2; false otherwise
:param sum_path_edge: sum(path_weight, edge). Adds edge to a path
returns value of path_weight with added weight of edge.
edge is a same structure as you use in graph
:param destination_by_edge: returns incident vertex by edge
No need to override it if you use (weight, destination) structure of edge
"""
n = len(graph)
self.res = [None] * n
self.previous = [None] * n
self.res[start_vertex] = start_value
self.previous[start_vertex] = start_vertex
vertex_generator = self.__vertex_element_generator__(cmp)
heap = [vertex_generator(start_vertex, start_value)]
while len(heap) > 0:
element = heapq.heappop(heap)
current_vertex = element.vertex
current_path = element.path
if not self.res is None and cmp(self.res[current_vertex], current_path):
continue
for edge in graph[current_vertex]:
new_path = sum_path_edge(self.res[current_vertex], edge)
incident_vertex = destination_by_edge(edge)
if self.res[incident_vertex] is None or cmp(new_path, self.res[incident_vertex]):
self.res[incident_vertex] = new_path
self.previous[incident_vertex] = current_vertex
heapq.heappush(heap, vertex_generator(incident_vertex, new_path))
def get_path_values(self):
"""
:return: list of weights of shortest paths from start vertex to all. None for unreachable vertices
res[i] is value of shortest path from start vertex to vertex with number i
"""
return self.res
def get_path_to_vertex(self, finish_vertex):
"""
:param finish_vertex: number of vertex you want to know shortest path to
:return: list of vertices you need to visit from start vertex to finish vertex in right order.
None if there is no path
"""
if self.res[finish_vertex] is None:
return None
else:
path = []
i = finish_vertex
while self.previous[i] != i:
path.append(i)
i = self.previous[i]
path.append(i)
path.reverse()
return path | Python |
__author__ = 'Алексей'
from unittest import TestCase
from dijkstra import Dijkstra
from floyd import Floyd
import random
import copy
class Edge:
def __init__(self, destination, weight):
self.destination = destination
self.weight = weight
class BaseReleaseIntegrationTests(TestCase):
def test_manual_dijkstra(self):
graph = [[Edge(1, 2)], [Edge(2, 3)], [], []]
res = Dijkstra(graph, 0)
dist = res.get_path_values()
self.assertEqual(dist, [0, 2, 5, None])
path = res.get_path_to_vertex(2)
self.assertEqual(path, [0, 1, 2])
path = res.get_path_to_vertex(3)
self.assertEqual(path, None)
def test_manual_floyd(self):
matrix = [[0, 2, 100, None], [600, 0, 3, None], [10, 5, 0, None], [None, 3, None, 0]]
Floyd(matrix, 4)
self.assertEqual(matrix, [[0, 2, 5, None], [13, 0, 3, None], [10, 5, 0, None], [16, 3, 6, 0]])
def form_random_graph_with_matrix(self, graph, matrix, graph_size, max_edge_weight, diagonal_value,
generator=lambda max_val: random.randint(0, max_val)):
for i in range(graph_size):
matrix.append([])
graph.append([])
for j in range(graph_size):
if random.randint(0, 1) == 0:
matrix[i].append(None)
else:
matrix[i].append(generator(max_edge_weight))
graph[i].append(Edge(j, matrix[i][j]))
for i in range(graph_size):
matrix[i][i] = diagonal_value
def test_stress(self):
number_of_tests = 10
max_graph_size = 30
max_edge_weight = 100
for test_case in range(number_of_tests):
graph_size = random.randint(1, max_graph_size)
matrix = []
graph = []
self.form_random_graph_with_matrix(graph, matrix, graph_size, max_edge_weight, 0)
shortest_paths = copy.deepcopy(matrix)
Floyd(shortest_paths, graph_size)
for i in range(graph_size):
res = Dijkstra(graph, i)
dists = res.get_path_values()
for j in range(graph_size):
self.assertEqual(dists[j], shortest_paths[i][j])
path = res.get_path_to_vertex(j)
if path is None:
self.assertEqual(shortest_paths[i][j], None)
else:
actual_weight = sum([matrix[path[i]][path[i + 1]] for i in range(len(path) - 1)])
self.assertEqual(actual_weight, shortest_paths[i][j])
class MinimumMaxEdgeReleaseIntegrationTests(TestCase):
def test_manual_dijkstra(self):
graph = [[Edge(1, 2), Edge(2, 4)], [Edge(2, 3)], [Edge(0, 3)]]
res = Dijkstra(graph, 0, sum_path_edge=lambda p, e: max(p, e.weight))
dist = res.get_path_values()
self.assertEqual(dist, [0, 2, 3])
path = res.get_path_to_vertex(2)
self.assertEqual(path, [0, 1, 2])
def test_manual_floyd(self):
matrix = [[0, 1, 3], [4, 0, None], [None, 2, 0]]
Floyd(matrix, 3, operation=lambda a, b: max(a, b))
self.assertEqual([[0, 1, 3], [4, 0, 4], [4, 2, 0]], matrix)
def test_stress(self):
number_of_tests = 10
max_graph_size = 30
max_edge_weight = 1000
for test_case in range(number_of_tests):
graph_size = random.randint(1, max_graph_size)
matrix = []
graph = []
BaseReleaseIntegrationTests().form_random_graph_with_matrix(graph, matrix, graph_size, max_edge_weight, 0)
shortest_paths = copy.deepcopy(matrix)
Floyd(shortest_paths, graph_size, operation=lambda a, b: max(a, b))
for i in range(graph_size):
res = Dijkstra(graph, i, sum_path_edge=lambda p, e: max(p, e.weight))
dists = res.get_path_values()
for j in range(graph_size):
self.assertEqual(dists[j], shortest_paths[i][j])
path = res.get_path_to_vertex(j)
if i != j:
if path is None:
self.assertEqual(shortest_paths[i][j], None)
else:
actual_weight = max([matrix[path[i]][path[i + 1]] for i in range(len(path) - 1)])
self.assertEqual(actual_weight, shortest_paths[i][j])
else:
self.assertEqual(path, [i])
from ordinals import Ordinal
from ordinals import ordinal_cmp
from ordinals import ordinal_sum
from ordinals import get_random_ordinal
class OrdinalFunctorsTests(TestCase):
def test_sum(self):
a = Ordinal([(1, 1), (0, 1)]) # w + 1
b = Ordinal([(1, 1)]) # w
c = ordinal_sum(a, b) # w + 1 + w = w * 2
d = ordinal_sum(b, a) # w + w + 1 = w * 2 + 1
self.assertEqual(c.list, [(1, 2)])
self.assertEqual(d.list, [(1, 2), (0, 1)])
a = Ordinal([(3, 1), (1, 1), (0, 1)]) # w^3 + w + 1
b = Ordinal([(2, 1)]) # w^2
c = ordinal_sum(a, b) # w^3 + w + 1 + w^2 = w^3 + w^2
self.assertEqual(c.list, [(3, 1), (2, 1)])
a = Ordinal([(0, 0)]) # 0
b = Ordinal([(3, 1), (2, 2), (1, 3)]) # w^3 + w^2 * 2 + w * 3
c = ordinal_sum(a, b)
d = ordinal_sum(b, a)
self.assertEqual(c.list, b.list)
self.assertEqual(d.list, b.list)
q = [(i, i) for i in range(1, 99)]
q.reverse()
a = Ordinal(q) # w^99 * 99 + w^98 * 98 + ... + w
b = Ordinal([(100, 1)]) # w^100
c = ordinal_sum(a, b) # w^99 * 99 + w^98 * 98 + ... + 0 + w^100 = w^100
self.assertEqual(c.list, b.list)
def test_cmp(self):
a = Ordinal([(1, 2), (0, 1)]) # w * 2 + 1
b = Ordinal([(1, 1), (0, 1)]) # w + 1
self.assertEqual(ordinal_cmp(a, b), False)
self.assertEqual(ordinal_cmp(b, a), True)
self.assertEqual(ordinal_cmp(a, a, ), False)
a = Ordinal([(100, 1)]) # w^100
b = Ordinal([(99, 3000)]) # w^99 * 3000
self.assertEqual(ordinal_cmp(a, b), False)
self.assertEqual(ordinal_cmp(b, a), True)
a = Ordinal([(2, 1), (1, 1), (0, 1)]) # w^2 + w + 1
b = Ordinal([(2, 1), (0, 1)]) # w^2 + 1
self.assertEqual(ordinal_cmp(a, b), False)
self.assertEqual(ordinal_cmp(b, a), True)
def test_get_random_ordinal(self):
a = get_random_ordinal(100)
for i in range(len(a.list) - 1):
self.assertTrue(a.list[i][0] > a.list[i + 1][0])
self.assertTrue(a.list[i][1] > 0)
self.assertTrue(a.list[i + 1][1] > 0)
class EdgeOrdinalsReleaseIntegrationTests(TestCase):
def test_manual_dijkstra(self):
a = Ordinal([(0, 1)]) # 1
b = Ordinal([(1, 1)]) # w
c = Ordinal([(1, 1), (0, 1)]) # w + 1
d = Ordinal([(0, 0)]) # 0
graph = [[Edge(1, a), Edge(2, c)], [Edge(2, b)], []]
res = Dijkstra(graph, 0, start_value=d, cmp=ordinal_cmp, sum_path_edge=lambda p, e: ordinal_sum(p, e.weight))
dist = res.get_path_values()
self.assertEqual(dist, [d, a, b])
path = res.get_path_to_vertex(2)
self.assertEqual(path, [0, 1, 2])
def test_manual_floyd(self):
a = Ordinal([(0, 1)]) # 1
b = Ordinal([(1, 1)]) # w
c = Ordinal([(1, 1), (0, 1)]) # w + 1
d = Ordinal([(0, 0)]) # 0
matrix = [[d, a, c], [None, d, b], [None, None, d]]
Floyd(matrix, 3, operation=ordinal_sum, cmp=ordinal_cmp)
self.assertEqual(matrix, [[d, a, b], [None, d, b], [None, None, d]])
def test_stress(self):
number_of_tests = 10
max_graph_size = 10
max_edge_weight = 10
for test_case in range(number_of_tests):
graph_size = random.randint(1, max_graph_size)
matrix = []
graph = []
BaseReleaseIntegrationTests().form_random_graph_with_matrix(graph, matrix, graph_size,
max_edge_weight, Ordinal([(0, 0)]),
generator=get_random_ordinal)
shortest_paths = copy.deepcopy(matrix)
Floyd(shortest_paths, graph_size, operation=ordinal_sum, cmp=ordinal_cmp)
for i in range(graph_size):
res = Dijkstra(graph, i, start_value=Ordinal([(0, 0)]), cmp=ordinal_cmp,
sum_path_edge=lambda p, e: ordinal_sum(p, e.weight))
dists = res.get_path_values()
for j in range(graph_size):
self.assertEqual(dists[j], shortest_paths[i][j])
path = res.get_path_to_vertex(j)
if i != j:
if path is None:
self.assertEqual(shortest_paths[i][j], None)
else:
weights = [matrix[path[i]][path[i + 1]] for i in range(len(path) - 1)]
result = Ordinal([(0, 0)])
for ordinal in weights:
result = ordinal_sum(result, ordinal)
self.assertEqual(result, shortest_paths[i][j])
else:
self.assertEqual(path, [i])
from transport import PublicTransport
class PublicTransportTest(TestCase):
def test_manual_first(self):
problem = PublicTransport(4, 10 ** 9)
problem.add_edge(0, 1, 9, 10)
problem.add_edge(1, 2, 11, 12)
problem.add_edge(1, 2, 8, 9)
problem.add_edge(0, 2, 20, 30)
problem.add_edge(0, 3, 7, 30)
problem.solve(0, 9)
times = problem.get_times()
self.assertEqual(times, [9, 10, 12, None])
path = problem.get_path_to_vertex(2)
self.assertEqual(path, [0, 1, 2])
def test_manual_second(self):
problem = PublicTransport(6, 10 ** 9)
problem.add_edge(1, 2, 5, 10)
problem.add_edge(2, 4, 10, 15)
problem.add_edge(5, 4, 0, 17)
problem.add_edge(4, 3, 17, 20)
problem.add_edge(3, 2, 20, 35)
problem.add_edge(1, 3, 2, 40)
problem.add_edge(3, 4, 40, 45)
problem.solve(1, 0)
times = problem.get_times()
self.assertEqual(times, [None, 0, 10, 20, 15, None])
path = problem.get_path_to_vertex(3)
self.assertEqual(path, [1, 2, 4, 3])
def test_manual_third(self):
problem = PublicTransport(6, 10 ** 9)
problem.add_edge(1, 3, 1, 2)
problem.add_edge(3, 4, 2, 10)
problem.add_edge(4, 5, 10, 20)
problem.add_edge(5, 4, 10, 15)
problem.add_edge(4, 2, 15, 40)
problem.solve(1, 1)
times = problem.get_times()
self.assertEqual(times, [None, 1, 40, 2, 10, 20])
path = problem.get_path_to_vertex(2)
self.assertEqual(path, [1, 3, 4, 2]) | Python |
__author__ = 'Алексей'
def Floyd(matrix, size, operation = lambda a, b: a + b, cmp = lambda w1, w2: w1 < w2):
"""
Floyd algorithm to find shortest paths in graph
Complexity O(V ^ 3), where V is number of vertices in graph
:param matrix: adjacency matrix of graph.
matrix[i][j] - weight of edge between vertices i and j. None if there is no edge
at the end of algorithm turns into matrix of shortest paths. None if there is no path
:param size: size of graph
:param operation: f(a, b) function which returns weight of union of paths a and b
:param cmp: cmp(weight1, weight2) Compares weights of two paths.
Returns true if weight1 < weight2; false otherwise
"""
for k in range(size):
for i in range(size):
for j in range(size):
if not matrix[i][k] is None and not matrix[k][j] is None:
if matrix[i][j] is None or cmp(operation(matrix[i][k], matrix[k][j]), matrix[i][j]):
matrix[i][j] = operation(matrix[i][k], matrix[k][j]) | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.