1980
« on: May 10, 2011, 12:58:27 am »
My math teacher has decided to give us a test today/tomorrow. It is called the MAP if anyones heard of it. so my project is not due till Wenseday.
I have spent today touching it up. Now it will graph the equation for you using the terms you set for the multiplying hydra. It even adjusts its window accordingly
I added ina new module called grapher. It is a modified version of a pygame grapher program I downloaded.
Hydras.py main program
import sys
import os
import pygame
import random
from math import *
from pygame.locals import *
#Check to see if pygame is working right
#check font
if not pygame.font:
print 'Warning, fonts disabled'
#check sound
if not pygame.mixer:
print 'Warning, sound disabled'
minimum=12.17
maximum=17.43
def calc_amount(doubling):
newval=2
rate=log(2)/doubling
valueatpoint=[2,]
num=0
while newval<limit+.5:
newval=eval('2*'+str(e)+'**(num*rate)')
valueatpoint.append(newval)
num+=1
return valueatpoint
#functions to create our resources
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Cannot load image:', fullname
raise SystemExit, message
image = image.convert()
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
def load_sound(name):
class NoneSound:
def play(self): pass
if not pygame.mixer or not pygame.mixer.get_init():
return NoneSound()
fullname = os.path.join('data', name)
try:
sound = pygame.mixer.Sound(fullname)
except pygame.error, message:
print 'Cannot load sound:', fullname
raise SystemExit, message
return sound
class Hydra(pygame.sprite.Sprite):
"""creates a Hydra on screen"""
def __init__(self,parentx,parenty):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
randint=random.randint(1,100)
if randint%2==1:
self.image, self.rect = load_image('hydraA.bmp', -1)
else:
self.image, self.rect = load_image('hydraB.bmp', -1)
self.rect.topleft=parentx,parenty
self.xvel=1
self.yvel=1
self.xdir=1
self.ydir=1
def update(self):
if self.rect.left<1:
self.xdir=1
self.xvel=4
elif self.rect.top<1:
self.ydir=1
self.yvel=4
elif self.rect.right>screen.get_size()[0]:
self.xdir=-1
self.xvel=-4
elif self.rect.bottom>screen.get_size()[1]:
self.ydir=-1
self.yvel=-4
randint=random.randint(1,120)
if randint%6>3:
newpos=self.rect.move((self.xvel,self.yvel))
elif randint%6==3:
self.xvel=1*self.xdir
self.yvel=1*self.ydir
newpos=self.rect.move((self.xvel,self.yvel))
elif randint%6==2:
self.xvel=1*self.xdir
self.yvel=1*self.ydir
newpos=self.rect.move((self.xvel,self.yvel))
elif randint%6==1:
self.xvel=-1
self.yvel=0
newpos=self.rect.move((self.xvel,self.yvel))
elif randint%6==0:
self.xvel=0
self.yvel=-1
newpos=self.rect.move((self.xvel,self.yvel))
else:
newpos=self.rect.move((0,0))
self.rect=newpos
def begin():
curamount=2
newamount=2
turn = 0
rounds=0
while 1:
#use the clock
clock.tick(days)
turn+=1
if turn%5==0:
rounds+=1
if rounds>len(amount)-1:
print rounds
final = "It took the Hydra "+str(rounds)+" days to get to "+str(limit)+" from 2"
text = font.render(final, 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
pygame.time.delay(2500)
pygame.quit()
return
newamount=int(amount[rounds])
if newamount>curamount:
hydras.append(Hydra(random.randint(2,screen.get_size()[0]),random.randint(2,screen.get_size()[1])))
hydras[len(hydras)-1].add(allsprites)
curamount=newamount
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
return
elif event.type == KEYDOWN and event.key == K_ESCAPE:
pygame.quit()
return
allsprites.update()
#Draw Everything
screen.blit(background, (0, 0))
allsprites.draw(screen)
pygame.display.flip()
def prep():
font = pygame.font.Font(None, 40)
rate='0'
while 1:
clock.tick(15)
for event in pygame.event.get():
if event.type == QUIT:
return rate
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
return rate
elif event.key==K_KP0:
rate+='0'
elif event.key==K_KP1:
rate+='1'
elif event.key==K_KP2:
rate+='2'
elif event.key==K_KP3:
rate+='3'
elif event.key==K_KP4:
rate+='4'
elif event.key==K_KP5:
rate+='5'
elif event.key==K_KP6:
rate+='6'
elif event.key==K_KP7:
rate+='7'
elif event.key==K_KP8:
rate+='8'
elif event.key==K_KP9:
rate+='9'
elif event.key==K_KP_PERIOD:
rate+='.'
elif event.key==K_KP_ENTER:
return rate
text = font.render("Please type in on the numpad the apropriate speed and then press enter", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
def preps():
font = pygame.font.Font(None, 40)
rate='0'
while 1:
clock.tick(15)
for event in pygame.event.get():
if event.type == QUIT:
return rate
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
return rate
elif event.key==K_KP0:
rate+='0'
elif event.key==K_KP1:
rate+='1'
elif event.key==K_KP2:
rate+='2'
elif event.key==K_KP3:
rate+='3'
elif event.key==K_KP4:
rate+='4'
elif event.key==K_KP5:
rate+='5'
elif event.key==K_KP6:
rate+='6'
elif event.key==K_KP7:
rate+='7'
elif event.key==K_KP8:
rate+='8'
elif event.key==K_KP9:
rate+='9'
elif event.key==K_KP_PERIOD:
rate+='.'
elif event.key==K_KP_ENTER:
return rate
text = font.render("Please type on the numpad the apropriate days a second and press enter", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
def preeps():
font = pygame.font.Font(None, 40)
rate='0'
while 1:
clock.tick(15)
for event in pygame.event.get():
if event.type == QUIT:
return rate
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
return rate
elif event.key==K_KP0:
rate+='0'
elif event.key==K_KP1:
rate+='1'
elif event.key==K_KP2:
rate+='2'
elif event.key==K_KP3:
rate+='3'
elif event.key==K_KP4:
rate+='4'
elif event.key==K_KP5:
rate+='5'
elif event.key==K_KP6:
rate+='6'
elif event.key==K_KP7:
rate+='7'
elif event.key==K_KP8:
rate+='8'
elif event.key==K_KP9:
rate+='9'
elif event.key==K_KP_PERIOD:
rate+='.'
elif event.key==K_KP_ENTER:
return rate
text = font.render("Please type on the numpad the number of hydras to go to and press enter", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
if __name__ == "__main__":
#Initialize Everything
pygame.init()
font = pygame.font.Font(None, 24)
screen = pygame.display.set_mode((1100, 700))
pygame.display.set_caption('Hydra Attack')
pygame.mouse.set_visible(0)
hydraA=Hydra(random.randint(1,100),random.randint(1,100))
hydraB=Hydra(random.randint(101,200),random.randint(101,200))
#Create The Backgound
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
safebackground=background.copy()
#Display The Background
screen.blit(background, (0, 0))
pygame.display.flip()
#Prepare Game Objects
clock = pygame.time.Clock()
hydras=[hydraA,hydraB]
allsprites = pygame.sprite.RenderPlain((hydraA,hydraB))
doubling=float(prep())
background.blit(safebackground,(0, 0))
while doubling<minimum or doubling>maximum:
text = font.render("Please type in the number between "+str(minimum)+' and '+str(maximum)+'.', 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
pygame.time.delay(1500)
background.blit(safebackground,(0, 0))
doubling=float(prep())
background.blit(safebackground,(0, 0))
days=int(preps())
background.blit(safebackground,(0, 0))
while days<1 or days>15:
text = font.render("Please type in the number between 1 and 15.", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
pygame.time.delay(1500)
background.blit(safebackground,(0, 0))
days=int(preps())
background.blit(safebackground,(0, 0))
limit=int(preeps())
background.blit(safebackground,(0, 0))
while limit<5 or limit>250:
text = font.render("Please type in the number between 5 and 250.", 1, (10, 10, 10))
textpos = text.get_rect(centerx=background.get_width()/2,centery=background.get_height()/2)
background.blit(text, textpos)
screen.blit(background, (0, 0))
pygame.display.flip()
pygame.time.delay(1500)
background.blit(safebackground,(0, 0))
limit=int(preeps())
amount=calc_amount(doubling)
days=days*5
background.fill((0,0,255))
begin()
from Grapher import Grapher as grapher
grapher.main(doubling,amount,limit)
Grapher->Grapher.py Graphing program. Needs some work. It has a lot of unneeded code since I took out all input except exit and initial input from the main program.
print "The Grapher - v.2.0.0 - Ian Mallett - 2008 - F1 Help"
import pygame
from pygame.locals import *
import os, sys
import math, random
import Dialog
print "Required modules loaded!"
def sin(Theta): return math.sin(math.radians(Theta))
def cos(Theta): return math.cos(math.radians(Theta))
def tan(Theta): return math.tan(math.radians(Theta))
def csc(Theta): return 1.0/math.sin(math.radians(Theta))
def sec(Theta): return 1.0/math.cos(math.radians(Theta))
def cot(Theta): return 1.0/math.tan(math.radians(Theta))
def asin(Theta): return math.asin(math.radians(Theta))
def acos(Theta): return math.acos(math.radians(Theta))
def atan(Theta): return math.atan(math.radians(Theta))
def acsc(Theta): return 1.0/math.asin(math.radians(Theta))
def asec(Theta): return 1.0/math.acos(math.radians(Theta))
def acot(Theta): return 1.0/math.atan(math.radians(Theta))
def ln(Number): return math.log(Number)
def log10(Number): return math.log10(Number)
def log(Number, base): return math.log(Number, base)
def sqrt(Number): return math.sqrt(Number)
def cbrt(Number): return Number**(1.0/3.0)
def XUnitsToPixels(Units):
if Units <= Window[0][1] and Units >= Window[0][0]:
UnitDistanceLeft = Window[0][1] - Units
XUnitsHeight = abs(Window[0][0]-Window[0][1])
PixelsPerUnitX = Screen[0]/XUnitsHeight
PixelsLeft = UnitDistanceLeft*PixelsPerUnitX
PixelsRight = Screen[0] - PixelsLeft
return PixelsRight
def YUnitsToPixels(Units):
if Units <= Window[1][1] and Units >= Window[1][0]:
UnitDistanceDown = Window[1][1] - Units
YUnitsHeight = abs(Window[1][0]-Window[1][1])
PixelsPerUnitY = Screen[1]/YUnitsHeight
PixelsDown = UnitDistanceDown*PixelsPerUnitY
return PixelsDown
def BuildGraph(doubling):
print Equations
print "that was Build"
GraphSurface.fill((255,255,255))
UnitsX = float(abs(Window[0][0]-Window[0][1]))
UnitsPerXPixel = float(UnitsX)/float(Screen[0])
x = Window[0][0]
Colors = [(0,0,0),(100,0,0),(0,100,0),(0,0,100),(100,100,0)]
for XPos in range(Screen[0]):
ColorIndex = 0
for Equation in Equations:
try:
y = eval(Equation)
## if y < Screen[1] and y > 0:
xPos = XUnitsToPixels(x)
yPos = YUnitsToPixels(y)
xPos = int(xPos)
yPos = int(yPos)
GraphSurface.set_at((xPos,yPos),Colors[ColorIndex])
except ZeroDivisionError: #Divide by zero
pass #Let's not get into that.
except TypeError: #y is off the screen
pass #don't draw it.
except ValueError: #Domain Errors, and the like.
pass #don't try it.
ColorIndex += 1
x += UnitsPerXPixel
Draw()
def EquationsStringsRectify(Strings):
if Strings != None:
Data = []
for String in Strings:
if String != "":
String2 = ""
for Character in String:
if Character == '[': String2 += ('(')
elif Character == ']': String2 += (')')
elif Character == '{': String2 += ('(')
elif Character == '}': String2 += (')')
elif Character == '^': String2 += ('**')
else:
AcceptedLetters = [" ",".","0","1","2","3","4","5","6","7","8","9",
"+","-","*","/","(",")",
"a","b","c","e","g","i","l","n","o","p","q","r","s","t","x"]
for letter in AcceptedLetters:
if letter == Character:
String2 += (Character)
Data.append(String2)
global Equations, GraphSurface
Equations = Data
GraphSurface.fill((255,255,255))
pygame.display.flip()
else:
print "The Equations could not be set!"
def WindowStringsRectify(Strings):
if Strings != None:
Data = []
for String in Strings:
try:
Data.append(float(eval(String)))
except:
print "Window Dimensions could not be set!"
return
global Window, GraphSurface
Window = [ [Data[0],Data[1]], [Data[2],Data[3]] ]
GraphSurface.fill((255,255,255))
pygame.display.flip()
return
else:
print "Window Dimensions could not be set!"
def GetInput():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit; sys.exit()
if keystate[K_F1]:
print "F1"
Dialog.Info()
if keystate[K_F5]:
print "F5"
BuildGraph()
pygame.event.clear()
if keystate[K_F6]: EquationsStringsRectify( Dialog.Equations() )
if keystate[K_F7]: WindowStringsRectify ( Dialog.Window() )
def Draw():
keystate = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT or keystate[K_ESCAPE]:
pygame.quit
sys.exit()
surface.fill((255,255,255))
surface.blit(GraphSurface, (0,0))
print Equations
#x-axis
try: YPos = YUnitsToPixels(0); pygame.draw.line(surface, (0,0,100), (0,YPos-1), (Screen[0],YPos-1), 2)
except: pass #Not on screen
#y-axis
try: XPos = XUnitsToPixels(0); pygame.draw.line(surface, (0,0,100), (XPos-1,0), (XPos-1,Screen[1]), 2)
except: pass #Not on screen
#flip to screen
pygame.display.flip()
def main(doubling,amount,limit):
global Equations, surface, GraphSurface, Window, Screen, pi, e
pygame.init()
Equations = [u'2*e**(x*ln(2)/doubling)']
pi = 3.1415926535897932
e = 2.7182818284590452
pygame.display.set_caption("The Grapher - v.2.0.0 - Ian Mallett - 2008 - F1 Help")
#pygame.display.set_icon(pygame.image.load('Icon.png'))
Screen = [800,600]
surface = pygame.display.set_mode(Screen)
GraphSurface = pygame.Surface(Screen,SRCALPHA)
GraphSurface.fill((255,255,255))
Window = [[-1,len(amount)+1],[-1,limit]] #left x, right x, bottom y, top y
print "Screen created Successfully!"
pygame.time.delay(500)
BuildGraph(doubling)
while True:
Draw()