Import everything

This commit is contained in:
LingDong 2015-12-11 02:08:53 -05:00
parent 0f9bd58b0e
commit 81948a2e50
13 changed files with 2314 additions and 0 deletions

1005
creature.py Normal file

File diff suppressed because it is too large Load Diff

54
filter.py Normal file
View File

@ -0,0 +1,54 @@
import pygame
import sys
import math
import utilities as u
import copy
import random
import noise
import numpy as np
pygame.init()
def filter(array,t = 0):
twave = math.sin(t*0.0005+1)
for x in np.nditer(array[0],op_flags=['readwrite'],flags = ['external_loop']):
x[...]= (x-35+twave*45)/(1.3-twave*0.3)
for x in np.nditer(array[1],op_flags=['readwrite'],flags = ['external_loop']):
x[...] = (x-35+twave*44)/(1.3-twave*0.3)
for x in np.nditer(array[2],op_flags=['readwrite'],flags = ['external_loop']):
x[...] = (x-25+twave*25)/(1.3-twave*0.3)
if __name__ == "__main__":
screen = pygame.display.set_mode([640,320])
clock = pygame.time.Clock()
print screen.get_bitsize()
t = 0
while 1:
t += 100
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
array = []
screen.fill([200,200,200])
u.circle(screen,(100,100,100),[50,50],50)
clock.tick()
u.text(screen,10,10,"FPS: %.1f" % clock.get_fps(),(150,150,150))
array = [pygame.surfarray.pixels_red(screen),pygame.surfarray.pixels_green(screen),pygame.surfarray.pixels_blue(screen)]
filter(array,t)
#pygame.surfarray.blit_array(screen,array)
pygame.display.flip()

80
font.py Normal file
View File

@ -0,0 +1,80 @@
import pygame
import sys
import math
import utilities as u
import copy
import random
import noise
import numpy as np
pygame.init()
class GFont():
font = {
' ' : [],
'H' : [['l',0,0,0,4],['l',1.8,0,1.8,4],['l',0,2,1.8,2]],
'a' : [['a',0,2,2,0,360], ['l',2,3,2,4]],
'b' : [['a',0,2,2,0,360], ['l',0,0,0,3]],
'c' : [['a',0,2,2,30,330]],
'd' : [['a',0,2,2,0,360], ['l',2,0,2,4]],
'e' : [['a',0,2,2,0,340], ['l',0,3,2,3]],
'f' : [['a',0,0,2,30,180],['l',0,1,0,5], ['l',0,2,2,2]],
'g' : [['a',0,2,2,0,360], ['l',2,3,2,5], ['a',0,4,2,180,360]],
'h' : [['a',0,2,2,0,180], ['l',0,0,0,4], ['l',2,3,2,4]],
'i' : [['l',1,0,1,0.5], ['l',1,2,1,4]],
'j' : [['l',1,0,1,0.5], ['l',1,2,1,5], ['a',-1,4,2,180,360]],
'k' : [['l',0,0,0,4], ['l',2,2,0,3], ['l',0,3,2,4]],
'l' : [['l',0,0,0,3], ['a',0,2,2,180,360]],
'm' : [['a',0,2,2,0,90], ['l',0,2,0,4], ['l',2,3,2,4], ['l',1,2,1,4],['l',0,2,1,2]],
'n' : [['a',0,2,2,0,180], ['l',0,2,0,4], ['l',2,3,2,4]],
'o' : [['a',0,2,2,0,360]],
'p' : [['a',0,2,2,0,360], ['l',0,3,0,6]],
'q' : [['a',0,2,2,0,360], ['l',2,2,2,6]],
'r' : [['a',.5,2,2,90,180],['l',.5,2,.5,4]],
's' : [['a',0,2,2,0,180], ['a',0,3,2,180,360],['l',0,3,2,4]],
't' : [['l',0,0,0,3], ['a',0,2,2,180,360],['l',0,2,2,2]],
'u' : [['l',2,2,2,4], ['a',0,2,2,180,360],['l',0,2,0,3]],
'v' : [['l',0,2,1,4], ['l',2,2,1,4]],
'w' : [['l',0,2,0,4], ['a',0,2,2,270,360],['l',2,2,2,3], ['l',1,2,1,4],['l',0,4,1,4]],
'x' : [['l',0,2,2,4], ['l',0,4,2,2]],
'y' : [['l',2,2,2,5], ['a',0,2,2,180,360],['l',0,2,0,3],['a',0,4,2,180,360]],
'z' : [['l',0,2,2,2], ['l',2,2,0,4],['l',0,4,2,4]]
}
def __init__(self,size,width,color=(0,0,0)):
self.s = size
self.w = width
self.color = color
def drawStr(self,surf,st,x,y,size=1):
s = self
for i in range(0,len(st)):
sp = i*2.3
for f in self.font[st[i]]:
if f[0] == 'a':
pygame.draw.arc(surf,s.color, [f[1]*s.s*size+x+sp*s.s*size, f[2]*s.s*size+y, f[3]*s.s*size, f[3]*s.s*size],math.radians(f[4]),math.radians(f[5]),s.w)
if f[0] == 'l':
pygame.draw.line(surf,s.color, [f[1]*s.s*size+x+sp*s.s*size, f[2]*s.s*size+y],[f[3]*s.s*size+x+sp*s.s*size,f[4]*s.s*size+y],s.w)
if __name__ == "__main__":
screen = pygame.display.set_mode([640,320])
gfont = GFont(20,2)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
screen.fill([255,255,255])
gfont.drawStr(screen,"by lingdong",10,100)
pygame.display.flip()

56
foo.py Normal file
View File

@ -0,0 +1,56 @@
class IRCReplyModule(object):
activated=True
moduleHandlerResultList=None
moduleHandlerCommandlist=None
modulename=""
def __init__(self,modulename):
self.modulename = modulename
class SimpleHelloWorld(IRCReplyModule):
def __init__(self):
super(SimpleHelloWorld,self).__init__('hello world')
class A(SimpleHelloWorld):
def __init__(self):
super(A,self).__init__()
a = SimpleHelloWorld()
b = A()
"""
def Icon1():
global icon
color = (70,69,63)
icondeer = creature.Deer(240,0,color,7.6)
icondeer.yo = 240
icondeer.t = 50
icondeer.walk()
icon.fill(COLOR_KEY)
icondeer.draw(icon)
iconman = creature.Man(320,0)
iconman.yo=240
iconman.s=7
iconman.color=color
iconman.to(4,0,90,1)
iconman.to(5,0,-160,1)
iconman.to(6,0,-80,1)
iconman.to(7,0,0,1)
iconman.to(4,1,10,1)
iconman.to(8,0,110,1)
iconman.to(9,0,-110,1)
iconman.to(1,0,100,1)
iconman.to(0,0,30,1)
iconman.to(3,1,10,1)
iconman.to(8,1,20,1)
iconman.to(9,1,20,1)
iconman.to(10,1,25,1)
iconman.to(10,0,-15,1)
iconman.assets=["bow","arrow"]
iconman.draw(icon)
pygame.display.set_icon(icon)
"""

592
main.py Normal file
View File

@ -0,0 +1,592 @@
import pygame
import sys
import math
import thread
import random
import numpy
import string
import os
import noise
import tree
import creature
import utilities as u
import filter
import parse
import pattern
import particle
import font
import pygame._view
import settings
pygame.init()
settings.init()
size = width, height = 1280, 320
buff = 200
screen = pygame.display.set_mode([width/2,height+50])#,pygame.FULLSCREEN )
canvas = pygame.Surface([width/2,height])
pygame.display.set_caption("")
x = 0
treeDensity = 32
landDensity = 32
SPEED = 0.5
allloads = width/treeDensity
loaded = 0
Ls = [None]*4
Lrs = [None]*4
gamestart = False
COLOR_KEY = [255,0,255]
fullscreen = False
terrain = [0]*4
lspds = [0.1,0.2,0.5,1]
totalMade = [0]*4
scheme = [(70,69,63),(225,225,210)]
icon = pygame.Surface([512,512])
icon.set_colorkey(COLOR_KEY)
def Icon():
global icon, scheme
iconhorse = creature.Horse(200,0)
iconhorse.yo = 240
iconhorse.color = scheme[0]
iconhorse.s=7
iconman = creature.Man(250,0)
iconman.yo = 250
iconman.s=6
iconman.color = scheme[0]
iconman.mount(iconhorse)
for i in range(0,200):
iconman.animate()
iconhorse.animate()
icon.fill(scheme[1])
pygame.draw.rect(icon,scheme[0],[0,0,512,512],50)
iconman.draw(icon)
iconhorse.draw(icon)
pygame.display.set_icon(icon)
Icon()
#pygame.image.save(icon,"icon.png")
def makeBGLayer(n):
global loaded, allloads, terrain, lspds, totalMade
print "Making Background..."
l = pygame.Surface([width+buff*2,height])
l.fill(COLOR_KEY)
l.set_colorkey(COLOR_KEY)
if terrain[n] == 0:
treesum = width/(0.0+len(Ls)*treeDensity)
for i in range(0,int(treesum)):
thetree = [ random.choice([tree.tree2]),
random.choice([tree.tree1,tree.tree1,tree.tree2]),
random.choice([tree.tree1,tree.tree4,tree.tree3]),
random.choice([tree.tree1,tree.tree4,tree.tree3]) ][n]
thetree(l,random.random()*width+buff,height,(120-n*30)+random.randrange(-10,10))
loaded += 1
elif terrain[n] == 1:
treesum = (width/(0.0+len(Ls)*treeDensity))
for i in range(0,int(math.ceil(treesum/2.0))):
thetree = [ random.choice([tree.tree1,tree.tree3]),
random.choice([tree.tree1,tree.tree3]),
random.choice([tree.tree1,tree.tree3]),
random.choice([tree.tree1,tree.tree3]) ][n]
thetree(l,random.random()*width+buff,height,(120-n*30)+random.randrange(-10,10))
loaded += 2
if n != 3:
poly = []
poly.append([0,height])
for i in range(buff,width+buff,landDensity):
poly.append([i,height-makeLand(i*0.05,n*0.5,500-n*90)])
poly[1][1] = (poly[1][1]-height)/2.0+height
poly[-1][1] = (poly[-1][1]-height)/2.0+height
poly.append([width+buff*2,height])
pygame.draw.polygon(l,(210-n*20,210-n*20,210-n*20),poly)
totalMade[n] += 1
if totalMade[n]%int(lspds[n]*10) == 0:
terrain[n] = (terrain[n]+1) % 2
print(str(loaded)+"/"+str(allloads))
return l
def mt(LN,*args):
global Ls, Lrs, loaded, allloads
allloads = len(args)*(width/(len(Ls)*treeDensity))
loaded = 0
if LN == 1:
for a in args:
Ls[a] = makeBGLayer(a)
elif LN == 2:
for a in args:
Lrs[a] = makeBGLayer(a)
vine = pattern.Vine(0,160)
screen.fill([240,240,240])
def loadscreen():
while loaded < allloads-1 and not gamestart:
#screen.fill([240,240,240])
for i in range(2):
vine.grow(screen)
pygame.draw.rect(screen,(240,240,240),[0,170,100,20])
u.text(screen,10,height/2+15,"Loading... "+str(loaded)+"/"+str(allloads),(180,180,180))
#u.text(screen,100,height/2-14,"Loading... "+str(loaded)+"/"+str(allloads),(250,250,250))
#u.text(screen,100,height/2-15,"Loading... "+str(loaded)+"/"+str(allloads),(180,180,180))
u.line(screen,(180,180,180),[0,height/2],[(float(loaded)/allloads)*width/2,height/2],1)
#u.line(screen,(250,250,250),[0,height/2+1],[(float(loaded)/allloads)*width/2,height/2+1],1)
pygame.display.flip()
locs = [0,0,0,0]
locrs = [width,width,width,width]
clock = pygame.time.Clock()
horse = creature.Horse(100,0)
horse.yo = height
horse.s = 1
horse.aspd = 0.09
horse.color = (140,140,140)
birds = []
deers = []
cranes = []
arrows = []
man = creature.Man(150,0)
man.yo = height
man.s = 0.7
man.color = (140,140,140)
man.arrows = arrows
man.walk()
pctrl = particle.ParticleCtrl()
def makeBirds(n):
global birds
for i in range(0,n):
b = creature.Bird(random.randrange(width/2+10,width/2+60),0)
b.s = 0.5
b.aspd = 0.3
b.yo = height
b.color = (140,140,140)
b.dir = random.choice([1,-1])
birds.append(b)
def makeDeers(n):
global deers
for i in range(0,n):
r = random.randrange(-5,5)
deer = creature.Deer(width/2+landDensity+50+r*10,0,color = (160+r,160+r,160+r))
deer.yo = height
deer.s = 1.1
deer.aspd = 0.15
deers.append(deer)
def makeCranes(n):
global cranes
for j in range(0,n):
r = random.randrange(-5,5)
crane = creature.Crane(width/2+landDensity+random.randrange(0,200),0)
crane.color = (180+r,180+r,180+r)
crane.yo = height-150-120*random.random()
crane.s = 0.5+random.random()*0.2
crane.aspd = 0.05
crane.dir = -1
crane.t = (j/5.0)*200
cranes.append(crane)
makeBirds(10)
def makeLand(n,m=0,maxheight = 20):
return max(noise.noise(n*0.1,m*0.5)*maxheight,2)-2
#landDensity = 64 #inited before!
land = [0]*(((width)/2)/landDensity+2)
landloc = 0
landni = 0
for landni in range(0,len(land)):
land[landni]=makeLand(landni,maxheight=20+terrain[3]*120)
def onLandY(instx):
if x== 0:ep = -0.01
else:ep = 0.01
lastAlt = land[int(((x-ep)%landDensity + instx)//landDensity)]
nextAlt = land[int(((x-ep)%landDensity + instx)//landDensity)+1]
return lastAlt+(nextAlt-lastAlt)*((((x-ep)%landDensity + instx)%landDensity)/landDensity)
gfont = font.GFont(10,2,)
box = pygame.Surface([240,50])
box.fill([0,0,0])
box.set_alpha(50,pygame.RLEACCEL)
keyseq = []
commandlist = ["set time","set speed","spawn","fullscreen","restart","set terrain","set tree density","eval"]
T = 0
def exe(command):
global T, SPEED,fullscreen,terrain,totalMade,landni,land, treeDensity
try:
com = parse.parse(command.split("-")[0],commandlist)[0]
par = command.split("-")[1:]
for i in range(0,len(par)):
par[i] = par[i].strip()
if com == "set time":
T = int(par[0])
settings.msg = ["TIME SET TO "+par[0]+".",settings.msgt]
elif com == "set speed":
SPEED = float(par[0])
settings.msg = ["SPEED SET TO "+par[0]+".",settings.msgt]
elif com == "restart":
#os.execv(__file__, sys.argv)
python = sys.executable
os.execl(python, python, * sys.argv)
elif com == "fullscreen":
if len(par) == 0:
fullscreen = not fullscreen
else:
fullscreen = [False,True][int(par[0])]
if fullscreen:
pygame.display.set_mode([width/2,height+50],pygame.FULLSCREEN)
else:
pygame.display.set_mode([width/2,height+50])
pygame.display.set_caption("")
settings.msg = ["FULLSCREEN "+["OFF.","ON."][fullscreen],settings.msgt]
elif com == "spawn":
animal = par[0]
xn = int(par[1])
if animal == "bird":
makeBirds(xn)
elif animal == "deer":
makeDeers(xn)
elif animal == "crane":
makeCranes(xn)
elif animal == "unicorn":
for i in range(xn):
r = random.randrange(-5,5)
unicorn = creature.Unicorn(width/2+landDensity+50+r*10,0)
unicorn.yo = height
unicorn.s = 1.0
unicorn.aspd = 0.2
unicorn.dir = -1
unicorn.spd = 2
deers.append(unicorn)
settings.msg = [str(xn)+" "+animal+" SPAWNED.",settings.msgt]
elif com == "set terrain":
#settings.msg = ["PLEASE WAIT",settings.msgt]
if int(par[0]) > 1:
raise
terrain = [int(par[0])]*4
totalMade = [0]*4
for landni in range(0,len(land)):
land[landni]=makeLand(landni,maxheight=20+terrain[3]*120)
mt(1, 3,2,1,0)
mt(2, 3,2,1,0)
settings.msg = ["TERRAIN SET TO "+par[0]+".",settings.msgt]
elif com == "set tree density":
print terrain
terrain = [terrain[3]]*4
totalMade = [0]*4
for landni in range(0,len(land)):
land[landni]=makeLand(landni,maxheight=20+terrain[3]*120)
treeDensity = int(width/float(par[0]))
mt(1, 3,2,1,0)
mt(2, 3,2,1,0)
elif com == "eval":
settings.msg = [str(eval(par[0])),settings.msgt]
except Exception, e:
print "%s" % e
settings.msg = ["COMMAND NOT EXECUTED.",settings.msgt]
def main():
global x, lspds, locs, gamestart, landloc, landni, fullscreen, birds, terrain, keyseq, T
gamestart = True
showconsole = False
while 1:
canvas.fill([240,240,240])
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
man.keyupdowncontrol(event,horse)
if event.type == pygame.KEYDOWN:
if showconsole:
k = pygame.key.name(event.key)
#print k
if k == "return":
exe("".join(keyseq))
showconsole = False
elif k == "space":
keyseq.append(" ")
elif k == "-":
keyseq.append("-")
elif len(k) == 1:
keyseq.append(k)
elif event.key == pygame.K_BACKSPACE :
if len(keyseq) > 0:
keyseq.pop()
if event.key == pygame.K_SLASH:
showconsole = not showconsole
if showconsole:
settings.msg = ["CONSOLE READY.",settings.msgt]
else:
settings.msg = ["",settings.msgt]
keyseq = []
if event.key == pygame.K_f and not showconsole:
fullscreen = not fullscreen
if fullscreen:
pygame.display.set_mode([width/2,height+50],pygame.FULLSCREEN)
else:
pygame.display.set_mode([width/2,height+50])
pygame.display.set_caption("")
#print(pygame.key.get_pressed())
for i in range(0,len(Ls)):
if i == 2:
for c in cranes:
c.draw(canvas)
if i == 3:#+terrain:
"""
gfont.s = 10
gfont.w = 1
gfont.color = (120,120,120)
gfont.drawStr(canvas,"Hermit",300-x*0.7,260)
gfont.s = 5
gfont.w = 1
gfont.color = (120,120,120)
gfont.drawStr(canvas,"by lingdong",450-x*0.7,280)
"""
for d in deers:
d.draw(canvas)
horse.draw(canvas)
man.draw(canvas)
for a in arrows:
a.draw(canvas)
for b in birds:
b.simpDraw(canvas)
pctrl.draw(canvas)
if Ls[i] != None:
canvas.blit(Ls[i],[locs[i]-x*lspds[i]-buff,0])
if locs[i]-x*lspds[i] < -width-buff:
locs[i] += width*2
Ls[i] = None
thread.start_new_thread(mt,(1, i))
if Lrs[i] != None:
canvas.blit(Lrs[i],[locrs[i]-x*lspds[i]-buff,0])
if locrs[i]-x*lspds[i] < -width-buff:
locrs[i] += width*2
Lrs[i] = None
thread.start_new_thread(mt,(2, i))
clock.tick()
T += 1
u.text(canvas,10,10,"FPS: %.1f" % clock.get_fps(),(160,160,160))
man.keyholdcontrol()
if (0 or pygame.key.get_pressed()[pygame.K_RIGHT]) and not man.status[0].endswith("ing"):
for a in arrows:
a.x -= SPEED
for b in birds:
b.x -= SPEED
for p in pctrl.particles:
p.x -= SPEED
for d in deers:
d.x-=SPEED*0.5
for c in cranes:
c.x-=SPEED
x+=SPEED
horse.walk()
if random.random()<0.0005:
makeBirds(random.randrange(6,12))
if random.random() < 0.0005 and terrain[3] == 0:
makeDeers(1)
if random.random() < 0.001 and terrain[3] == 1:
makeCranes(random.randrange(1,5))
else:
horse.rest()
u.polygon(canvas,(130,130,130),[[0,height]]+[[landloc-x+i*landDensity,height-land[i]] for i in range(0,len(land))]+[[width/2,height]])
if -x+landloc<-landDensity:
landni += 1
land.append(makeLand(landni,maxheight=20+terrain[3]*120))
land.pop(0)
landloc += landDensity
man.yo = height-20-onLandY(man.x)
horse.yo = height-30-onLandY(horse.x)
for d in deers:
d.yo = height-30-onLandY(max(min(d.x,width/2),0))
if noise.noise(T*0.001,deers.index(d))<0.5:
d.x -= d.spd
d.walk()
else:
d.rest()
if d.x<-100:
deers.remove(d)
for c in cranes:
c.x -= 2*c.s
c.fly()
if c.x<-100:
cranes.remove(c)
for a in arrows:
#a.fly()
#print(a.x)
if a.x > width/2 or a.x < -10 or height-onLandY(a.x) >= a.calcHead()[1]:
a.fly()
else:
a.v[0] = 0
a.v[1] = 0
a.flicker = 0
if a.x > width/2:
arrows.remove(a)
for b in birds:
if b.health > 0:
if ((abs(man.x - b.x) < 100 and random.random()<0.05) or random.random()<0.0002) and b.on == 0:
b.on = 1
ra = math.pi/20.0+random.random()*math.pi/6.0*2.1
rl = random.choice([3,4,5])
b.v=[rl*math.cos(ra),-rl*math.sin(ra)]
if b.on == 1:
b.simpFly()
if abs(man.x - b.x) > 160 and random.random()<1:
b.v[1] = min(b.v[1]+0.05,0.4)
if b.y >= 2:
b.on = 0
else:
b.rest()
if 0 < b.x < width/2:
b.yo=height-3-onLandY(b.x)
for a in arrows:
#print(u.dist(a.x,a.y,b.x,b.y+b.yo))
if u.dist(a.x,a.y,b.x,b.y+b.yo) < b.s*30 and a.v[0] > 0:
a.v[0]/= 2
b.arrow = a
b.health = 0
b.x = a.calcFeather()[0]
b.y = a.calcFeather()[1] - b.yo
for i in range(0,12):
pctrl.particles.append(particle.Particle(a.calcFeather()[0],a.calcFeather()[1],[8*(random.random()-0.5),8*(random.random()-0.3)]))
if b.x<0 or b.x>width or b.yo<0:
birds.remove(b)
else:
b.fall()
pctrl.emit()
man.animate()
horse.animate()
#array = []
#screen.unlock()
screen.blit(canvas,[0,0])
reflection = canvas#pygame.transform.flip(canvas,False,True)
pygame.draw.rect(screen,(180,180,180),[0,height,width/2,50])
for i in range(0,2*(screen.get_height()-height),2):
screen.blit(reflection,[(math.sin(i*0.5))*i*0.5+(noise.noise(pygame.time.get_ticks()*0.001,i*0.2)-0.5)*20,height+i-1],(0,height-i,width/2,1))
if settings.msg[0] != "":
screen.blit(box,[5,height+33-showconsole*20])
u.text(screen,10,height+35-showconsole*20,settings.msg[0],(240,240,240))
if settings.msg[1] <= 0 and not showconsole:
settings.msg[0] = ""
else:
settings.msg[1]-=1
if showconsole:
input = "".join(keyseq)
u.text(screen,10,height+25,">"+input.lower(),(240,240,240))
u.text(screen,10,height+35," "+" | ".join(parse.parse(input.split("-")[0],commandlist)[:3]),(240,240,240))
array = [pygame.surfarray.pixels_red(screen),pygame.surfarray.pixels_green(screen),pygame.surfarray.pixels_blue(screen)]
filter.filter(array,T)
array = []
#icon.blit(screen,[0,0],[0,0,512,512])
#pygame.display.set_icon(icon)
pygame.display.flip()
#t1 = thread.start_new_thread( loadscreen, () )
#mt(1, 3,2,1,0)
t1 = thread.start_new_thread( mt, (1, 3,2,1,0) )
loadscreen()
while loaded<allloads:
pass
print('loaded')
treeDensity = 16
t3 = thread.start_new_thread(mt, (2, 3,2,1,0))
main()

105
noise.py Normal file
View File

@ -0,0 +1,105 @@
#Perlin Noise
#Based on Javascript from p5.js (https://github.com/processing/p5.js/blob/master/src/math/noise.js)
#Ported to Python by Lingdong Huang
import math
import random
PERLIN_YWRAPB = 4
PERLIN_YWRAP = 1<<PERLIN_YWRAPB
PERLIN_ZWRAPB = 8
PERLIN_ZWRAP = 1<<PERLIN_ZWRAPB
PERLIN_SIZE = 4095
perlin_octaves = 4
perlin_amp_falloff = 0.5
def scaled_cosine(i):
return 0.5*(1.0-math.cos(i*math.pi));
perlin = None
def noise(x,y=0,z=0):
global perlin
if perlin == None:
perlin = []
for i in range(0,PERLIN_SIZE+1):
perlin.append(random.random())
if x<0:x=-x
if y<0:y=-y
if z<0:z=-z
xi,yi,zi = int(x),int(y),int(z)
xf = x-xi
yf = y-yi
zf = z-zi
rxf = ryf = None
r = 0
ampl = 0.5
n1 = n2 = n3 = None
for o in range(0,perlin_octaves):
of=xi+(yi<<PERLIN_YWRAPB)+(zi<<PERLIN_ZWRAPB)
rxf = scaled_cosine(xf)
ryf = scaled_cosine(yf)
n1 = perlin[of&PERLIN_SIZE]
n1 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n1)
n2 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]
n2 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n2)
n1 += ryf*(n2-n1)
of += PERLIN_ZWRAP
n2 = perlin[of&PERLIN_SIZE]
n2 += rxf*(perlin[(of+1)&PERLIN_SIZE]-n2)
n3 = perlin[(of+PERLIN_YWRAP)&PERLIN_SIZE]
n3 += rxf*(perlin[(of+PERLIN_YWRAP+1)&PERLIN_SIZE]-n3)
n2 += ryf*(n3-n2)
n1 += scaled_cosine(zf)*(n2-n1)
r += n1*ampl
ampl *= perlin_amp_falloff
xi<<=1
xf*=2
yi<<=1
yf*=2
zi<<=1
zf*=2
if (xf>=1.0): xi+=1; xf-=1
if (yf>=1.0): yi+=1; yf-=1
if (zf>=1.0): zi+=1; zf-=1
return r
def noiseDetail(lod, falloff):
if lod>0:perlin_octaves=lod
if falloff>0:perlin_amp_falloff=falloff
class LCG():
def __init__(self):
self.m = 4294967296.0
self.a = 1664525.0
self.c = 1013904223.0
self.seed = self.z = None
def setSeed(self,val=None):
self.z = self.seed = (math.random()*self.m if val == None else val) >> 0
def getSeed(self):
return self.seed
def rand(self):
self.z = (self.a * self.z + self.c) % self.m
return self.z/self.m
def noiseSeed(seed):
lcg = LCG()
lcg.setSeed(seed)
perlin = []
for i in range(0,PERLIN_SIZE+1):
perlin.append(lcg.rand())

42
parse.py Normal file
View File

@ -0,0 +1,42 @@
def parse(command,allcommands):
allcommands.sort()
results = []
if command == "":
return results
command = command.strip()
for c in allcommands:
if "".join([x[0] for x in c.split(" ")])==command:
if not c in results:
results.append(c)
for c in allcommands:
if c.startswith(command):
if not c in results:
results.append(c)
for c in allcommands:
if (not False in [c.split(" ")[min(i,len(c.split(" "))-1)].startswith(command.split(" ")[i]) for i in range (len(command.split(" ")))]):
if not c in results:
results.append(c)
for c in allcommands:
if "".join(c.split(" ")).startswith(command):
if not c in results:
results.append(c)
for c in allcommands:
if "".join([x[0] for x in c.split(" ")]).startswith(command):
if not c in results:
results.append(c)
for c in allcommands:
for d in c.split(" "):
if d.startswith(command):
if not c in results:
results.append(c)
for c in allcommands:
if command in "".join(c.split(" ")[i][0] for i in range(0,len(c.split(" ")))):
if not c in results:
results.append(c)
return results
if __name__ == "__main__":
while 1:
print(parse(raw_input("?"),[
"kill horse","kill dog","khan","kill cat","open door","eat meat","restore full health","roast full chicken","raw fury","eat shit","eat mother","kill motherfucker"]))

41
particle.py Normal file
View File

@ -0,0 +1,41 @@
import pygame
import sys
import math
import utilities as u
import copy
import random
import noise
pygame.init()
class Particle():
def __init__(self,x,y,v):
self.x = x
self.y = y
self.v = v
self.g = 0.2
self.color = (100,100,100)
self.s = 1
self.life = 50
def fly(self):
self.x += self.v[0]
self.y += self.v[1]
self.v[1] += self.g
self.life -= 1
def draw(self,surf):
u.circle(surf,self.color,[self.x,self.y],self.s/2)
class ParticleCtrl():
def __init__(self):
self.particles = []
def emit(self):
for p in self.particles:
p.fly()
if p.life <= 0:
self.particles.remove(p)
def draw(self,surf):
for p in self.particles:
p.draw(surf)

78
pattern.py Normal file
View File

@ -0,0 +1,78 @@
import pygame
import sys
import math
import utilities as u
import copy
import random
import noise
pygame.init()
class Dot():
def __init__(self,x,y,a,r,adir=1,color = (180,180,180)):
self.x = x
self.y = y
self.a = a
self.adir = adir
self.r = r
self.s = 1
self.color = color
self.t = 0
self.f = 0
def crawl(self):
self.x += self.s*math.cos(self.a)
self.y -= self.s*math.sin(self.a)
self.t += 1
if self.t > self.r * 7:
try:
self.a += 0.0005*self.t**2*self.adir/self.r**3
except:pass
else:
pass
#self.a+=1*(noise.noise(self.t*0.01)-0.5)
#self.r -= 1
def draw(self,surf):
#u.circle(surf,(245,245,245),[self.x,self.y+1],self.s/2)
u.circle(surf,self.color,[self.x,self.y],self.s/2)
class Vine():
def __init__(self,x,y,color = (180,180,180)):
self.color =color
self.dots = []
self.dots.append(Dot(x,y,0,10,color = self.color))
def grow(self,surf):
for d in self.dots:
d.crawl()
d.draw(surf)
if d.t == int(d.r * 7) and random.random() < 0.5 and d.r > 2:
if len(self.dots) < 40:
self.dots.append(Dot(d.x,d.y,0,d.r*(0.5+0.7*random.random()),-d.adir,self.color))
if random.random() < 0.02 and d.r*50 > d.t > d.r * 6 and d.f < d.r/5 and d.r > 3:
if len(self.dots) < 40:
self.dots.append(Dot(d.x,d.y,0.5*(random.random()-0.5),d.r*(0.5+0.6*random.random()),-d.adir,self.color))
d.f += 1
if abs(d.t) > d.r*50:
self.dots.remove(d)
if len(self.dots) < 1:
self.dots.append(Dot(d.x,d.y,0.5*(random.random()-0.5),d.r*(0.5+0.6*random.random()),-d.adir,self.color))
if __name__ == "__main__":
screen = pygame.display.set_mode([640,320])
screen.fill([240,240,240])
vine = Vine(0,160)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
u.text(screen,20,160+5,"Loading... ",(180,180,180))
#screen.fill([240,240,240])
vine.grow(screen)
pygame.display.flip()

51
projectile.py Normal file
View File

@ -0,0 +1,51 @@
import pygame
import sys
import math
import utilities as u
import copy
import random
import noise
pygame.init()
class Arrow():
def __init__(self,x,y):
self.color = (150,150,150)
self.x=x
self.y=y
self.l=20
self.a=0
self.spd=10
self.v=[self.spd,0]
self.g=0.2
#self.body = None
#self.state = 0
self.flicker = 1
def calcA(self):
return math.degrees(math.atan2(self.v[1],self.v[0]))
def calcV(self):
return [self.spd*math.cos(math.radians(self.a)), -self.spd*math.sin(math.radians(self.a))]
def calcHead(self):
return self.x+self.l*math.cos(math.radians(self.a)), self.y+self.l*math.sin(math.radians(self.a))
def calcFeather(self):
return self.x+self.l*0.3*math.cos(math.radians(self.a)), self.y+self.l*0.3*math.sin(math.radians(self.a))
def draw(self,surf):
u.line(surf,[245,245,245],[self.x,self.y],self.calcFeather(),3)
u.line(surf,self.color,[self.x,self.y],self.calcHead(),random.randrange(0,2)*self.flicker+1)
def fly(self):
self.a=self.calcA()
self.x += self.v[0]
self.y += self.v[1]
self.v[1]+=self.g

5
settings.py Normal file
View File

@ -0,0 +1,5 @@
def init():
global msg,msgt
msg = ["",0]
msgt = 50

169
tree.py Normal file
View File

@ -0,0 +1,169 @@
import pygame
import sys
import math
import random
import utilities as u
def drawTree(**p):
if p['depth'] < p['maxdepth']:
if p['height'] <1:return
dep = p['depth']
p['width'] *= p['dwidth'](dep)
x0 = p['x']+math.cos(p['angle'])*p['trunk']
y0 = p['y']-math.sin(p['angle'])*p['trunk']
u.line(p['surf'],p['color'],[p['x'],p['y']],[x0,y0],p['width'])
p['width'] *= p['dwidth'](dep)
a1 = p['angle']-p['opening']*p['dopening'](dep)
a2 = p['angle']+p['opening']*p['dopening'](dep)
h1 = p['height'] * p['dheight'](dep)
x1 = x0+math.cos(a1)*h1
y1 = y0-math.sin(a1)*h1
h2 = p['height'] * p['dheight'](dep)
x2 = x0+math.cos(a2)*h2
y2 = y0-math.sin(a2)*h2
#u.text(p['surf'],x1,y1,str(dep),(0,150,0))
#u.text(p['surf'],x2,y2,str(dep),(0,150,0))
u.line(p['surf'],p['color'],[x0,y0],[x1,y1],p['width'])
u.line(p['surf'],p['color'],[x0,y0],[x2,y2],p['width'])
p['trunk'] *= p['dtrunk'](dep)
p['depth'] += .5
p['x'],p['y'],p['height'],p['angle'] = x1,y1,h1,a1-p['dangle'](dep)
drawTree(**p)
p['depth'] += .5
p['x'],p['y'],p['height'],p['angle'] = x2,y2,h2,a2+p['dangle'](dep)
drawTree(**p)
else:
return
def tree1(surf,x,y,shade=0):
drawTree(surf = surf,
x = x,
y = y,
angle = math.pi/2,
dangle = lambda dep: -(random.random()-0.5)*math.pi/3,
trunk = 50,
dtrunk = lambda dep: 0.8*random.random(),
width = 8,
dwidth = lambda dep: random.random()*0.2+0.8,
height = 50,
dheight = lambda dep: random.random()*0.6+0.4,
opening = math.pi/6,
dopening = lambda dep: 0.8 + random.random()*0.5,
color = (100+shade,100+shade,100+shade),
depth = 0,
maxdepth = 10
)
def tree2(surf,x,y,shade=0):
drawTree(surf = surf,
x = x,
y = y,
angle = math.pi/2,
dangle = lambda dep: 0,
trunk = 20,
dtrunk = lambda dep: 0.9,
width = 10,
dwidth = lambda dep: random.random()*0.3+0.7,
height = 100,
dheight = lambda dep: random.random()*0.6+0.3,
opening = math.pi/3,
dopening = lambda dep: ((dep*2)%2)*(0.8+random.random()*0.4),#*(dep<2),
color = (100+shade,100+shade,100+shade),
depth = 0,
maxdepth = 12
)
def tree3(surf,x,y,shade=0):
drawTree(surf = surf,
x = x,
y = y,
angle = math.pi/2,
dangle = lambda dep: -(random.random()-0.5)*math.pi/3,
trunk = 0,
dtrunk = lambda dep: 0.8*random.random(),
width = 6,
dwidth = lambda dep: random.random()*0.2+0.8,
height = 100,
dheight = lambda dep: random.random()*0.7+0.2,
opening = math.pi/3,
dopening = lambda dep: random.random()*2-1,
color = (100+shade,100+shade,100+shade),
depth = 0,
maxdepth = 10
)
def tree4(surf,x,y,shade=0):
drawTree(surf = surf,
x = x,
y = y,
angle = math.pi/2,
dangle = lambda dep: (-math.pi/6)+((random.random()-0.5)*(dep))*2,
trunk = 50,
dtrunk = lambda dep: 0.8*random.random(),
width = 8,
dwidth = lambda dep: random.random()*0.2+0.8,
height = 50,
dheight = lambda dep: random.random()*0.5+0.5,
opening = math.pi/5,
dopening = lambda dep: 0.8 + random.random()*0.5*dep*2,
color = (100+shade,100+shade,100+shade),
depth = 0,
maxdepth = 10
)
if __name__ == "__main__":
screen = pygame.display.set_mode([800,500])
screen.fill([240,240,240])
for i in range(0,4):
[tree1,tree2,tree3,tree4][i](screen,100+i*200,500,30)
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key==pygame.K_SPACE:
print event.key==pygame.K_SPACE
screen.fill([240,240,240])
for i in range(0,4):
[tree1,tree2,tree3,tree4][i](screen,100+i*200,500,30)
pygame.display.flip()

36
utilities.py Normal file
View File

@ -0,0 +1,36 @@
import pygame
import math
pygame.init()
sysf = pygame.font.SysFont(pygame.font.get_default_font(),16)
def lmap(f,l):
return list(map(f,l))
def toInt(n):
return int(n)
def line(surface,color,start_pos,end_pos,width=1):
return pygame.draw.line(surface,color,lmap(toInt,start_pos),lmap(toInt,end_pos),int(math.ceil(width)))
def polygon(surface,color,pointlist,width=0):
#print pointlist
return pygame.draw.polygon(surface,color,lmap(lambda l: lmap(toInt, l),pointlist),int(round(width)))
def circle(surface,color,pos,radius,width=0):
return pygame.draw.circle(surface,color,lmap(toInt,pos),int(radius),int(round(width)))
def text(surf,x,y,t,color=(0,0,0),Font=sysf):
fs = Font.render(t,False,color)
surf.blit(fs,[x,y])
def triwave(t,a=2*math.pi):
t = float(t)
a = float(a)
return (2/a)*(t-a*int(t/a+0.5))*(-1)**int(t/a+0.5)
def trapwave(x):
return ((8*math.sqrt(2))/(math.pi*math.pi)) * (math.sin(x)+math.sin(3*x)/9.0)
def dist(x1,y1,x2,y2):
return math.sqrt((x1-x2)**2+(y1-y2)**2)