commit 12135f9a60d91500d518e8e8099297659448134d Author: bendtherules Date: Wed Feb 5 10:44:04 2014 +0530 All the previous files diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..412eeda --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9d6bd9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,215 @@ +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg diff --git a/I'm the villian/a.png b/I'm the villian/a.png new file mode 100644 index 0000000..c287ea3 Binary files /dev/null and b/I'm the villian/a.png differ diff --git a/I'm the villian/a.py b/I'm the villian/a.py new file mode 100644 index 0000000..dfa0e73 --- /dev/null +++ b/I'm the villian/a.py @@ -0,0 +1,14 @@ +import math; +import pygame; +from pygame.locals import * +pygame.init() +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Wtf is this??") +#c=pygame.time.Clock(); +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); + + #c.tick(); \ No newline at end of file diff --git a/I'm the villian/ball.bmp b/I'm the villian/ball.bmp new file mode 100644 index 0000000..297a095 Binary files /dev/null and b/I'm the villian/ball.bmp differ diff --git a/I'm the villian/cam.py b/I'm the villian/cam.py new file mode 100644 index 0000000..32b8b60 --- /dev/null +++ b/I'm the villian/cam.py @@ -0,0 +1,5 @@ +from SimpleCV import Camera, Display, Image; +cam=Camera(); +disp=Display(); +img=cam.getImage(); +img.sample_points(disp); \ No newline at end of file diff --git a/I'm the villian/class_definition(permanent).py b/I'm the villian/class_definition(permanent).py new file mode 100644 index 0000000..e5dbd98 --- /dev/null +++ b/I'm the villian/class_definition(permanent).py @@ -0,0 +1,84 @@ +# all imports +import math; +import pygame; +from pygame.locals import * + +# init +pygame.init() + +# setting display +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Wtf is this??") + +#custom image-loading function +def load_image(self,sprite_filename=None,alpha=None): + '''Load correct image with convert calls''' + if sprite_filename!=None: + self.spr=pygame.image.load(sprite_filename); + if alpha==None: + self.spr=self.spr.convert(); + elif alpha==1: + self.spr=self.spr.convert(); + self.spr.set_colorkey(self.spr.get_at((self.spr.get_width()-1,self.spr.get_height()-1))); + elif alpha==2: + self.spr=self.spr.convert_alpha(); + + self.image=self.spr;#spr and image point to the same surface, to be checked + else: + self.image=self.spr=None; + +class obj(pygame.sprite.Sprite): + '''Can be inherited as a base class''' + #all_obj_derived=pygame.sprite.Group(); + def __init__(self,x,y,sprite_filename=None,alpha=None): + ''' alpha may have values None(no alpha set),1(set_colorkey as the bottom-right corner),2(per-pixel alpha)''' + super(obj,self).__init__(); + self.x=x; + self.y=y; + self.xprevious=x; + self.yprevious=y; #ToDO : Make way for acceleration ("force" model) and setting speed + self.hspeed=0; + self.vspeed=0; + global load_image; + load_image(self,sprite_filename,alpha); + # as it is a derived class of Sprite, it can be directly added to gr group + #obj.all_obj_derived.add(self); + + + #obj.list.append(self); + + def draw_self(self): + surf.blit(self.sprite,(self.x-self.sprite.get_width()/2,self.y-self.sprite.get_height()/2)); + + def update(self): + ''' Should be called after draw_self (or as the last method) to update xprevious. + If not called, get_speed(),get_hspeed(),get_vspeed() won't work''' + self.xprevious=self.x; + self.yprevious=self.y; + self.x+=self.hspeed; + self.y+=self.vspeed; + self.speed=int(math.sqrt(self.hspeed**2+self.vspeed**2)); + self.rect=self.image.get_rect(center=(self.x,self.y)); + +#custom-made functions +def update_inside(group_name): + '''e.g. group_name=a.all_instances. + Calls group_name.update only when sprite.image is within screen, else delete it.''' + temp=None; + for temp in group_name.sprites(): + if (temp.x-temp.image.get_width()/2=surf.get_width(): + a.all_instances.remove(b); + #del(b); + print(5) + print(a.all_instances.sprites()) + if len(a.all_instances)>0: + pygame.display.update(a.all_instances.draw(surf)) + + #Events here +#--------------------------------------------------------- end---------------------------------------------------# \ No newline at end of file diff --git a/I'm the villian/main.py b/I'm the villian/main.py new file mode 100644 index 0000000..05a2b4a --- /dev/null +++ b/I'm the villian/main.py @@ -0,0 +1,99 @@ +# all imports +import math; +import pygame; +from pygame.locals import * + +# init +pygame.init() + +# setting display +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Wtf is this??") + +'''class obj(pygame.sprite.Sprite): + Can be inherited as a base class + #all_obj_derived=pygame.sprite.Group(); + def __init__(self,x,y,sprite_filename,alpha=None): + alpha may have values None(no alpha set),1(set_colorkey as the bottom-right corner),2(per-pixel alpha) + super(obj,self).__init__(); + self.x=x; + self.y=y; + self.xprevious=x; + self.yprevious=y; #ToDO : Make way for acceleration ("force" model) and setting speed + # set correct spr attribute + self.spr=pygame.image.load(sprite_filename).convert(); + + if alpha==None: + self.spr=self.spr.convert(); + elif alpha==1: + self.spr=self.spr.convert(); + self.spr.set_colorkey(self.spr.get_at((self.spr.get_width(),self.spr.get_height()))); + elif alpha==2: + self.spr=self.spr.convert_alpha(); + + self.image=self.spr;#spr and image point to the same surface, to be checked + + # as it is a derived class of Sprite, it can be directly added to gr group + #obj.all_obj_derived.add(self); + + + #obj.list.append(self); + + def get_speed(self): + return int(math.sqrt(self.get_hspeed()**2+self.get_vspeed*()*2)); + + def get_hspeed(self): + return (self.x-self.xprevious); + + def get_vspeed(self): + return (self.y-self.yprevious); + + def draw_self(self): + surf.blit(self.sprite,(self.x-self.sprite.get_width()/2,self.y-self.sprite.get_height()/2)); + + def update(self): + Should be called after draw_self (or as the last method) to update xprevious. + If not called, get_speed(),get_hspeed(),get_vspeed() won't work + self.x+=1; + #self.y+=1; + self.xprevious=self.x; + self.yprevious=self.y; + self.rect=self.image.get_rect(center=(self.x,self.y));''' + +# creating new classes +'''class a(obj): + all_instances=pygame.sprite.RenderUpdates(); + def __init__(self,x,y,sprite_filename,alpha=None): + super().__init__(x,y,sprite_filename,alpha=None) + a.all_instances.add(self);''' +# wow=True; + +#class b(obj): + #wow=False; + +#a1=a(surf.get_width()/2,surf.get_height()/2,"ball.bmp") +#a2=a(100,100,"ball.bmp") +# game startup code +c=pygame.time.Clock(); +#surf.fill((255,0,255)) +# main game loop +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); + + c.tick(); +# pygame.display.set_caption(str(c.get_fps())); + # + +''' for b in a.all_instances.sprites(): + if b.x+b.image.get_width()self.vel: + self.x+=self.vel*s.math.cos(self.angle) + self.y-=self.vel*s.math.sin(self.angle) + else: + self.x=self.ori_x + self.y=self.ori_y + +## if round(self.x)img.width-w/2: +## self.x=img.width-w/2 +## if round(self.y)>img.height-h/2: +## self.y=img.height-h/2 + self.vel-=self.accln + + +def distance((x1,y1),(x2,y2)): + import math + return(math.sqrt((x2-x1)**2+(y2-y1)**2)) + +n1=img.getNumpy() +p_list=[] +from random import randint +for c1 in range(img.width/w): + for c2 in range(img.height/h): + p_list.append( Pixel( ((c1+0.5)*w,(c2+0.5)*h),(randint(w+1,img.width*2-w-1),randint(h+1,img.height*2-h-1)),n1[c1*w:(c1+1)*w,c2*h:(c2+1)*h] ) ) +print("Done "+str(time.clock()-c)) +c=time.clock() + #print((c1+0.5)*w,(c2+0.5)*h) +print(len(p_list)) +n1=img.scale(2).getNumpy() +for count in range(total_time+5): + #del n1 + print(count) + #i1=s.Image((img.width*2,img.height*2)) + n1[:,:]=[0,0,0] + #del i1 + for p in p_list: + p.step() + #temp=n[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2] + n1[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2]=p.arr + img=s.Image(n1) + #img=img.scale(0.5) +## if count<70: +## img=img.blur((70-count)/10+1) + iset.append(img) + #img.scale(2).show() +print(time.clock()-c) +iset.save(r"C:\Users\Abhas_2\Desktop\ani.gif",3.5/100) \ No newline at end of file diff --git a/animation_2.py b/animation_2.py new file mode 100644 index 0000000..a228bd4 --- /dev/null +++ b/animation_2.py @@ -0,0 +1,67 @@ +import SimpleCV as s +import time +import time +img = s.Image("C:\Users\Abhas_2\Pictures\world_of_tanks_2-851x315.jpg") +iset=s.ImageSet() +total_time=100 # in steps +w=40 +h=40 +c=time.clock() +class Pixel(object): + def __init__(self,(ori_x,ori_y),(start_x,start_y),arr): + self.ori_x=ori_x + self.ori_y=ori_y + self.x=float(start_x) + self.y=float(start_y) + self.angle=s.math.atan2(-(ori_y-start_y),(ori_x-start_x)) + self.dist=distance((ori_x,ori_y),(start_x,start_y)) #float + self.accln=2*self.dist/float((total_time**2)) + self.vel=self.accln*total_time + self.arr=arr + def step(self): + if distance((self.x,self.y),(self.ori_x,self.ori_y))>self.vel: + self.x+=self.vel*s.math.cos(self.angle) + self.y-=self.vel*s.math.sin(self.angle) + else: + self.x=self.ori_x + self.y=self.ori_y + +## if round(self.x)img.width-w/2: +## self.x=img.width-w/2 +## if round(self.y)>img.height-h/2: +## self.y=img.height-h/2 + self.vel-=self.accln + + +def distance((x1,y1),(x2,y2)): + import math + return(math.sqrt((x2-x1)**2+(y2-y1)**2)) + +n1=img.getNumpy() +p_list=[] +from random import randint +for c1 in range(img.width/w): + for c2 in range(img.height/h): + p_list.append( Pixel( ((c1+0.5)*w,(c2+0.5)*h),(randint(w/2,img.width-w/2),randint(h/2,img.height-h/2)),n1[c1*w:(c1+1)*w,c2*h:(c2+1)*h] ) ) +print("Done "+str(time.clock()-c)) +c=time.clock() + #print((c1+0.5)*w,(c2+0.5)*h) +print(len(p_list)) +for count in range(total_time+5): + #del n + i1=s.Image((img.width,img.height)) + n=i1.getNumpy() + for p in p_list: + p.step() + #temp=n[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2] + n[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2]=p.arr + img=s.Image(n) + iset.append(img) + print(count) + #img.scale(2).show() +print(time.clock()-c) +iset.save(r"C:\Users\Abhas_2\Desktop\ani.gif",3.5/100) \ No newline at end of file diff --git a/another_file.py b/another_file.py new file mode 100644 index 0000000..0acee59 --- /dev/null +++ b/another_file.py @@ -0,0 +1,3 @@ +class class_a(): + def __init__(self): + print(math.cos(0)) \ No newline at end of file diff --git a/apple-touch-icon.png b/apple-touch-icon.png new file mode 100644 index 0000000..f610016 Binary files /dev/null and b/apple-touch-icon.png differ diff --git a/avg_detection.py b/avg_detection.py new file mode 100644 index 0000000..6792496 --- /dev/null +++ b/avg_detection.py @@ -0,0 +1,25 @@ +import SimpleCV as s +import time +c= s.Camera(0, {'width': 320, 'height': 240}) +size=25 +count=size-1 # important to make it float +i=[] +for temp in range(size): + i.append(c.getImage()) + print(temp) +d=s.Display() +while not d.isDone(): + show_img=c.getImage() + i[int(count)]=show_img + count+=1 + if count==size: + count=0 + print(count/(count+1)) + temp_img=s.Image((320,240)) + for temp in i: + temp_img+=(temp/float(size)) + show_img=(show_img-temp_img)+(temp_img-show_img) +## print(count) +## i1.save(d) +## time.sleep(0.05) + show_img.binarize(50).erode(4).dilate(4).save(d) \ No newline at end of file diff --git a/ball.bmp b/ball.bmp new file mode 100644 index 0000000..297a095 Binary files /dev/null and b/ball.bmp differ diff --git a/basic_template.py b/basic_template.py new file mode 100644 index 0000000..617bbb1 --- /dev/null +++ b/basic_template.py @@ -0,0 +1,60 @@ +# all imports +import math; +import pygame; +from pygame.locals import * + +# init +pygame.init() + +# setting display +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Bendtherules rocks!!") + +class obj(): + '''Can be inherited as a base class''' + list=[]; + def __init__(self,x,y,sprite_filename): + self.x=x; + self.y=y; + self.xprevious=x; + self.yprevious=y; #ToDO : Make way for acceleration ("force" model) and setting speed + self.sprite=pygame.image.load(sprite_filename).convert_alpha(); + obj.list.append(self); + + def get_speed(self): + return int(math.sqrt(self.get_hspeed()**2+self.get_vspeed*()*2)); + + def get_hspeed(self): + return (self.x-self.xprevious); + + def get_vspeed(self): + return (self.y-self.yprevious); + + def draw_self(self): + surf.blit(self.sprite,(self.x-self.sprite.get_width()/2,self.y-self.sprite.get_height()/2)); + + def update(self): + ''' Should be called after draw_self (or as the last method) to update xprevious. + If not called, get_speed(),get_hspeed(),get_vspeed() won't work''' + self.xprevious=self.x; + self.x+=1 + +# game startup code +c=pygame.time.Clock(); +a=obj(100,100,"a.png"); +surf.fill((250,50,50)) +# main game loop +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); + surf.fill((250,50,50)) + a.update() + a.draw_self(); + c.tick(); + pygame.display.set_caption(str(c.get_fps())); + pygame.display.update(); + + #Events here +#--------------------------------------------------------- end---------------------------------------------------# \ No newline at end of file diff --git a/bot_detect.py b/bot_detect.py new file mode 100644 index 0000000..f82734e --- /dev/null +++ b/bot_detect.py @@ -0,0 +1,110 @@ +import SimpleCV as s +import time +import webcolors as w +import serial_setup +from math import sqrt,atan2,degrees,sin, cos,radians + +#Uncomment below line only while using serial +#serial_setup.setup(port=8) + +def mean(list_a): + sum=0 + for elements in list_a: + sum+=elements + return float(sum)/len(list_a) + +clock1=time.clock() +cam=s.JpegStreamCamera(r"http://192.168.173.109:8080/videofeed") +def loop(): + #img=s.Image(r"C:\Users\Abhas_2\Desktop\untitled.png").scale(.25) + img=cam.getImage() + #clock1=time.clock() + #print("0: "+str(1/(time.clock()-clock1))) + img2=img.toGray() + #print("1: "+str(1/(time.clock()-clock1))) + img_black=img2.stretch(50,50) + #img_black=img2.threshold(10) + #print("2: "+str(1/(time.clock()-clock1))) + bot_blobs=img_black.invert().findBlobs() + if bot_blobs: + bot=bot_blobs[-1:][0] + #print("3: "+str(1/(time.clock()-clock1))) + bot_hole=(img2.crop(bot)-bot.hullMask().invert()).morphOpen() + #print("4: "+str(1/(time.clock()-clock1))) + hole_blobs=bot_hole.findBlobs() + if hole_blobs: + hole=hole_blobs[-1:][0] + hole_center=[bot.topLeftCorner()[0]+hole.x, bot.topLeftCorner()[1]+hole.y] + #print("5: "+str(1/(time.clock()-clock1))) + bot_center=bot.centroid() + bot_radius=bot.radius() + bot_angle=ball_angle=degrees(atan2(-(hole_center[1]-bot_center[1]),hole_center[0]-bot_center[0])) + img3=(img2-img)+(img-img2) + #img3.show() + + #f[0].show() + #print("6: "+str(1/(time.clock()-clock1))) + img_=img-img3.threshold(5).invert() + #print("7: "+str(1/(time.clock()-clock1))) + f=img_.findBlobs() + #print("8: "+str(1/(time.clock()-clock1))) + if f: + f=f[-1:] + c_match=f[0].meanColor() + ball_centre=[f[0].x,f[0].y] + ball_angle=degrees(atan2(-(ball_centre[1]-bot_center[1]),ball_centre[0]-bot_center[0])) + #print(ball_angle) + img.drawLine(ball_centre,bot_center,s.Color.YELLOW,5) + #img_.drawLine(bot_center,[bot_center[0]+cos(radians( bot_angle))*bot_radius,bot_center[1]-sin(radians(bot_angle))*bot_radius],s.Color.BLUE,5) + #img_.show() + #c=f[0].centroid() + #out=img_.crop(c[0],c[1],f[0].width(),f[0].height(),True) + + #img_in=out.crop(out.width/2,out.height/2,out.width/sqrt(2),out.height/sqrt(2),True) + #c_match=img_in.toRGB().meanColor() + #print(c_match) + c_match=s.Color.getHueFromRGB(c_match) + #print(c_match) + least=255*3 + color=None + list_check=s.Color.colorlist + #list_check=[s.Color.getHueFromRGB(s.Color.YELLOW),s.Color.getHueFromRGB(s.Color.RED),s.Color.getHueFromRGB(s.Color.BLUE),s.Color.getHueFromRGB(s.Color.GREEN),s.Color.getHueFromRGB(s.Color.HOTPINK)] + for c in list_check: + c_=s.Color.getHueFromRGB(c) + diff=abs(c_match-c_) + if diff img_width*0.70: + print("Detected") + print(right_step,left_step) + if right_step>left_step: + print("Left to right") + else: + print("Right to left") + print(c1) + detection_sleep=gesture_time+1 + else: + pass + #print("Not detected") + else: + min_x=None + min_y=None + max_x=None + max_y=None + if detection_sleep: + detection_sleep-=1 +## max_x=min([max([temp[0] for temp in blobs_temp.topLeftCorners()]) for blobs_temp in blobs if blobs_temp ].append(0)) +## min_x=min([min([temp[0] for temp in blobs_temp.topLeftCorners()]) for blobs_temp in blobs]) +## max_y=max([max([temp[1] for temp in blobs_temp.bottomRightCorners()]) for blobs_temp in blobs]) +## min_y=min([min([temp[1] for temp in blobs_temp.bottomRightCorners()]) for blobs_temp in blobs]) + if f: + f.draw(width=2) + i3.show() + c2=time.clock() + #print(1/(c1-c2)) + c1=c2 + count+=1 + count=count%gesture_time +## i2.findSkintoneBlobs().show() \ No newline at end of file diff --git a/camera_fps.py b/camera_fps.py new file mode 100644 index 0000000..c29c6e3 --- /dev/null +++ b/camera_fps.py @@ -0,0 +1,10 @@ +import SimpleCV as s +import time +#cam=s.Camera() +cam=s.JpegStreamCamera(r"192.168.173.227:8080/videofeed") +c1=time.clock() +while True: + img=cam.getImage().show() + c2=time.clock() + print(1/(c1-c2)) + c1=c2 \ No newline at end of file diff --git a/class_ball.py b/class_ball.py new file mode 100644 index 0000000..24d254c --- /dev/null +++ b/class_ball.py @@ -0,0 +1,42 @@ +import pygame +class ball(object): + #global pygame + def __init__(self,class_lst,x=320,y=240,speed=3):#pass a shared globals object + import class_ball + mouse_down=False + self.x=x + self.y=y + self.speed=speed + self.dir=None + self.ball=pygame.image.load("gun.png") + self.ballrect=self.ball.get_rect() + #mouse_down=False; # needs to be in a seperate object - make the event stream step-by-step by caching during every step + + def mouse_handler(self): + if pygame.event.get(pygame.MOUSEBUTTONDOWN) or self.__class__.mouse_down == True: + self.x=self.mouse_x + self.y=self.mouse_y + self.__class__.mouse_down=True + print 6 + + if pygame.event.get(pygame.MOUSEBUTTONUP): + self.__class__.mouse_down=False + + def step(self): + self.mouse_x,self.mouse_y=pygame.mouse.get_pos() + self.diff_x=self.mouse_x-self.x + self.diff_y=self.mouse_y-self.y + self.diff_rad=math.atan2(self.diff_y,self.diff_x) + self.x+=self.speed*math.cos(self.diff_rad) + self.y+=self.speed*math.sin(self.diff_rad) + self.ballrect.center=(self.x,self.y) + + def draw(self): + screen.blit(self.ball, self.ballrect) + + + def update(self): + self.step() + self.mouse_handler() + self.draw() + diff --git a/csv_try.py b/csv_try.py new file mode 100644 index 0000000..31b838b --- /dev/null +++ b/csv_try.py @@ -0,0 +1,14 @@ +import csv +c=[89,25] +a=["hi, there ",509,c] +f=open("a.csv","w") +w=csv.writer(f) +w.writerow(a) +f.close() +f=open("a.csv","r") +r=csv.reader(f) +for c in r: + d=c; + +print(type(c)) +print(c) diff --git a/cv_test.py b/cv_test.py new file mode 100644 index 0000000..701a417 --- /dev/null +++ b/cv_test.py @@ -0,0 +1,7 @@ +import cv2 +# read image +im = cv2.imread("Photo0094.jpg") +h,w = im.shape[:2] +print h,w +# save image +cv2.imwrite("result.png",im) \ No newline at end of file diff --git a/django_try/mysite/manage.py b/django_try/mysite/manage.py new file mode 100644 index 0000000..8a50ec0 --- /dev/null +++ b/django_try/mysite/manage.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + + from django.core.management import execute_from_command_line + + execute_from_command_line(sys.argv) diff --git a/django_try/mysite/mysite/__init__.py b/django_try/mysite/mysite/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_try/mysite/mysite/settings.py b/django_try/mysite/mysite/settings.py new file mode 100644 index 0000000..55954ed --- /dev/null +++ b/django_try/mysite/mysite/settings.py @@ -0,0 +1,158 @@ +# Django settings for mysite project. + +DEBUG = True +TEMPLATE_DEBUG = DEBUG + +ADMINS = ( + # ('Your Name', 'your_email@example.com'), +) + +MANAGERS = ADMINS + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. + 'NAME': './new_sqlite3.db', # Or path to database file if using sqlite3. + # The following settings are not used with sqlite3: + 'USER': '', + 'PASSWORD': '', + 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. + 'PORT': '', # Set to empty string for default. + } +} + +# Hosts/domain names that are valid for this site; required if DEBUG is False +# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts +ALLOWED_HOSTS = [] + +# Local time zone for this installation. Choices can be found here: +# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name +# although not all choices may be available on all operating systems. +# In a Windows environment this must be set to your system time zone. +TIME_ZONE = 'Asia/Kolkata' + +# Language code for this installation. All choices can be found here: +# http://www.i18nguy.com/unicode/language-identifiers.html +LANGUAGE_CODE = 'en-us' + +SITE_ID = 1 + +# If you set this to False, Django will make some optimizations so as not +# to load the internationalization machinery. +USE_I18N = True + +# If you set this to False, Django will not format dates, numbers and +# calendars according to the current locale. +USE_L10N = True + +# If you set this to False, Django will not use timezone-aware datetimes. +USE_TZ = True + +# Absolute filesystem path to the directory that will hold user-uploaded files. +# Example: "/var/www/example.com/media/" +MEDIA_ROOT = '' + +# URL that handles the media served from MEDIA_ROOT. Make sure to use a +# trailing slash. +# Examples: "http://example.com/media/", "http://media.example.com/" +MEDIA_URL = '' + +# Absolute path to the directory static files should be collected to. +# Don't put anything in this directory yourself; store your static files +# in apps' "static/" subdirectories and in STATICFILES_DIRS. +# Example: "/var/www/example.com/static/" +STATIC_ROOT = '' + +# URL prefix for static files. +# Example: "http://example.com/static/", "http://static.example.com/" +STATIC_URL = '/static/' + +# Additional locations of static files +STATICFILES_DIRS = ( + # Put strings here, like "/home/html/static" or "C:/www/django/static". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. +) + +# List of finder classes that know how to find static files in +# various locations. +STATICFILES_FINDERS = ( + 'django.contrib.staticfiles.finders.FileSystemFinder', + 'django.contrib.staticfiles.finders.AppDirectoriesFinder', +# 'django.contrib.staticfiles.finders.DefaultStorageFinder', +) + +# Make this unique, and don't share it with anybody. +SECRET_KEY = r'@e{@q]%h;2u^u.,.y8772+98d/d/;,[.&;=9#0$9%@0(rtrt)=-=dgd' + +# List of callables that know how to import templates from various sources. +TEMPLATE_LOADERS = ( + 'django.template.loaders.filesystem.Loader', + 'django.template.loaders.app_directories.Loader', +# 'django.template.loaders.eggs.Loader', +) + +MIDDLEWARE_CLASSES = ( + 'django.middleware.common.CommonMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + # Uncomment the next line for simple clickjacking protection: + # 'django.middleware.clickjacking.XFrameOptionsMiddleware', +) + +ROOT_URLCONF = 'mysite.urls' + +# Python dotted path to the WSGI application used by Django's runserver. +WSGI_APPLICATION = 'mysite.wsgi.application' + +TEMPLATE_DIRS = ( + # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". + # Always use forward slashes, even on Windows. + # Don't forget to use absolute paths, not relative paths. +) + +INSTALLED_APPS = ( + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.sites', + 'django.contrib.messages', + 'django.contrib.staticfiles', + # Uncomment the next line to enable the admin: + 'django.contrib.admin', + # Uncomment the next line to enable admin documentation: + # 'django.contrib.admindocs', + 'poll', + 'polls' +) + +# A sample logging configuration. The only tangible logging +# performed by this configuration is to send an email to +# the site admins on every HTTP 500 error when DEBUG=False. +# See http://docs.djangoproject.com/en/dev/topics/logging for +# more details on how to customize your logging configuration. +LOGGING = { + 'version': 1, + 'disable_existing_loggers': False, + 'filters': { + 'require_debug_false': { + '()': 'django.utils.log.RequireDebugFalse' + } + }, + 'handlers': { + 'mail_admins': { + 'level': 'ERROR', + 'filters': ['require_debug_false'], + 'class': 'django.utils.log.AdminEmailHandler' + } + }, + 'loggers': { + 'django.request': { + 'handlers': ['mail_admins'], + 'level': 'ERROR', + 'propagate': True, + }, + } +} diff --git a/django_try/mysite/mysite/urls.py b/django_try/mysite/mysite/urls.py new file mode 100644 index 0000000..bcfb17c --- /dev/null +++ b/django_try/mysite/mysite/urls.py @@ -0,0 +1,18 @@ +from django.conf.urls import patterns, include, url + +# Uncomment the next two lines to enable the admin: +from django.contrib import admin +admin.autodiscover() + +urlpatterns = patterns('', + # Examples: + # url(r'^$', 'mysite.views.home', name='home'), + # url(r'^mysite/', include('mysite.foo.urls')), + + # Uncomment the admin/doc line below to enable admin documentation: + url(r'^admin/doc/', include('django.contrib.admindocs.urls')), + + # Uncomment the next line to enable the admin: + url(r'^admin/', include(admin.site.urls)), + url(r"^polls/", include("poll.urls")), +) diff --git a/django_try/mysite/mysite/wsgi.py b/django_try/mysite/mysite/wsgi.py new file mode 100644 index 0000000..34e900e --- /dev/null +++ b/django_try/mysite/mysite/wsgi.py @@ -0,0 +1,32 @@ +""" +WSGI config for mysite project. + +This module contains the WSGI application used by Django's development server +and any production WSGI deployments. It should expose a module-level variable +named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover +this application via the ``WSGI_APPLICATION`` setting. + +Usually you will have the standard Django WSGI application here, but it also +might make sense to replace the whole Django WSGI application with a custom one +that later delegates to the Django one. For example, you could introduce WSGI +middleware here, or combine a Django application with an application of another +framework. + +""" +import os + +# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks +# if running multiple sites in the same mod_wsgi process. To fix this, use +# mod_wsgi daemon mode with each site in its own daemon process, or use +# os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") + +# This application object is used by any WSGI server configured to use this +# file. This includes Django's development server, if the WSGI_APPLICATION +# setting points here. +from django.core.wsgi import get_wsgi_application +application = get_wsgi_application() + +# Apply WSGI middleware here. +# from helloworld.wsgi import HelloWorldApplication +# application = HelloWorldApplication(application) diff --git a/django_try/mysite/new_sqlite3.db b/django_try/mysite/new_sqlite3.db new file mode 100644 index 0000000..ad37d7e Binary files /dev/null and b/django_try/mysite/new_sqlite3.db differ diff --git a/django_try/mysite/poll/__init__.py b/django_try/mysite/poll/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_try/mysite/poll/admin.py b/django_try/mysite/poll/admin.py new file mode 100644 index 0000000..d8f8269 --- /dev/null +++ b/django_try/mysite/poll/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin +from poll.models import Poll +admin.site.register(Poll) diff --git a/django_try/mysite/poll/models.py b/django_try/mysite/poll/models.py new file mode 100644 index 0000000..105d407 --- /dev/null +++ b/django_try/mysite/poll/models.py @@ -0,0 +1,21 @@ +from django.db import models +import datetime +from django.utils import timezone + +# Create your models here. +class Poll(models.Model): + question=models.CharField(max_length=200) + pub_date=models.DateTimeField("date published") + + def __unicode__(self): + return self.question + + def was_published_recently(self): + return self.pub_date>=timezone.now()-datetime.timedelta(days=1) + +class Choice(models.Model): + poll=models.ForeignKey(Poll) + choice_text=models.CharField(max_length=200) + votes=models.IntegerField(default=0) + def __unicode__(self): + return self.choice_text \ No newline at end of file diff --git a/django_try/mysite/poll/prints itself.py b/django_try/mysite/poll/prints itself.py new file mode 100644 index 0000000..b55e3fc --- /dev/null +++ b/django_try/mysite/poll/prints itself.py @@ -0,0 +1,2 @@ +s = r"print 's = r\"' + s + '\"' + '\nexec(s)'" +exec(s) \ No newline at end of file diff --git a/django_try/mysite/poll/remove repeat.py b/django_try/mysite/poll/remove repeat.py new file mode 100644 index 0000000..77be68c --- /dev/null +++ b/django_try/mysite/poll/remove repeat.py @@ -0,0 +1,18 @@ +def remove_dup(line): + words=line.split() + final="" + check=words[0] + final+=check + for word in words[1:]: + if word!=check: + final+=" "+word + check=word + answers.append(final) + +answers=[] +f=open(r"C:\Users\Abhas_2\Desktop\input(1).txt") +times=input() +for count in range(times): + remove_dup(raw_input()) +for answer in answers: + print(answer) \ No newline at end of file diff --git a/django_try/mysite/poll/tests.py b/django_try/mysite/poll/tests.py new file mode 100644 index 0000000..501deb7 --- /dev/null +++ b/django_try/mysite/poll/tests.py @@ -0,0 +1,16 @@ +""" +This file demonstrates writing tests using the unittest module. These will pass +when you run "manage.py test". + +Replace this with more appropriate tests for your application. +""" + +from django.test import TestCase + + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.assertEqual(1 + 1, 2) diff --git a/django_try/mysite/poll/urls.py b/django_try/mysite/poll/urls.py new file mode 100644 index 0000000..d5b5b4b --- /dev/null +++ b/django_try/mysite/poll/urls.py @@ -0,0 +1,11 @@ +from django.conf.urls import patterns, url +from poll import views +urlpatterns = patterns("", + url(r"^$", views.index, name="index"), + url(r"^(?P\d+)/$", views.detail, name="detail"), + url(r"^(?P\d+)/details?/$", views.detail, name="detail"), + # ex: /polls/5/results/ + url(r"^(?P\d+)/results/$", views.results, name="results"), + # ex: /polls/5/vote/ + url(r"^(?P\d+)/vote/$", views.vote, name="vote"), + ) diff --git a/django_try/mysite/poll/views.py b/django_try/mysite/poll/views.py new file mode 100644 index 0000000..8a2b3f4 --- /dev/null +++ b/django_try/mysite/poll/views.py @@ -0,0 +1,12 @@ +# Create your views here. +from django.http import HttpResponse +def index(request): + return HttpResponse("Hello, world. You're at the poll index.") +def detail(request, poll_id): + return HttpResponse("You're looking at poll %s." % poll_id) +def results(request, poll_id): + return HttpResponse("You're looking at the results of poll %s." % poll_id) +def vote(request, poll_id): + return HttpResponse("You're voting on poll %s." % poll_id) + + diff --git a/django_try/mysite/polls/__init__.py b/django_try/mysite/polls/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/django_try/mysite/polls/models.py b/django_try/mysite/polls/models.py new file mode 100644 index 0000000..b046d75 --- /dev/null +++ b/django_try/mysite/polls/models.py @@ -0,0 +1,12 @@ +from django.db import models + +# Create your models here. +class Poll(models.Model): + question=models.CharField(max_length=200) + pub_date=models.DateTimeField("date published") + +class Choice(models.Model): + poll=models.ForeignKey(Poll) + choice_text=models.CharField(max_length=200) + votes=models.IntegerField(default=0) + diff --git a/django_try/mysite/polls/tests.py b/django_try/mysite/polls/tests.py new file mode 100644 index 0000000..501deb7 --- /dev/null +++ b/django_try/mysite/polls/tests.py @@ -0,0 +1,16 @@ +""" +This file demonstrates writing tests using the unittest module. These will pass +when you run "manage.py test". + +Replace this with more appropriate tests for your application. +""" + +from django.test import TestCase + + +class SimpleTest(TestCase): + def test_basic_addition(self): + """ + Tests that 1 + 1 always equals 2. + """ + self.assertEqual(1 + 1, 2) diff --git a/django_try/mysite/polls/views.py b/django_try/mysite/polls/views.py new file mode 100644 index 0000000..60f00ef --- /dev/null +++ b/django_try/mysite/polls/views.py @@ -0,0 +1 @@ +# Create your views here. diff --git a/empire.png b/empire.png new file mode 100644 index 0000000..a3279a9 Binary files /dev/null and b/empire.png differ diff --git a/face_detection.py b/face_detection.py new file mode 100644 index 0000000..08d60d4 --- /dev/null +++ b/face_detection.py @@ -0,0 +1,31 @@ +import SimpleCV as s +#c=s.JpegStreamCamera(r"http://192.168.173.144:8080/videofeed") +c=s.Camera() +##i=c.getImage().scale(.5) +##f=i.findHaarFeatures("face.xml") +count=1 +while count<5: + count+=1 + i=c.getImage() + f=i.findHaarFeatures("face.xml") + if f: + f.draw(width=2) + i.show() + +i.flipHorizontal().save(r"E:\Babu\pytry\robocon\face_detect.jpg") +##f.show() +##import time +##cl=time.clock() +##if time.clock()-cl<2: +## pass +##fs1=[] +##bbox=f[0].boundingBox() +## +##while True: +## img1 = c.getImage() +## fs1 = img1.track("camshift",fs1,i,tuple(bbox),num_frames=5) +## fs1.drawBB() +## fs1.draw() +## img1.show() +## del img1 + #fs1.drawPredict(color=Color.RED) \ No newline at end of file diff --git a/gloss try/basic_app.py b/gloss try/basic_app.py new file mode 100644 index 0000000..9ac0c3a --- /dev/null +++ b/gloss try/basic_app.py @@ -0,0 +1,13 @@ +import gloss as g +import random +class Test(g.GlossGame): + def draw(self): + print g.Gloss.running_slowly + for count in range(150): + g.Gloss.draw_box(position = (count,count), width = random.randint(0,128), height = random.randint(0,128), rotation = random.randint(0,360), origin = (0, 0), scale = 1, color = g.Color.WHITE) + def load_content(self): + self.bck=g.Texture("content/background.jpg") +app=Test("Testing boss..") +g.Gloss.screen_resolution = 640,480 +#g.Gloss.full_screen = True +app.run() \ No newline at end of file diff --git a/gloss try/content/background.jpg b/gloss try/content/background.jpg new file mode 100644 index 0000000..c414af4 Binary files /dev/null and b/gloss try/content/background.jpg differ diff --git a/gloss try/content/cloud.png b/gloss try/content/cloud.png new file mode 100644 index 0000000..806492b Binary files /dev/null and b/gloss try/content/cloud.png differ diff --git a/gloss try/content/fire.png b/gloss try/content/fire.png new file mode 100644 index 0000000..25f4edb Binary files /dev/null and b/gloss try/content/fire.png differ diff --git a/gloss try/content/fire.tga b/gloss try/content/fire.tga new file mode 100644 index 0000000..731e9a4 Binary files /dev/null and b/gloss try/content/fire.tga differ diff --git a/gloss try/content/freesans.ttf b/gloss try/content/freesans.ttf new file mode 100644 index 0000000..9d51347 Binary files /dev/null and b/gloss try/content/freesans.ttf differ diff --git a/gloss try/content/gem.png b/gloss try/content/gem.png new file mode 100644 index 0000000..293f5ca Binary files /dev/null and b/gloss try/content/gem.png differ diff --git a/gloss try/content/gem_green.png b/gloss try/content/gem_green.png new file mode 100644 index 0000000..9f5250b Binary files /dev/null and b/gloss try/content/gem_green.png differ diff --git a/gloss try/content/marble_blue.png b/gloss try/content/marble_blue.png new file mode 100644 index 0000000..4ea90ba Binary files /dev/null and b/gloss try/content/marble_blue.png differ diff --git a/gloss try/content/marble_green.png b/gloss try/content/marble_green.png new file mode 100644 index 0000000..b9d13d2 Binary files /dev/null and b/gloss try/content/marble_green.png differ diff --git a/gloss try/content/marble_purple.png b/gloss try/content/marble_purple.png new file mode 100644 index 0000000..b28e552 Binary files /dev/null and b/gloss try/content/marble_purple.png differ diff --git a/gloss try/content/marble_red.png b/gloss try/content/marble_red.png new file mode 100644 index 0000000..4fbefad Binary files /dev/null and b/gloss try/content/marble_red.png differ diff --git a/gloss try/content/marble_yellow.png b/gloss try/content/marble_yellow.png new file mode 100644 index 0000000..4aea96d Binary files /dev/null and b/gloss try/content/marble_yellow.png differ diff --git a/gloss try/content/red_cross.png b/gloss try/content/red_cross.png new file mode 100644 index 0000000..e746337 Binary files /dev/null and b/gloss try/content/red_cross.png differ diff --git a/gloss try/content/sharpshooter.png b/gloss try/content/sharpshooter.png new file mode 100644 index 0000000..234665b Binary files /dev/null and b/gloss try/content/sharpshooter.png differ diff --git a/gloss try/content/smoke.tga b/gloss try/content/smoke.tga new file mode 100644 index 0000000..62493b1 Binary files /dev/null and b/gloss try/content/smoke.tga differ diff --git a/gloss try/content/star.png b/gloss try/content/star.png new file mode 100644 index 0000000..7b569a4 Binary files /dev/null and b/gloss try/content/star.png differ diff --git a/gloss try/content/target.png b/gloss try/content/target.png new file mode 100644 index 0000000..9ebefa4 Binary files /dev/null and b/gloss try/content/target.png differ diff --git a/gloss try/gloss.py b/gloss try/gloss.py new file mode 100644 index 0000000..8efd805 --- /dev/null +++ b/gloss try/gloss.py @@ -0,0 +1,1302 @@ +## Gloss +## Copyright (C) 2009 Paul Hudson (http://www.tuxradar.com/gloss) + +## Gloss is free software; you can redistribute it and/or +## modify it under the terms of the GNU Lesser 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 Lesser General Public License +## along with this program; if not, write to the Free Software +## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +from __future__ import division + +import math +import os +import pygame +import random +import signal +import sys +import threading +import time +import traceback +import weakref + +from OpenGL.GL import * +OpenGL.ERROR_CHECKING = False +from OpenGL.GL.EXT.framebuffer_object import * +from OpenGL.GLU import * + +from pygame.locals import * + + +class GlossGame(object): + def __init__(self, name): + Gloss.active_game = self + + Gloss.game_name = name + Gloss.screen_resolution = 1280,720 + Gloss.full_screen = False + Gloss.enable_multisampling = False + + # set empty event handlers + self.on_mouse_motion = None + self.on_mouse_down = None + self.on_mouse_up = None + self.on_key_down = None + self.on_key_up = None + self.on_quit = None + self.on_joy_axis_motion = None + self.on_joy_ball_motion = None + self.on_joy_button_down = None + self.on_joy_button_up = None + self.on_joy_hat_motion = None + + def preload_content(self): + pass + + def load_content(self): + pass + + def draw_loading_screen(self): + pass + + def draw(self): + pass + + def update(self): + pass + + def gloss_initialise(self): + os.environ['SDL_VIDEO_CENTERED'] = '1' + pygame.mixer.pre_init(44100, 16, 2, 4096) + pygame.init() + + pygame.joystick.init() + for i in range(pygame.joystick.get_count()): + joystick = pygame.joystick.Joystick(i) + joystick.init() + Gloss.joysticks.append(joystick) + + Gloss.game_clock = pygame.time.Clock() + + pygame.display.set_caption(Gloss.game_name) + + if Gloss.enable_multisampling: + pygame.display.gl_set_attribute(pygame.locals.GL_MULTISAMPLEBUFFERS, 1) + pygame.display.gl_set_attribute(pygame.locals.GL_MULTISAMPLESAMPLES, 4) + + if Gloss.full_screen: + pygame.display.set_mode(Gloss.screen_resolution, pygame.OPENGL | pygame.DOUBLEBUF | pygame.FULLSCREEN) + else: + pygame.display.set_mode(Gloss.screen_resolution, pygame.OPENGL | pygame.DOUBLEBUF) + + if Gloss.screen_resolution == (0, 0): + scr = pygame.display.get_surface() + Gloss.screen_resolution = scr.get_size() + + Gloss.MaxTextureSize = glGetInteger(GL_MAX_TEXTURE_SIZE); + + Gloss.clear(Color.CORNFLOWER_BLUE) + pygame.display.flip() + Gloss.clear(Color.CORNFLOWER_BLUE) + + glEnable(GL_CULL_FACE) + glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST) + + glHint(GL_LINE_SMOOTH_HINT, GL_NICEST) + glEnable(GL_LINE_SMOOTH) + + glEnable(GL_TEXTURE_2D) + + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + glEnable(GL_BLEND) + + glEnable(GL_LIGHTING) + glColorMaterial (GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE) + glEnable (GL_COLOR_MATERIAL) + Gloss.set_scene_tint(Color.WHITE) + + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + glOrtho(0, Gloss.screen_resolution[0], Gloss.screen_resolution[1], 0, -100, 100) + + Gloss.viewport_size = Gloss.screen_resolution + + glMatrixMode(GL_MODELVIEW) + glLoadIdentity() + + self.preload_content() + self.draw_loading_screen() + pygame.display.flip() + + Gloss.tick_count = 0 + + self.load_content() + + def gloss_internal_update(self): + for particlesystem in reversed(Gloss.auto_particle_systems): + # don't update this particle system if it's frozen + if particlesystem.frozen: + continue + + if particlesystem.update() is False: + Gloss.auto_particle_systems.remove(particlesystem) + particlesystem.alive = False + + if particlesystem.on_finish is not None: + particlesystem.on_finish(particlesystem) + + def gloss_internal_draw(self): + # if we take a screenshot after picking, we get the picking view rather than the real view + # to fix this, save_screenshot() looks for Gloss.redraw_needed, and, if it's true, redraws the screen + if Gloss.picking: + Gloss.redraw_needed = True + else: + Gloss.redraw_needed = False + + self.draw() + + def run(self): + self.gloss_initialise() + + Gloss.game_is_running = True + + while Gloss.game_is_running: + Gloss.elapsed_seconds = Gloss.game_clock.tick(60) / 1000 + Gloss.total_seconds += Gloss.elapsed_seconds + + if Gloss.elapsed_seconds > 0.02: + Gloss.running_slowly = True + else: + Gloss.running_slowly = False + + # tick_count is used in lots of places, so read it only once per update + Gloss.tick_count = pygame.time.get_ticks() + + for event in pygame.event.get(): + if event.type == MOUSEMOTION: + if self.on_mouse_down is not None: + self.on_mouse_motion(event) + + if event.type == MOUSEBUTTONDOWN: + if self.on_mouse_down is not None: + self.on_mouse_down(event) + + if event.type == MOUSEBUTTONUP: + if self.on_mouse_up is not None: + self.on_mouse_up(event) + + if Gloss.sprite_click_tracking: + Gloss.select_object(event.pos) + + if event.type == KEYDOWN: + if event.mod & KMOD_LCTRL == KMOD_LCTRL: + if event.key == K_ESCAPE: + # Left Ctrl+Escape held - quit + Gloss.game_is_running = False + + if self.on_key_down is not None: + self.on_key_down(event) + + if event.type == KEYUP: + if self.on_key_up is not None: + self.on_key_up(event) + + if event.type == JOYAXISMOTION: + if self.on_joy_axis_motion is not None: + self.on_joy_axis_motion(event) + + if event.type == JOYBALLMOTION: + if self.on_joy_ball_motion is not None: + self.on_joy_ball_motion(event) + + if event.type == JOYHATMOTION: + if self.on_joy_hat_motion is not None: + self.on_joy_hat_motion(event) + + if event.type == JOYBUTTONDOWN: + if self.on_joy_button_down is not None: + self.on_joy_button_down(event) + + if event.type == JOYBUTTONUP: + if self.on_joy_button_up is not None: + self.on_joy_button_up(event) + + if event.type == QUIT: + Gloss.game_is_running = False + + # this all has to be done after the above events so that any changes from events + # take place as soon as possible + self.gloss_internal_update() + self.update() + + self.gloss_internal_draw() + + pygame.display.flip() + + if self.on_quit is not None: + self.on_quit() + + pygame.quit() + + def quit(self): + Gloss.game_is_running = False + +class Color(object): + def __init__(self, r, g, b, a = 1.0): + self.r = r + self.g = g + self.b = b + self.a = a + + @staticmethod + def from_bytes(r, g, b, a = 255): + return Color(r / 255.0, g / 255.0, b / 255.0, a / 255.0) + + @staticmethod + def from_html(col): + pygamecol = pygame.color.Color(col) + return Color.from_pygame(pygamecol) + + @staticmethod + def from_pygame(col): + return Color(col[0] / 255, col[1] / 255, col[2] / 255, col[3] / 255) + + @staticmethod + def lerp(colorfrom, colorto, amount): + return Color(Gloss.lerp(colorfrom.r, colorto.r, amount), Gloss.lerp(colorfrom.g, colorto.g, amount), Gloss.lerp(colorfrom.b, colorto.b, amount), Gloss.lerp(colorfrom.a, colorto.a, amount)) + + @staticmethod + def lerp2(colorfrom, colorto, amount): + return Color(Gloss.lerp2(colorfrom.r, colorto.r, amount), Gloss.lerp2(colorfrom.g, colorto.g, amount), Gloss.lerp2(colorfrom.b, colorto.b, amount), Gloss.lerp2(colorfrom.a, colorto.a, amount)) + + @staticmethod + def multi_lerp(values, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + if result == 1.0: + return values[len(values) - 1] + + num_items = len(values) + position = int(math.floor(amount * (num_items - 1))) # what was the minimum item we were up to? + individual_lerp = 1.0 / (num_items - 1) # how much is each step? + current_lerp = amount - position * individual_lerp # how far through the current step are we? + lerp_amount = current_lerp / individual_lerp # how much is that compared to a full step + + return Color.lerp(values[position], values[position + 1], lerp_amount) + + @staticmethod + def smooth_step(colorfrom, colorto, amount): + return Color(Gloss.smooth_step(colorfrom.r, colorto.r, amount), Gloss.smooth_step(colorfrom.g, colorto.g, amount), Gloss.smooth_step(colorfrom.b, colorto.b, amount), Gloss.smooth_step(colorfrom.a, colorto.a, amount)) + + @staticmethod + def smooth_step2(colorfrom, colorto, amount): + return Color(Gloss.smooth_step2(colorfrom.r, colorto.r, amount), Gloss.smooth_step2(colorfrom.g, colorto.g, amount), Gloss.smooth_step2(colorfrom.b, colorto.b, amount), Gloss.smooth_step2(colorfrom.a, colorto.a, amount)) + + +class Point(object): + @staticmethod + def add(point1, point2): + return (point1[0] + point2[0], point1[1] + point2[1]) + + def bounce_both(point1, point2, amount, overshoot = 20): + return (Gloss.bounce_both(point1[0], point2[0], amount, overshoot), Gloss.bounce_both(point1[1], point2[1], amount, overshoot)) + + def bounce_in(point1, point2, amount, overshoot = 20): + return (Gloss.bounce_in(point1[0], point2[0], amount, overshoot), Gloss.bounce_in(point1[1], point2[1], amount, overshoot)) + + def bounce_out(point1, point2, amount, overshoot = 20): + return (Gloss.bounce_out(point1[0], point2[0], amount, overshoot), Gloss.bounce_out(point1[1], point2[1], amount, overshoot)) + + @staticmethod + def distance(point1, point2): + return math.sqrt(Point.distance_squared(point1, point2)) + + @staticmethod + def distance_squared(point1, point2): + return (point1[0] - point2[0]) * (point1[0] - point2[0]) + (point1[1] - point2[1]) * (point1[1] - point2[1]) + + @staticmethod + def length(point): + return math.sqrt(Point.length_squared(point)) + + @staticmethod + def length_squared(point): + return (point[0] * point[0]) + (point[1] * point[1]) + + @staticmethod + def lerp(point1, point2, amount): + return (Gloss.lerp(point1[0], point2[0], amount), Gloss.lerp(point1[1], point2[1], amount)) + + @staticmethod + def lerp2(point1, point2, amount): + return (Gloss.lerp2(point1[0], point2[0], amount), Gloss.lerp2(point1[1], point2[1], amount)) + + @staticmethod + def multi_lerp(values, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + if result == 1.0: + return values[len(values) - 1] + + num_items = len(values) + position = int(math.floor(amount * (num_items - 1))) # what was the minimum item we were up to? + individual_lerp = 1.0 / (num_items - 1) # how much is each step? + current_lerp = amount - position * individual_lerp # how far through the current step are we? + lerp_amount = current_lerp / individual_lerp # how much is that compared to a full step + + return Point.lerp(values[position], values[position + 1], lerp_amount) + + @staticmethod + def multiply(point1, to): + if to.__class__.__name__ == "tuple": + return (point1[0] * to[0], point1[1] * to[1]) + else: + return (point1[0] * to, point1[1] * to) + + @staticmethod + def normalize(point): + length = self.length() + factor = 1.0 / length + return (point[0] * factor, point[1] * factor) + + @staticmethod + def smooth_step(point1, point2, amount): + return (Gloss.smooth_step(point1[0], point2[0], amount), Gloss.smooth_step(point1[1], point2[1], amount)) + + @staticmethod + def smooth_step2(point1, point2, amount): + return (Gloss.smooth_step2(point1[0], point2[0], amount), Gloss.smooth_step2(point1[1], point2[1], amount)) + + @staticmethod + def subtract(point1, point2): + return (point1[0] - point2[0], point1[1] - point2[1]) + + +class Gloss(object): + VERSION = 0.9 + + PI_OVER_2 = math.pi / 2.0 + PI_OVER_4 = math.pi / 4.0 + TWO_PI = math.pi * 2.0 + + Color.WHITE = Color(1, 1, 1, 1) + Color.RED = Color(1, 0, 0, 1) + Color.GREEN = Color(0, 1, 0, 1) + Color.BLUE = Color(0, 0, 1, 1) + Color.BLACK = Color(0, 0, 0, 1) + Color.CORNFLOWER_BLUE = Color(0.392156863, 0.584313725, 0.929411765, 1) # used for clearing the screen to a safe value + Color.PURPLE = Color(0.5, 0, 0.5, 1) # used for clearing rendertargets to a safe value + Color.TRANSPARENT_WHITE = Color(1, 1, 1, 0) + + Point.ZERO = (0, 0) + + picking = False + enable_texturing = True + running_slowly = False + + total_seconds = 0 + + sprite_click_tracking = False # set to True when any sprite has an OnClick method attached + last_clicked_sprite = None # the sprite that was clicked most recently + + joysticks = [] + auto_particle_systems = [] + sprites = [] + + @staticmethod + def bounce_both(value1, value2, amount, overshoot = 20): + overshoot *= 0.25949 + + value2 -= value1 + amount /= 0.5 + + if (amount < 1): + return value2 / 2 * (amount * amount * ((overshoot + 1) * amount - overshoot)) + value1 + else: + amount -= 2 + return value2 / 2 * (amount * amount * ((overshoot + 1) * amount + overshoot) + 2) + value1 + + @staticmethod + def bounce_in(value1, value2, amount, overshoot = 20): + overshoot *= 0.170158 + value2 -= value1 + + return value2 * amount * amount * ((overshoot + 1) * amount - overshoot) + value1; + + @staticmethod + def bounce_out(value1, value2, amount, overshoot = 20): + overshoot *= 0.170158 + amount = amount / 1.0 - 1 + value2 -= value1 + return value2 * (amount * amount * ((overshoot + 1) * amount + overshoot) + 1) + value1; + + @staticmethod + def draw_box(position = (0, 0), width = 128, height = 128, rotation = 0.0, origin = (0, 0), scale = 1, color = Color.WHITE): + glPushMatrix() + + glColor4f(color.r, color.g, color.b, color.a) + glDisable(GL_TEXTURE_2D) + + boxwidth = width * scale + boxheight = height * scale + + if origin is None: + originx = boxwidth / 2 + originy = boxheight / 2 + else: + originx = origin[0] * scale + originy = origin[1] * scale + + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + glBegin(GL_QUADS) + glVertex2f(-originx, boxheight - originy) + glVertex2f(boxwidth - originx, boxheight - originy) + glVertex2f(boxwidth - originx, -originy) + glVertex2f(-originx, -originy) + + glEnd() + + glEnable(GL_TEXTURE_2D) + glPopMatrix() + + @staticmethod + def draw_line(start, finish, color = Color.WHITE, width = 1.0): + glPushMatrix() + glColor4f(color.r, color.g, color.b, color.a) + glLineWidth(width) + + glDisable(GL_TEXTURE_2D) + + glBegin(GL_LINES) + glVertex2f(start[0], start[1]) + glVertex2f(finish[0], finish[1]) + glEnd() + + glEnable(GL_TEXTURE_2D) + glPopMatrix() + + @staticmethod + def draw_lines(lines, color = Color.WHITE, width = 1.0, join = False): + glPushMatrix() + glColor4f(color.r, color.g, color.b, color.a) + glLineWidth(width) + + glDisable(GL_TEXTURE_2D) + + if join: + glBegin(GL_LINE_LOOP) + else: + glBegin(GL_LINE_STRIP) + + for line in lines: + glVertex2f(line[0], line[1]) + + glEnd() + + glEnable(GL_TEXTURE_2D) + glPopMatrix() + + @staticmethod + def draw_triangle(points = [(0, 0), (-50, 100), (50, 100)], position = (0,0), rotation = 0.0, origin = (0, 0), scale = 1, color = Color.WHITE): + glPushMatrix() + + glColor4f(color.r, color.g, color.b, color.a) + glDisable(GL_TEXTURE_2D) + glDisable(GL_CULL_FACE) # don't give people the hassle of thinking about clockwise vs anti-clockwise + + if origin is None: + x1 = points[0][0] + x2 = points[1][0] + x3 = points[2][0] + y1 = points[0][1] + y2 = points[1][1] + y3 = points[2][1] + + originx = (x1 + x2 + x3) / 3.0 + originy = (y1 + y2 + y3) / 3.0 + else: + originx = origin[0] + originy = origin[1] + + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + glBegin(GL_TRIANGLES) + glVertex2f((points[0][0] - originx) * scale, (points[0][1] - originy) * scale) + glVertex2f((points[1][0] - originx) * scale, (points[1][1] - originy) * scale) + glVertex2f((points[2][0] - originx) * scale, (points[2][1] - originy) * scale) + glEnd() + + glEnable(GL_TEXTURE_2D) + glEnable(GL_CULL_FACE) + glPopMatrix() + + @staticmethod + def fill(texture = None, color = Color.WHITE, top = Color.CORNFLOWER_BLUE, bottom = Color.CORNFLOWER_BLUE, vertical = True): + # never draw backgrounds when picking + if Gloss.picking: + return + + if texture is not None: + width = Gloss.viewport_size[0] + height = Gloss.viewport_size[1] + + glPushMatrix() + + glColor4f(color.r, color.g, color.b, color.a) + glBindTexture(GL_TEXTURE_2D, texture.surface) + + glBegin(GL_TRIANGLE_STRIP) + glTexCoord2f(0, texture.height_ratio); glVertex2f(0, height) + glTexCoord2f(texture.width_ratio, texture.height_ratio); glVertex2f(width, height) + glTexCoord2f(0, 1); glVertex2f(0, 0) + glTexCoord2f(texture.width_ratio, 1); glVertex2f(width, 0) + glEnd() + + glPopMatrix() + else: + # if we're still here, draw the polygon without texture using gradient colors + if Gloss.enable_texturing: + glDisable(GL_TEXTURE_2D) + + width = Gloss.viewport_size[0] + height = Gloss.viewport_size[1] + + glPushMatrix() + + if vertical: + glBegin(GL_TRIANGLE_STRIP) + glColor4f(bottom.r, bottom.g, bottom.b, bottom.a); glVertex2f(0, height) + glColor4f(bottom.r, bottom.g, bottom.b, bottom.a); glVertex2f(width, height) + glColor4f(top.r, top.g, top.b, top.a); glVertex2f(0, 0) + glColor4f(top.r, top.g, top.b, top.a); glVertex2f(width, 0) + glEnd() + else: + glBegin(GL_TRIANGLE_STRIP) + glColor4f(top.r, top.g, top.b, top.a); glVertex2f(0, height) + glColor4f(bottom.r, bottom.g, bottom.b, bottom.a); glVertex2f(width, height) + glColor4f(top.r, top.g, top.b, top.a); glVertex2f(0, 0) + glColor4f(bottom.r, bottom.g, bottom.b, bottom.a); glVertex2f(width, 0) + glEnd() + + if Gloss.enable_texturing: + glEnable(GL_TEXTURE_2D) + + glPopMatrix() + + @staticmethod + def clamp(value, minval, maxval): + if value > maxval: + value = maxval + elif value < minval: + value = minval + + return value + + @staticmethod + def clear(color = Color.CORNFLOWER_BLUE): + glClearColor(color.r, color.g, color.b, color.a) + glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) + + @staticmethod + def hermite(value1, tangent1, value2, tangent2, amount): + AmountSquared = amount * amount + AmountCubed = AmountSquared * amount + + + if amount is 0.0: + result = value1 + elif amount is 1.0: + result = value2 + else: + result = (2 * value1 - 2 * value2 + tangent2 + tangent1) * AmountCubed + (3 * value2 - 3 * value1 - 2 * tangent1 - tangent2) * AmountSquared + tangent1 * amount + value1 + + return result + + @staticmethod + def lerp(value1, value2, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + return value1 + (value2 - value1) * result + + @staticmethod + def lerp2(value1, value2, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + + if result > 0.5: + return value2 + (value1 - value2) * ((result - 0.5) * 2) + else: + return value1 + (value2 - value1) * (result * 2) + + @staticmethod + def multi_lerp(values, amount): + # this method lets people lerp through multiple numbers, eg (0, 1, 2) with + # lerp amount 0.5 would return 1. It works by figuring out where in the values list + # we're up to, seeing how far we've moved towards the next position. + + result = Gloss.clamp(amount, 0.0, 1.0) + if result == 1.0: + return values[len(values) - 1] + + num_items = len(values) + position = int(math.floor(amount * (num_items - 1))) # what was the minimum item we were up to? + individual_lerp = 1.0 / (num_items - 1) # how much is each step? + current_lerp = amount - position * individual_lerp # how far through the current step are we? + lerp_amount = current_lerp / individual_lerp # how much is that compared to a full step + + return Gloss.lerp(values[position], values[position + 1], lerp_amount) + + @staticmethod + def next_po2(value): + logbase2 = (math.log(value) / math.log(2)) + return int(round(pow(2, math.ceil(logbase2)))) + + @staticmethod + def smooth_step(value1, value2, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + result = Gloss.hermite(value1, 0.0, value2, 0.0, result) + return result + + @staticmethod + def smooth_step2(value1, value2, amount): + result = Gloss.clamp(amount, 0.0, 1.0) + + if result > 0.5: + result = Gloss.hermite(value2, 0.0, value1, 0.0, (result - 0.5) * 2) + else: + result = Gloss.hermite(value1, 0.0, value2, 0.0, result * 2) + + return result + + @staticmethod + def rand_float(value1, value2): + return random.random() * (value2 - value1) + value1 + + + @staticmethod + def save_screenshot(filename): + if Gloss.redraw_needed: + Gloss.active_game.gloss_internal_draw() + + glFinish() + glPixelStorei(GL_PACK_ALIGNMENT, 4) + glPixelStorei(GL_PACK_ROW_LENGTH, 0) + glPixelStorei(GL_PACK_SKIP_ROWS, 0) + glPixelStorei(GL_PACK_SKIP_PIXELS, 0) + + data = glReadPixels(0, 0, Gloss.viewport_size[0], Gloss.viewport_size[1], GL_RGBA, GL_UNSIGNED_BYTE) + + surface = pygame.image.fromstring(data, (Gloss.viewport_size[0], Gloss.viewport_size[1]), 'RGBA', 1) + pygame.image.save(surface, filename) + + @staticmethod + def set_scene_tint(color): + glLightModelfv( GL_LIGHT_MODEL_AMBIENT, ((color.r, color.g, color.b, color.a)) ) + + @staticmethod + def to_radians(degrees): + return degrees * 0.017453292519943295769236907685 + + @staticmethod + def enable_picking(): + Gloss.picking = True + glDisable(GL_LIGHTING) + glDisable(GL_TEXTURE_2D) + Gloss.enable_texturing = False + + @staticmethod + def disable_picking(): + Gloss.picking = False + glEnable(GL_LIGHTING) + glEnable(GL_TEXTURE_2D) + Gloss.enable_texturing = True + + @staticmethod + def select_object(pos): + Gloss.enable_picking() + Gloss.active_game.gloss_internal_draw() + + pixels = glReadPixelsub(pos[0], Gloss.viewport_size[1] - pos[1], 1, 1, GL_RGBA) + + r = pixels[0][0][0] + g = pixels[0][0][1] + b = pixels[0][0][2] + + Gloss.disable_picking() + + for sprite in Gloss.sprites: + if (sprite.pick_color[0] == r) and sprite.pick_color[1] == g and sprite.pick_color[2] == b: + if sprite._on_click is not None: + # a function has been attached here - call it! + sprite._on_click(sprite) + + Gloss.last_clicked_sprite = sprite + + return sprite + + return None + + +class Texture(object): + def __init__(self, source): + self.surface = None + + if (source.__class__.__name__ == "str") or (source.__class__.__name__ == "unicode"): + try: + surface = pygame.image.load(source) + except: + print("Unable to load texture " + source + ".") + sys.exit(1) + else: + surface = source + + width = surface.get_width() + height = surface.get_height() + + self.width = width + self.height = height + self.half_width = self.width / 2 + self.half_height = self.height / 2 + + po2width = Gloss.next_po2(width) + po2height = Gloss.next_po2(height) + + if (po2width > Gloss.MaxTextureSize or po2height > Gloss.MaxTextureSize): + print "Fatal error: texture at " + path + " is bigger than the maximum supported texture size of " + str(Gloss.MaxTextureSize) + sys.exit(1) + + self.width_ratio = (self.width / po2width) + self.height_ratio = 1 - (self.height / po2height) + + if (width != po2width or height != po2height): + tmpsurface = pygame.Surface((po2width, po2height), SRCALPHA, 32) + tmpsurface.blit(surface, (0,0)) + surface = tmpsurface + + data = pygame.image.tostring(surface, "RGBA", 1) + + self.surface = glGenTextures(1) + glBindTexture(GL_TEXTURE_2D, self.surface) + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, po2width, po2height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data) + + def __del__(self): + if self.surface is not None: + # before we try freeing this memory, be careful: Python may have unloaded the OpenGL module by now, in which case just bail out + if glDeleteTextures is not None: + glDeleteTextures(self.surface) + self.surface = None + + def draw(self, position = (0, 0), rotation = 0.0, origin = (0, 0), scale = 1, color = Color.WHITE): + # never draw textures if picking + if Gloss.picking: + return + + texwidth = self.width * scale + texheight = self.height * scale + + if origin is None: + originx = texwidth / 2 + originy = texheight / 2 + else: + originx = origin[0] * scale + originy = origin[1] * scale + + glPushMatrix() + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + glColor4f(color.r, color.g, color.b, color.a) + + glBindTexture(GL_TEXTURE_2D, self.surface) + + glBegin(GL_TRIANGLE_STRIP) + glTexCoord2f(0, self.height_ratio); glVertex2f(-originx, texheight - originy) + glTexCoord2f(self.width_ratio, self.height_ratio); glVertex2f(texwidth - originx, texheight - originy) + glTexCoord2f(0, 1); glVertex2f(-originx, -originy) + glTexCoord2f(self.width_ratio, 1); glVertex2f(texwidth - originx, -originy) + glEnd() + + glPopMatrix() + +class Sprite(object): + next_id = 1 + pick_r = 0 + pick_g = 0 + pick_b = 0 + + def __init__(self, texture, position = None): + self.id = str(Sprite.next_id) + Sprite.next_id += 1 + + self.texture = texture + + if position is None: + self.position = (0, 0) + else: + self.position = position + + Sprite.pick_r += 1 + if Sprite.pick_r > 255: + Sprite.pick_r = 0 + Sprite.pick_g += 1 + if Sprite.pick_g > 255: + Sprite.pick_g = 0 + Sprite.pick_b += 1 + + self.pick_color = (Sprite.pick_r, Sprite.pick_g, Sprite.pick_b, 255) + + self._on_click = None + + Gloss.sprites.append(weakref.ref(self)) + + def __del__(self): + # remove any dead weak references from the sprite list + for i in reversed(range(len(Gloss.sprites))): + if Gloss.sprites[i]() is None: + del Gloss.sprites[i] + + def get_on_click(self): + return self._on_click + + def set_on_click(self, value): + self._on_click = value + Gloss.sprite_click_tracking = True + + on_click = property(get_on_click, set_on_click) + + + def draw(self, position = None, rotation = 0.0, origin = (0, 0), scale = 1, color = Color.WHITE): + texwidth = self.texture.width * scale + texheight = self.texture.height * scale + + if origin is None: + originx = texwidth / 2 + originy = texheight / 2 + else: + originx = origin[0] * scale + originy = origin[1] * scale + + if position is None: + position = self.position + + glPushMatrix() + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + if Gloss.picking is False: + glColor4f(color.r, color.g, color.b, color.a) + else: + glColor3ub(self.pick_color[0], self.pick_color[1], self.pick_color[2]) + + glBindTexture(GL_TEXTURE_2D, self.texture.surface) + + glBegin(GL_TRIANGLE_STRIP) + glTexCoord2f(0, self.texture.height_ratio); glVertex2f(-originx, texheight - originy) + glTexCoord2f(self.texture.width_ratio, self.texture.height_ratio); glVertex2f(texwidth - originx, texheight - originy) + glTexCoord2f(0, 1); glVertex2f(-originx, -originy) + glTexCoord2f(self.texture.width_ratio, 1); glVertex2f(texwidth - originx, -originy) + glEnd() + + glPopMatrix() + + def move(self, x, y): + self.position = (self.position[0] + x, self.position[1] + y) + + def move_to(self, x = None, y = None): + if x is None: + if y is None: + return + + self.position = (self.position[0], y) + return + + if y is None: + self.position = (x, self.position[1]) + else: + self.position = (x, y) + +class ParticleSystem(object): + additive = False + + def __init__(self, texture, position = None, lifespan = -1, creationspeed = None, initialparticles = 50, particlelifespan = 1000, minspeed = 50, maxspeed = 250, minrotation = 0, maxrotation = 0, minscale = 1.0, maxscale = 1.0, growth = 0.0, wind = None, drag = None, startcolor = Color.WHITE, endcolor = Color.TRANSPARENT_WHITE, onfinish = None, name = ""): + Gloss.auto_particle_systems.append(self) + + self.name = name + self.on_finish = onfinish + + self.texture = texture + + if position is None: + self.position = (0, 0) + else: + self.position = position + + self.created_time = Gloss.tick_count + self.last_particle_created_time = Gloss.tick_count + + self.frozen = False # used to stop particle systems being automatically updated + self.alive = True # set to be False when destroyed + + self.lifespan = lifespan + self.creation_speed = creationspeed + self.initial_particles = initialparticles + self.particle_lifespan = particlelifespan + + self.start_color = startcolor + self.end_color = endcolor + self.particle_speed_min = minspeed + self.particle_speed_max = maxspeed + self.particle_rotation_min = minrotation + self.particle_rotation_max = maxrotation + self.particle_scale_min = minscale + self.particle_scale_max = maxscale + self.particle_growth = growth + self.particle_drag = drag + self.particle_wind = wind + + self.particles = [] + + for i in range(initialparticles): + self.create_particle() + + def __del__(self): + self.particles = [] # destroy all particles now + + def draw(self): + if self.alive is False: + return + + # never draw particle systems if picking + if Gloss.picking: + return + + if self.additive: + glBlendFunc(GL_SRC_ALPHA, GL_ONE) + + for particle in self.particles: + self.texture.draw(position = particle.position, rotation = particle.rotation, origin = None, scale = particle.scale + (particle.anim_pos * self.particle_growth), color = particle.color) + + if self.additive: + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) + + def update(self): + # kill off old particle systems + if (self.lifespan == -1): + # long-term particle systems also need to be auto-removed if they haven't done anything for a little while + if len(self.particles) == 0: + return False + else: + # if we have finished our life and all our particles are dead, return false so that the game can remove us from the list of particle systems + if self.created_time + self.lifespan < Gloss.tick_count: + return False + + + # do we need to create a new particle? + if (self.creation_speed is not None and self.last_particle_created_time + self.creation_speed < Gloss.tick_count): + self.create_particle() + + #cache the current wind and drag amounts to save calculation in the particle loop + if self.particle_wind is not None: + current_wind = Point.multiply(self.particle_wind, Gloss.elapsed_seconds) + + if self.particle_drag is not None: + current_drag = Gloss.elapsed_seconds * self.particle_drag + + for i in reversed(range(len(self.particles))): + particle = self.particles[i] + + if particle.created_time + self.particle_lifespan < Gloss.tick_count: + del self.particles[i] + + particle.position = Point.add(particle.position, Point.multiply(particle.velocity, Gloss.elapsed_seconds)) + + if self.particle_wind is not None: + particle.position = Point.add(particle.position, current_wind) + + particle.anim_pos = Gloss.clamp((Gloss.tick_count - particle.created_time) / self.particle_lifespan, 0.0, 1.0) + particle.color = Color.lerp(self.start_color, self.end_color, particle.anim_pos) + + if self.particle_drag is not None: + particle.velocity = Point.subtract(particle.velocity, Point.multiply(particle.velocity, current_drag)) + + if (Point.length_squared(particle.velocity) <= 0): + particle.velocity = Point.ZERO + + return True + + def create_particle(self): + particle = Particle() + + particle.created_time = Gloss.tick_count + particle.position = self.position + particle.rotation = Gloss.rand_float(self.particle_rotation_min, self.particle_rotation_max) + particle.scale = Gloss.rand_float(self.particle_scale_min, self.particle_scale_max) + + angle = random.random() * Gloss.TWO_PI + particle.velocity = Point.multiply((math.cos(angle), math.sin(angle)), Gloss.rand_float(self.particle_speed_min, self.particle_speed_max)) + + self.last_particle_created_time = Gloss.tick_count + + self.particles.append(particle) + +class Particle: + def __init__(self): + self.anim_pos = 0.0 + self.color = Color.WHITE + + +class RenderTarget: + def __init__(self, width = 512, height = 512): + self.buffer = None + self.surface = None + self.width = width + self.height = height + self.half_width = width / 2.0 + self.half_height = height / 2.0 + + # create the framebuffer + temp = glGenFramebuffersEXT(1) + self.buffer = temp + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, self.buffer) + + # create a texture for rendering + temp = glGenTextures(1) + self.surface = temp + + glActiveTexture(GL_TEXTURE0) + glBindTexture(GL_TEXTURE_2D, self.surface) + + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, width, height, 0, GL_RGBA, GL_FLOAT, None) + + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, self.surface, 0) + + status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT) + if status != GL_FRAMEBUFFER_COMPLETE_EXT: + return + + Gloss.clear(Color.PURPLE) + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0) # we don't need this activated yet, so unbind it for now + + # start rendering to this framebuffer + def activate(self): + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, self.buffer) + Gloss.viewport_size = self.width, self.height + glViewport(0, 0, self.width, self.height) + + glMatrixMode(GL_PROJECTION) + glPushMatrix() + glLoadIdentity() + glOrtho(0, self.width, self.height, 0, -100, 100) + glMatrixMode(GL_MODELVIEW) + glPushMatrix() + glLoadIdentity() + + # stop rendering to this framebuffer + def deactivate(self): + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0) + Gloss.viewport_size = Gloss.screen_resolution + glViewport(0, 0, Gloss.screen_resolution[0], Gloss.screen_resolution[1]) + + glMatrixMode(GL_PROJECTION) + glPopMatrix() + glMatrixMode(GL_MODELVIEW) + glPopMatrix() + + + # destroy this framebuffer and free allocated resources. + def __del__(self): + glDeleteFramebuffersEXT(1, [self.buffer]) + glDeleteTextures(1, [self.surface]) + self.buffer = None + self.surface = None + + # draw the contents of the buffer to the screen + def draw(self, position, width = None, height = None, rotation = 0.0, origin = (0, 0), scale = 1, color = Color.WHITE): + # always draw this texture, even when picking + glEnable(GL_TEXTURE_2D) + + if width is None: width = self.width + if height is None: height = self.height + + texheight = height * scale + texwidth = width * scale + + if origin is None: + originx = texwidth / 2 + originy = texheight / 2 + else: + originx = origin[0] * scale + originy = origin[1] * scale + + glPushMatrix() + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + if Gloss.picking is False: + glColor4f(color.r, color.g, color.b, color.a) + else: + # when picking, use pure white so that all textures inside this are visible + glColor4f(1, 1, 1, 1) + + glBindTexture(GL_TEXTURE_2D, self.surface) + + glBegin(GL_TRIANGLE_STRIP) + glTexCoord2f(0, 0); glVertex2f(-originx, texheight - originy) + glTexCoord2f(1, 0); glVertex2f(texwidth - originx, texheight - originy) + glTexCoord2f(0, 1); glVertex2f(-originx, -originy) + glTexCoord2f(1, 1); glVertex2f(texwidth - originx, -originy) + glEnd() + + # disable texturing if we're picking + if Gloss.enable_texturing is False: + glDisable(GL_TEXTURE_2D) + + glPopMatrix() + +class SpriteFont(object): + def __init__(self, filename, size = 18, bold = False, underline = False, startcharacter = 32, endcharacter = 126): + self.font = pygame.font.Font(filename, size) + self.font.set_underline(bold) + self.font.set_bold(underline) + + self.characters = {} + + for letter in range(startcharacter, endcharacter + 1): + self.characters[chr(letter)] = SpriteFontLetter(self.font, chr(letter)) + + self.line_height = self.characters["A"].height + + def draw(self, text = "Hello, Gloss!", position = (0, 0), rotation = 0.0, scale = 1.0, color = Color.WHITE, letterspacing = 0, linespacing = 0): + # don't draw text when picking + if Gloss.picking: + return + + currentwidth = 0 # used to reset to the start of the line when breaking + + if position is None: + position = self.position + + letterspacing *= scale + linespacing *= scale + + glPushMatrix() + glTranslatef(position[0], position[1], 0) + + if rotation is not 0.0: + glRotatef(rotation, 0, 0, 1) + + glColor4f(color.r, color.g, color.b, color.a) + + lines = text.splitlines() + + for line in lines: + for letter in line: + lettertexture = self.characters[letter] + + texheight = lettertexture.height * scale + texwidth = lettertexture.width * scale + + glBindTexture(GL_TEXTURE_2D, lettertexture.surface) + + glBegin(GL_TRIANGLE_STRIP) + glTexCoord2f(0, lettertexture.height_ratio); glVertex2f(0, texheight) + glTexCoord2f(lettertexture.width_ratio, lettertexture.height_ratio); glVertex2f(texwidth, texheight) + glTexCoord2f(0, 1); glVertex2f(0, 0) + glTexCoord2f(lettertexture.width_ratio, 1); glVertex2f(texwidth, 0) + glEnd() + + glTranslatef(texwidth + letterspacing, 0, 0) + currentwidth += texwidth + letterspacing + + # carriage return + line feed + glTranslatef(-currentwidth, texheight + linespacing, 0) + currentwidth = 0 + + glPopMatrix() + + def measure_string(self, text, scale = 1.0, letterspacing = 0, linespacing = 0): + currentwidth = 0 # used to track the width of the current line + maxwidth = 0 # used to track the width of the longest line + maxheight = 0 # used to track the height of the longest line + + letterspacing *= scale + linespacing *= scale + + lines = text.splitlines() + + for line in lines: + for letter in line: + lettertexture = self.characters[letter] + texheight = lettertexture.height * scale + texwidth = lettertexture.width * scale + currentwidth += texwidth + letterspacing + + # carriage return + line feed + if currentwidth > maxwidth: + maxwidth = currentwidth + + currentwidth = 0 + + maxheight += texheight + linespacing + + return maxwidth,maxheight + +class SpriteFontLetter(object): + def __init__(self, font, letter): + surface = font.render(letter, True, (255,255,255)) + + width = surface.get_width() + height = surface.get_height() + + self.width = width + self.height = height + self.half_width = self.width / 2 + self.half_height = self.height / 2 + + po2width = Gloss.next_po2(width) + po2height = Gloss.next_po2(height) + + if (po2width > Gloss.MaxTextureSize or po2height > Gloss.MaxTextureSize): + print "Fatal error: texture at " + path + " is bigger than the maximum supported texture size of " + str(Gloss.MaxTextureSize) + sys.exit(1) + + self.width_ratio = (self.width / po2width) + self.height_ratio = 1 - (self.height / po2height) + + if (width != po2width or height != po2height): + tmpsurface = pygame.Surface((po2width, po2height), SRCALPHA, 32) + tmpsurface.blit(surface, (0,0)) + surface = tmpsurface + + letter = pygame.image.tostring(surface, 'RGBA', 1) + + self.surface = glGenTextures(1) + glBindTexture(GL_TEXTURE_2D, self.surface) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, po2width, po2height, 0, GL_RGBA, GL_UNSIGNED_BYTE, letter) diff --git a/guess_all_words.py b/guess_all_words.py new file mode 100644 index 0000000..7d1a1cd --- /dev/null +++ b/guess_all_words.py @@ -0,0 +1,35 @@ +import nltk as n +from random import * +import re +word_list=n.corpus.words.words(); + +chr_list=[] +match_list=[] +while len(chr_list)<=9: + temp=chr(randint(ord('a'),ord('z'))); + if temp not in chr_list: + chr_list.append(temp); +print chr_list; + +# need to make a regexp out of it +def add_str(s1,s2):return s1+s2; +reg_string="["+reduce(add_str,chr_list)+"]*" +#print reg_string; +r=re.compile(reg_string) +# after making the regexp +for w in word_list: + if w==r.match(w).group(): + match_list.append(w); + +print len(match_list); + +correct_guess=[] +def check_word(word): + if word in match_list: + if word in correct_guess: + return "already guessed" + else: + correct_guess.append(word) + return "correct guess" + else: + return "wrong guess" \ No newline at end of file diff --git a/gun.png b/gun.png new file mode 100644 index 0000000..5d9160b Binary files /dev/null and b/gun.png differ diff --git a/hand_detection.py b/hand_detection.py new file mode 100644 index 0000000..bb082cf --- /dev/null +++ b/hand_detection.py @@ -0,0 +1,55 @@ +import SimpleCV as s +import math as m +import random +c=s.Camera() +d=s.Display() +i1=c.getImage().pixelize() +avgX=0 +absX=0 +ballPos=[320,240] +ballSpeedX=10+random.randint(0,5) +ballSpeedY=10+random.randint(0,5) +print ballPos +ballRadius=10 +while True: + i2=c.getImage().pixelize() + i3=(i2-i1)+(i1-i2) + i1=i2 + i3=i3.binarize(50).erode(3).dilate(3) + i3=i3.invert().flipHorizontal() + f=i3.findBlobs(minsize=200,threshval=50) + if f: + totalSum=0 + areaSum=0 + for temp in f: + areaSum+=temp.area() + totalSum+=temp.area()*temp.x + if areaSum!=0: + avgX=totalSum/areaSum + f.draw(width=3) + else: + print("None") + x_diff=(avgX-absX) + if m.copysign(x_diff,1)>=40: + absX+=m.copysign(40,x_diff) + else: + absX=avgX + #i3.drawText(text="Avg. X="+str(avgX),x=avgX,color=s.Color.AQUAMARINE) + i3.drawRectangle(absX-50,50,100,20) + print ballPos + if ballPos[0]-ballRadius<150: + ballSpeedX=-ballSpeedX + if ballPos[0]+ballRadius>640-150: + ballSpeedX=-ballSpeedX + if ballPos[1]+ballRadius>480: + ballSpeedY=-ballSpeedY + if (ballPos[0] in range(int(absX)-50,int(absX)+50)) and ((ballPos[1]-ballRadius) in range(50,70)): + ballSpeedY=-ballSpeedY + elif ballPos[1]-ballRadius<0: + print("Quitting "+str(ballPos)) + quit() + ballPos[0]+=ballSpeedX + ballPos[1]+=ballSpeedY + i3.drawCircle(tuple(ballPos),ballRadius,color=s.Color.AQUAMARINE) + #print(absX) + i3.save(d) \ No newline at end of file diff --git a/hand_detection2.py b/hand_detection2.py new file mode 100644 index 0000000..26985db --- /dev/null +++ b/hand_detection2.py @@ -0,0 +1,35 @@ +import SimpleCV as s +import math as m +import random +col=s.Color.RED +c=s.Camera() +d=s.Display() +i1=c.getImage() +i1a=i1.colorDistance(col).binarize(50).erode().dilate() +while True: + i2=c.getImage() + i2a=i2.hueDistance(col).binarize(10).show() +## i3=(i2a-i1a) +## i3=i3.dilate().erode().morphClose().flipHorizontal() +## i3.show() +## i1a=i2a +## +## f=i3.findBlobs(minsize=200) +## if f: +## f=f[-5:] +## totalSumX=0 +## totalSumY=0 +## areaSum=0 +## for temp in f: +## areaSum+=temp.area() +## totalSumX+=temp.area()*temp.x +## totalSumY+=temp.area()*temp.y +## if areaSum!=0: +## avgX=totalSumX/areaSum +## avgY=totalSumY/areaSum +## f.draw(width=3) +## i3.drawText(text="("+str(avgX)+","+str(avgY)+")",x=avgX,y=avgY,color=s.Color.AQUAMARINE) +#### f=i1.findBlobs(minsize=300) +#### if f: +#### f.draw(width=3) +## i3.save(d) \ No newline at end of file diff --git a/hello.txt b/hello.txt new file mode 100644 index 0000000..c42259e --- /dev/null +++ b/hello.txt @@ -0,0 +1 @@ +gggfg \ No newline at end of file diff --git a/how i want/pong.py b/how i want/pong.py new file mode 100644 index 0000000..3885442 --- /dev/null +++ b/how i want/pong.py @@ -0,0 +1,25 @@ +import pyFun +class pong(pyFun.fun_Game): + class bat(pyFun.fun_Class): + def __init__(self,up_key,down_key,*args,**kwargs): + super(bat,self).__init__(*args,**kwargs) + self.up_key=up_key + self.down_key=down_key + self.img=pyFun.shapes.rect(w=24,h=96) + + def action_create(self): + self.move_step=3 + + def action_key_press(self,key): + if key==self.up_key: + self.y-=self.move_step + if key==self.down_key: + self.y+=self.move_step + + def action_touch_room_boundary(self): + self.y=self.y_prev + +game=pong(width=760,height=640,fps=60) +game.bat(up_key=k_up,down_key=k_down,x=80,y=game.h/2) +game.bat(up_key=k_w,down_key=k_s,x=game.w-80,y=game.h/2) +game.run() \ No newline at end of file diff --git a/internal_right_left_gesture.py b/internal_right_left_gesture.py new file mode 100644 index 0000000..7f254be --- /dev/null +++ b/internal_right_left_gesture.py @@ -0,0 +1,76 @@ +import SimpleCV as s +import time +import simulate_keypress as press +#c=s.JpegStreamCamera(r"192.168.173.169:8080/videofeed") +c=s.Camera() +c1=time.clock() +gesture_time=30 +detection_sleep=False +blobs=[None]*gesture_time +#d=s.Display() +i1=c.getImage() +img_width_ori=i1.width +img_height=i1.height +i1=i1.crop(img_width_ori/4,0,img_width_ori*3/4,img_height/2).flipHorizontal() +img_width=img_width_ori/2 +count=0 +while True: + i2=c.getImage().crop(img_width_ori/4,0,img_width_ori*3/4,img_height/2).flipHorizontal() + i3=(i2-i1)+(i1-i2) + i1=i2 + i3=i3.stretch(10,255).erode(2).dilate(2) + f=i3.findBlobs(minsize=100) + blobs[count]=f + min_x_list=[] + #min_y_list=[] + max_x_list=[] + #max_y_list=[] + blobs_empty=True + count_blobs=0 + for blobs_temp in blobs: + count_blobs+=1 + if blobs_temp: + min_x_list.append([min(temp[0] for temp in blobs_temp.center()),count_blobs]) + #min_y_list.append([min(temp[1] for temp in blobs_temp.topLeftCorners()),count_blobs]) + max_x_list.append([max(temp[0] for temp in blobs_temp.center()),count_blobs]) + #max_y_list.append([min(temp[1] for temp in blobs_temp.bottomRightCorners()),count_blobs]) + blobs_empty=False + if not blobs_empty: + min_x=min([temp[0] for temp in min_x_list]) + left_step=min_x_list[[temp[0] for temp in min_x_list].index(min_x)][1] + #min_y=min([temp[0] for temp in min_y_list]) + max_x=max([temp[0] for temp in max_x_list]) + right_step=max_x_list[[temp[0] for temp in max_x_list].index(max_x)][1] + #max_y=max([temp[0] for temp in max_y_list]) + detection_width=abs(max_x-min_x) + if not detection_sleep and detection_width> img_width*0.80: + print("Detected") + blobs=[None]*gesture_time + print(right_step,left_step) + if right_step>left_step: + print("Left to right") + press.press_up() + else: + print("Right to left") + press.press_down() + print(c1) + detection_sleep=gesture_time*2 + else: + pass + #print("Not detected") + else: + min_x=None + min_y=None + max_x=None + max_y=None + if detection_sleep: + detection_sleep-=1 + if f: + f.draw(width=2) + #i3.show() + c2=time.clock() + #print(1/(c1-c2)) + c1=c2 + count+=1 + count=count%gesture_time +## i2.findSkintoneBlobs().show() \ No newline at end of file diff --git a/js/impress.js b/js/impress.js new file mode 100644 index 0000000..d57bc51 --- /dev/null +++ b/js/impress.js @@ -0,0 +1,800 @@ +/** + * impress.js + * + * impress.js is a presentation tool based on the power of CSS3 transforms and transitions + * in modern browsers and inspired by the idea behind prezi.com. + * + * + * Copyright 2011-2012 Bartek Szopka (@bartaz) + * + * Released under the MIT and GPL Licenses. + * + * ------------------------------------------------ + * author: Bartek Szopka + * version: 0.5.3 + * url: http://bartaz.github.com/impress.js/ + * source: http://github.com/bartaz/impress.js/ + */ + +/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true, + noarg:true, noempty:true, undef:true, strict:true, browser:true */ + +// You are one of those who like to know how thing work inside? +// Let me show you the cogs that make impress.js run... +(function ( document, window ) { + 'use strict'; + + // HELPER FUNCTIONS + + // `pfx` is a function that takes a standard CSS property name as a parameter + // and returns it's prefixed version valid for current browser it runs in. + // The code is heavily inspired by Modernizr http://www.modernizr.com/ + var pfx = (function () { + + var style = document.createElement('dummy').style, + prefixes = 'Webkit Moz O ms Khtml'.split(' '), + memory = {}; + + return function ( prop ) { + if ( typeof memory[ prop ] === "undefined" ) { + + var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), + props = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' '); + + memory[ prop ] = null; + for ( var i in props ) { + if ( style[ props[i] ] !== undefined ) { + memory[ prop ] = props[i]; + break; + } + } + + } + + return memory[ prop ]; + }; + + })(); + + // `arraify` takes an array-like object and turns it into real Array + // to make all the Array.prototype goodness available. + var arrayify = function ( a ) { + return [].slice.call( a ); + }; + + // `css` function applies the styles given in `props` object to the element + // given as `el`. It runs all property names through `pfx` function to make + // sure proper prefixed version of the property is used. + var css = function ( el, props ) { + var key, pkey; + for ( key in props ) { + if ( props.hasOwnProperty(key) ) { + pkey = pfx(key); + if ( pkey !== null ) { + el.style[pkey] = props[key]; + } + } + } + return el; + }; + + // `toNumber` takes a value given as `numeric` parameter and tries to turn + // it into a number. If it is not possible it returns 0 (or other value + // given as `fallback`). + var toNumber = function (numeric, fallback) { + return isNaN(numeric) ? (fallback || 0) : Number(numeric); + }; + + // `byId` returns element with given `id` - you probably have guessed that ;) + var byId = function ( id ) { + return document.getElementById(id); + }; + + // `$` returns first element for given CSS `selector` in the `context` of + // the given element or whole document. + var $ = function ( selector, context ) { + context = context || document; + return context.querySelector(selector); + }; + + // `$$` return an array of elements for given CSS `selector` in the `context` of + // the given element or whole document. + var $$ = function ( selector, context ) { + context = context || document; + return arrayify( context.querySelectorAll(selector) ); + }; + + // `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data + // and triggers it on element given as `el`. + var triggerEvent = function (el, eventName, detail) { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent(eventName, true, true, detail); + el.dispatchEvent(event); + }; + + // `translate` builds a translate transform string for given data. + var translate = function ( t ) { + return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) "; + }; + + // `rotate` builds a rotate transform string for given data. + // By default the rotations are in X Y Z order that can be reverted by passing `true` + // as second parameter. + var rotate = function ( r, revert ) { + var rX = " rotateX(" + r.x + "deg) ", + rY = " rotateY(" + r.y + "deg) ", + rZ = " rotateZ(" + r.z + "deg) "; + + return revert ? rZ+rY+rX : rX+rY+rZ; + }; + + // `scale` builds a scale transform string for given data. + var scale = function ( s ) { + return " scale(" + s + ") "; + }; + + // `perspective` builds a perspective transform string for given data. + var perspective = function ( p ) { + return " perspective(" + p + "px) "; + }; + + // `getElementFromHash` returns an element located by id from hash part of + // window location. + var getElementFromHash = function () { + // get id from url # by removing `#` or `#/` from the beginning, + // so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work + return byId( window.location.hash.replace(/^#\/?/,"") ); + }; + + // `computeWindowScale` counts the scale factor between window size and size + // defined for the presentation in the config. + var computeWindowScale = function ( config ) { + var hScale = window.innerHeight / config.height, + wScale = window.innerWidth / config.width, + scale = hScale > wScale ? wScale : hScale; + + if (config.maxScale && scale > config.maxScale) { + scale = config.maxScale; + } + + if (config.minScale && scale < config.minScale) { + scale = config.minScale; + } + + return scale; + }; + + // CHECK SUPPORT + var body = document.body; + + var ua = navigator.userAgent.toLowerCase(); + var impressSupported = + // browser should support CSS 3D transtorms + ( pfx("perspective") !== null ) && + + // and `classList` and `dataset` APIs + ( body.classList ) && + ( body.dataset ) && + + // but some mobile devices need to be blacklisted, + // because their CSS 3D support or hardware is not + // good enough to run impress.js properly, sorry... + ( ua.search(/(iphone)|(ipod)|(android)/) === -1 ); + + if (!impressSupported) { + // we can't be sure that `classList` is supported + body.className += " impress-not-supported "; + } else { + body.classList.remove("impress-not-supported"); + body.classList.add("impress-supported"); + } + + // GLOBALS AND DEFAULTS + + // This is were the root elements of all impress.js instances will be kept. + // Yes, this means you can have more than one instance on a page, but I'm not + // sure if it makes any sense in practice ;) + var roots = {}; + + // some default config values. + var defaults = { + width: 1024, + height: 768, + maxScale: 1, + minScale: 0, + + perspective: 1000, + + transitionDuration: 1000 + }; + + // it's just an empty function ... and a useless comment. + var empty = function () { return false; }; + + // IMPRESS.JS API + + // And that's where interesting things will start to happen. + // It's the core `impress` function that returns the impress.js API + // for a presentation based on the element with given id ('impress' + // by default). + var impress = window.impress = function ( rootId ) { + + // If impress.js is not supported by the browser return a dummy API + // it may not be a perfect solution but we return early and avoid + // running code that may use features not implemented in the browser. + if (!impressSupported) { + return { + init: empty, + goto: empty, + prev: empty, + next: empty + }; + } + + rootId = rootId || "impress"; + + // if given root is already initialized just return the API + if (roots["impress-root-" + rootId]) { + return roots["impress-root-" + rootId]; + } + + // data of all presentation steps + var stepsData = {}; + + // element of currently active step + var activeStep = null; + + // current state (position, rotation and scale) of the presentation + var currentState = null; + + // array of step elements + var steps = null; + + // configuration options + var config = null; + + // scale factor of the browser window + var windowScale = null; + + // root presentation elements + var root = byId( rootId ); + var canvas = document.createElement("div"); + + var initialized = false; + + // STEP EVENTS + // + // There are currently two step events triggered by impress.js + // `impress:stepenter` is triggered when the step is shown on the + // screen (the transition from the previous one is finished) and + // `impress:stepleave` is triggered when the step is left (the + // transition to next step just starts). + + // reference to last entered step + var lastEntered = null; + + // `onStepEnter` is called whenever the step element is entered + // but the event is triggered only if the step is different than + // last entered step. + var onStepEnter = function (step) { + if (lastEntered !== step) { + triggerEvent(step, "impress:stepenter"); + lastEntered = step; + } + }; + + // `onStepLeave` is called whenever the step element is left + // but the event is triggered only if the step is the same as + // last entered step. + var onStepLeave = function (step) { + if (lastEntered === step) { + triggerEvent(step, "impress:stepleave"); + lastEntered = null; + } + }; + + // `initStep` initializes given step element by reading data from its + // data attributes and setting correct styles. + var initStep = function ( el, idx ) { + var data = el.dataset, + step = { + translate: { + x: toNumber(data.x), + y: toNumber(data.y), + z: toNumber(data.z) + }, + rotate: { + x: toNumber(data.rotateX), + y: toNumber(data.rotateY), + z: toNumber(data.rotateZ || data.rotate) + }, + scale: toNumber(data.scale, 1), + el: el + }; + + if ( !el.id ) { + el.id = "step-" + (idx + 1); + } + + stepsData["impress-" + el.id] = step; + + css(el, { + position: "absolute", + transform: "translate(-50%,-50%)" + + translate(step.translate) + + rotate(step.rotate) + + scale(step.scale), + transformStyle: "preserve-3d" + }); + }; + + // `init` API function that initializes (and runs) the presentation. + var init = function () { + if (initialized) { return; } + + // First we set up the viewport for mobile devices. + // For some reason iPad goes nuts when it is not done properly. + var meta = $("meta[name='viewport']") || document.createElement("meta"); + meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no"; + if (meta.parentNode !== document.head) { + meta.name = 'viewport'; + document.head.appendChild(meta); + } + + // initialize configuration object + var rootData = root.dataset; + config = { + width: toNumber( rootData.width, defaults.width ), + height: toNumber( rootData.height, defaults.height ), + maxScale: toNumber( rootData.maxScale, defaults.maxScale ), + minScale: toNumber( rootData.minScale, defaults.minScale ), + perspective: toNumber( rootData.perspective, defaults.perspective ), + transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration ) + }; + + windowScale = computeWindowScale( config ); + + // wrap steps with "canvas" element + arrayify( root.childNodes ).forEach(function ( el ) { + canvas.appendChild( el ); + }); + root.appendChild(canvas); + + // set initial styles + document.documentElement.style.height = "100%"; + + css(body, { + height: "100%", + overflow: "hidden" + }); + + var rootStyles = { + position: "absolute", + transformOrigin: "top left", + transition: "all 0s ease-in-out", + transformStyle: "preserve-3d" + }; + + css(root, rootStyles); + css(root, { + top: "50%", + left: "50%", + transform: perspective( config.perspective/windowScale ) + scale( windowScale ) + }); + css(canvas, rootStyles); + + body.classList.remove("impress-disabled"); + body.classList.add("impress-enabled"); + + // get and init steps + steps = $$(".step", root); + steps.forEach( initStep ); + + // set a default initial state of the canvas + currentState = { + translate: { x: 0, y: 0, z: 0 }, + rotate: { x: 0, y: 0, z: 0 }, + scale: 1 + }; + + initialized = true; + + triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] }); + }; + + // `getStep` is a helper function that returns a step element defined by parameter. + // If a number is given, step with index given by the number is returned, if a string + // is given step element with such id is returned, if DOM element is given it is returned + // if it is a correct step element. + var getStep = function ( step ) { + if (typeof step === "number") { + step = step < 0 ? steps[ steps.length + step] : steps[ step ]; + } else if (typeof step === "string") { + step = byId(step); + } + return (step && step.id && stepsData["impress-" + step.id]) ? step : null; + }; + + // used to reset timeout for `impress:stepenter` event + var stepEnterTimeout = null; + + // `goto` API function that moves to step given with `el` parameter (by index, id or element), + // with a transition `duration` optionally given as second parameter. + var goto = function ( el, duration ) { + + if ( !initialized || !(el = getStep(el)) ) { + // presentation not initialized or given element is not a step + return false; + } + + // Sometimes it's possible to trigger focus on first link with some keyboard action. + // Browser in such a case tries to scroll the page to make this element visible + // (even that body overflow is set to hidden) and it breaks our careful positioning. + // + // So, as a lousy (and lazy) workaround we will make the page scroll back to the top + // whenever slide is selected + // + // If you are reading this and know any better way to handle it, I'll be glad to hear about it! + window.scrollTo(0, 0); + + var step = stepsData["impress-" + el.id]; + + if ( activeStep ) { + activeStep.classList.remove("active"); + body.classList.remove("impress-on-" + activeStep.id); + } + el.classList.add("active"); + + body.classList.add("impress-on-" + el.id); + + // compute target state of the canvas based on given step + var target = { + rotate: { + x: -step.rotate.x, + y: -step.rotate.y, + z: -step.rotate.z + }, + translate: { + x: -step.translate.x, + y: -step.translate.y, + z: -step.translate.z + }, + scale: 1 / step.scale + }; + + // Check if the transition is zooming in or not. + // + // This information is used to alter the transition style: + // when we are zooming in - we start with move and rotate transition + // and the scaling is delayed, but when we are zooming out we start + // with scaling down and move and rotation are delayed. + var zoomin = target.scale >= currentState.scale; + + duration = toNumber(duration, config.transitionDuration); + var delay = (duration / 2); + + // if the same step is re-selected, force computing window scaling, + // because it is likely to be caused by window resize + if (el === activeStep) { + windowScale = computeWindowScale(config); + } + + var targetScale = target.scale * windowScale; + + // trigger leave of currently active element (if it's not the same step again) + if (activeStep && activeStep !== el) { + onStepLeave(activeStep); + } + + // Now we alter transforms of `root` and `canvas` to trigger transitions. + // + // And here is why there are two elements: `root` and `canvas` - they are + // being animated separately: + // `root` is used for scaling and `canvas` for translate and rotations. + // Transitions on them are triggered with different delays (to make + // visually nice and 'natural' looking transitions), so we need to know + // that both of them are finished. + css(root, { + // to keep the perspective look similar for different scales + // we need to 'scale' the perspective, too + transform: perspective( config.perspective / targetScale ) + scale( targetScale ), + transitionDuration: duration + "ms", + transitionDelay: (zoomin ? delay : 0) + "ms" + }); + + css(canvas, { + transform: rotate(target.rotate, true) + translate(target.translate), + transitionDuration: duration + "ms", + transitionDelay: (zoomin ? 0 : delay) + "ms" + }); + + // Here is a tricky part... + // + // If there is no change in scale or no change in rotation and translation, it means there was actually + // no delay - because there was no transition on `root` or `canvas` elements. + // We want to trigger `impress:stepenter` event in the correct moment, so here we compare the current + // and target values to check if delay should be taken into account. + // + // I know that this `if` statement looks scary, but it's pretty simple when you know what is going on + // - it's simply comparing all the values. + if ( currentState.scale === target.scale || + (currentState.rotate.x === target.rotate.x && currentState.rotate.y === target.rotate.y && + currentState.rotate.z === target.rotate.z && currentState.translate.x === target.translate.x && + currentState.translate.y === target.translate.y && currentState.translate.z === target.translate.z) ) { + delay = 0; + } + + // store current state + currentState = target; + activeStep = el; + + // And here is where we trigger `impress:stepenter` event. + // We simply set up a timeout to fire it taking transition duration (and possible delay) into account. + // + // I really wanted to make it in more elegant way. The `transitionend` event seemed to be the best way + // to do it, but the fact that I'm using transitions on two separate elements and that the `transitionend` + // event is only triggered when there was a transition (change in the values) caused some bugs and + // made the code really complicated, cause I had to handle all the conditions separately. And it still + // needed a `setTimeout` fallback for the situations when there is no transition at all. + // So I decided that I'd rather make the code simpler than use shiny new `transitionend`. + // + // If you want learn something interesting and see how it was done with `transitionend` go back to + // version 0.5.2 of impress.js: http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js + window.clearTimeout(stepEnterTimeout); + stepEnterTimeout = window.setTimeout(function() { + onStepEnter(activeStep); + }, duration + delay); + + return el; + }; + + // `prev` API function goes to previous step (in document order) + var prev = function () { + var prev = steps.indexOf( activeStep ) - 1; + prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ]; + + return goto(prev); + }; + + // `next` API function goes to next step (in document order) + var next = function () { + var next = steps.indexOf( activeStep ) + 1; + next = next < steps.length ? steps[ next ] : steps[ 0 ]; + + return goto(next); + }; + + // Adding some useful classes to step elements. + // + // All the steps that have not been shown yet are given `future` class. + // When the step is entered the `future` class is removed and the `present` + // class is given. When the step is left `present` class is replaced with + // `past` class. + // + // So every step element is always in one of three possible states: + // `future`, `present` and `past`. + // + // There classes can be used in CSS to style different types of steps. + // For example the `present` class can be used to trigger some custom + // animations when step is shown. + root.addEventListener("impress:init", function(){ + // STEP CLASSES + steps.forEach(function (step) { + step.classList.add("future"); + }); + + root.addEventListener("impress:stepenter", function (event) { + event.target.classList.remove("past"); + event.target.classList.remove("future"); + event.target.classList.add("present"); + }, false); + + root.addEventListener("impress:stepleave", function (event) { + event.target.classList.remove("present"); + event.target.classList.add("past"); + }, false); + + }, false); + + // Adding hash change support. + root.addEventListener("impress:init", function(){ + + // last hash detected + var lastHash = ""; + + // `#/step-id` is used instead of `#step-id` to prevent default browser + // scrolling to element in hash. + // + // And it has to be set after animation finishes, because in Chrome it + // makes transtion laggy. + // BUG: http://code.google.com/p/chromium/issues/detail?id=62820 + root.addEventListener("impress:stepenter", function (event) { + window.location.hash = lastHash = "#/" + event.target.id; + }, false); + + window.addEventListener("hashchange", function () { + // When the step is entered hash in the location is updated + // (just few lines above from here), so the hash change is + // triggered and we would call `goto` again on the same element. + // + // To avoid this we store last entered hash and compare. + if (window.location.hash !== lastHash) { + goto( getElementFromHash() ); + } + }, false); + + // START + // by selecting step defined in url or first step of the presentation + goto(getElementFromHash() || steps[0], 0); + }, false); + + body.classList.add("impress-disabled"); + + // store and return API for given impress.js root element + return (roots[ "impress-root-" + rootId ] = { + init: init, + goto: goto, + next: next, + prev: prev + }); + + }; + + // flag that can be used in JS to check if browser have passed the support test + impress.supported = impressSupported; + +})(document, window); + +// NAVIGATION EVENTS + +// As you can see this part is separate from the impress.js core code. +// It's because these navigation actions only need what impress.js provides with +// its simple API. +// +// In future I think about moving it to make them optional, move to separate files +// and treat more like a 'plugins'. +(function ( document, window ) { + 'use strict'; + + // throttling function calls, by Remy Sharp + // http://remysharp.com/2010/07/21/throttling-function-calls/ + var throttle = function (fn, delay) { + var timer = null; + return function () { + var context = this, args = arguments; + clearTimeout(timer); + timer = setTimeout(function () { + fn.apply(context, args); + }, delay); + }; + }; + + // wait for impress.js to be initialized + document.addEventListener("impress:init", function (event) { + // Getting API from event data. + // So you don't event need to know what is the id of the root element + // or anything. `impress:init` event data gives you everything you + // need to control the presentation that was just initialized. + var api = event.detail.api; + + // KEYBOARD NAVIGATION HANDLERS + + // Prevent default keydown action when one of supported key is pressed. + document.addEventListener("keydown", function ( event ) { + if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { + event.preventDefault(); + } + }, false); + + // Trigger impress action (next or prev) on keyup. + + // Supported keys are: + // [space] - quite common in presentation software to move forward + // [up] [right] / [down] [left] - again common and natural addition, + // [pgdown] / [pgup] - often triggered by remote controllers, + // [tab] - this one is quite controversial, but the reason it ended up on + // this list is quite an interesting story... Remember that strange part + // in the impress.js code where window is scrolled to 0,0 on every presentation + // step, because sometimes browser scrolls viewport because of the focused element? + // Well, the [tab] key by default navigates around focusable elements, so clicking + // it very often caused scrolling to focused element and breaking impress.js + // positioning. I didn't want to just prevent this default action, so I used [tab] + // as another way to moving to next step... And yes, I know that for the sake of + // consistency I should add [shift+tab] as opposite action... + document.addEventListener("keyup", function ( event ) { + if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { + switch( event.keyCode ) { + case 33: // pg up + case 37: // left + case 38: // up + api.prev(); + break; + case 9: // tab + case 32: // space + case 34: // pg down + case 39: // right + case 40: // down + api.next(); + break; + } + + event.preventDefault(); + } + }, false); + + // delegated handler for clicking on the links to presentation steps + document.addEventListener("click", function ( event ) { + // event delegation with "bubbling" + // check if event target (or any of its parents is a link) + var target = event.target; + while ( (target.tagName !== "A") && + (target !== document.documentElement) ) { + target = target.parentNode; + } + + if ( target.tagName === "A" ) { + var href = target.getAttribute("href"); + + // if it's a link to presentation step, target this step + if ( href && href[0] === '#' ) { + target = document.getElementById( href.slice(1) ); + } + } + + if ( api.goto(target) ) { + event.stopImmediatePropagation(); + event.preventDefault(); + } + }, false); + + // delegated handler for clicking on step elements + document.addEventListener("click", function ( event ) { + var target = event.target; + // find closest step element that is not active + while ( !(target.classList.contains("step") && !target.classList.contains("active")) && + (target !== document.documentElement) ) { + target = target.parentNode; + } + + if ( api.goto(target) ) { + event.preventDefault(); + } + }, false); + + // touch handler to detect taps on the left and right side of the screen + // based on awesome work of @hakimel: https://github.com/hakimel/reveal.js + document.addEventListener("touchstart", function ( event ) { + if (event.touches.length === 1) { + var x = event.touches[0].clientX, + width = window.innerWidth * 0.3, + result = null; + + if ( x < width ) { + result = api.prev(); + } else if ( x > window.innerWidth - width ) { + result = api.next(); + } + + if (result) { + event.preventDefault(); + } + } + }, false); + + // rescale presentation when window is resized + window.addEventListener("resize", throttle(function () { + // force going to active step again, to trigger rescaling + api.goto( document.querySelector(".active"), 500 ); + }, 250), false); + + }, false); + +})(document, window); + +// THAT'S ALL FOLKS! +// +// Thanks for reading it all. +// Or thanks for scrolling down and reading the last part. +// +// I've learnt a lot when building impress.js and I hope this code and comments +// will help somebody learn at least some part of it. \ No newline at end of file diff --git a/logger.py b/logger.py new file mode 100644 index 0000000..e83758a --- /dev/null +++ b/logger.py @@ -0,0 +1,11 @@ +import pyHook, pythoncom,sys,logging +file_log=r"E:\Babu\log.txt" +def OnKeyboardEvent(event): + logging.basicConfig(filename=file_log,level=logging.DEBUG,format="%(message)s") + print chr(event.Ascii) + logging.log(10,chr(event.Ascii)) +hooks_manager=pyHook.HookManager() +hooks_manager.KeyDown=OnKeyboardEvent +hooks_manager.HookKeyboard() + +pythoncom.PumpMessages() \ No newline at end of file diff --git a/meta_practise.py b/meta_practise.py new file mode 100644 index 0000000..b9a6660 --- /dev/null +++ b/meta_practise.py @@ -0,0 +1,17 @@ +class C(): + + class mclass(type): + def __new__(mcs, name, bases, attributes): + # Do something clever with name, base or attributes + name="so_cool "+name + cls = type.__new__(mcs, name, bases, attributes) + # Do something cleverer with the class itself + print ("I've created class whose","name: ",name," mcs: ",mcs," bases: ",bases," attributes: ",attributes) + return cls + + class A(object): + "Customizing the creation of class A" + __metaclass__=C.mclass + + class B(A): + static = 1 diff --git a/module1.py b/module1.py new file mode 100644 index 0000000..c2711cb --- /dev/null +++ b/module1.py @@ -0,0 +1,41 @@ +# all imports +import pygame +from pygame.locals import * + +# init +pygame.init() + +# setting display +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Wtf is this??") + +# loading sprites and backgrounds +spr_cursor=pygame.image.load("sprite0.png").convert_alpha(); +back_0=pygame.image.load("result.png").convert(); + +# set up fonts +font_default=pygame.font.SysFont(None,40); + +# set up colour +c_grey=(128,128,128); + +# set up text +text=font_default.render("This is a text",True,c_grey); +textRect=text.get_rect(); +textRect.center=surf.get_rect().center + +# main game loop +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); + # draw + surf.blit(back_0,(0,0)); + surf.blit(text,textRect); + x,y=pygame.mouse.get_pos(); + x-=spr_cursor.get_width()/2; + y-=spr_cursor.get_height()/2; + surf.blit(spr_cursor,(x,y)); + + pygame.display.update(); \ No newline at end of file diff --git a/notebook project/note.py b/notebook project/note.py new file mode 100644 index 0000000..8a56db7 --- /dev/null +++ b/notebook project/note.py @@ -0,0 +1,55 @@ +import time; +class note: + def __init__(self,note_id,title,contents,tags=[]): + self.id=note_id; + self.title=title; + self.contents=contents; + self.tags=tags; + self.creationtime=time.localtime(); + #tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec supported + def search(self,term,where=None): + ''' "term" is the search term. + "where" is supported to search for only in title or contents or + tags -currently unused. + Currently searches for a whole word-better than searching + for letters''' + #ToDo1 search for the whole string and perfect match .. actually use + #option for partial and whole check + #ToDO2 make sure all checkings are string type or atleast permissible after notebook class + #ToDo3 implement "where" in this function + return bool(self.title.split(" ").count(term)) or bool(self.contents.split(" ").count(term)) or bool(self.tags.count(term)) ; + def edit(self,title="",contents="",tags=[],choice=1): + + '''Only mention required parameters.Choice must be given. Choice: 1 for replace, 2 for append. + Call example:edit(title="untitled",choice=1) will make the title "untitled". Rest unaffected''' + if title!="": + if choice==1: + self.title=title; + elif choice==2: + self.title+=title; + if contents!="": + if choice==1: + self.contents=contents; + elif choice==2: + self.contents+=contents; + if tags!=[]: + if choice==1: + self.tags=tags; + elif choice==2: + self.tags+=tags; + self.creationtime=time.localtime(); + + def _print_(self,which="all"): + #To print the details for debugging purpose..working + if which=="all": + print ("Id="+str(self.id)+"\nTitle="+self.title+"\ncontents="+self.contents+"\ntags="+str(self.tags)+"\ncreationtime="+str(self.creationtime)); + else: + print which+"=",;# trailing comma(,) is used to print without newline + #ToDo3 fix the above print so that a space is not printed between them + exec("print(str(self."+which+"))"); + +def main(): + pass + +if __name__ == '__main__': + main() diff --git a/notebook project/note_32.py b/notebook project/note_32.py new file mode 100644 index 0000000..7d336bd --- /dev/null +++ b/notebook project/note_32.py @@ -0,0 +1,54 @@ +import time; +class note: + def __init__(self,note_id,title,contents,tags=[]): + self.id=note_id; + self.title=title; + self.contents=contents; + self.tags=tags; + self.creationtime=time.localtime(); + #tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec supported + def search(self,term,where=None): + ''' "term" is the search term. + "where" is supported to search for only in title or contents or + tags -currently unused. + Currently searches for a whole word-better than searching + for letters''' + #ToDo1 search for the whole string and perfect match .. actually use + #option for partial and whole check + #ToDO2 make sure all checkings are string type or atleast permissible after notebook class + #ToDo3 implement "where" in this function + return bool(self.title.split(" ").count(term)) or bool(self.contents.split(" ").count(term)) or bool(self.tags.count(term)) ; + def edit(self,title="",contents="",tags=[],choice=1): + + '''Only mention required parameters.Choice must be given. Choice: 1 for replace, 2 for append. + Call example:edit(title="untitled",choice=1) will make the title "untitled". Rest unaffected''' + if title!="": + if choice==1: + self.title=title; + elif choice==2: + self.title+=title; + if contents!="": + if choice==1: + self.contents=contents; + elif choice==2: + self.contents+=contents; + if tags!=[]: + if choice==1: + self.tags=tags; + elif choice==2: + self.tags+=tags; + self.creationtime=time.localtime(); + + def _print_(self,which="all"): + #To print the details for debugging purpose..working + if which=="all": + print ("Id="+str(self.id)+"\nTitle="+self.title+"\ncontents="+self.contents+"\ntags="+str(self.tags)+"\ncreationtime="+str(self.creationtime)); + else: + print (which+"=",end='');# end='' is used to print without newline + exec("print(str(self."+which+"))"); + +def main(): + pass + +if __name__ == '__main__': + main() diff --git a/notebook project/notebook.py b/notebook project/notebook.py new file mode 100644 index 0000000..2b3dfd2 --- /dev/null +++ b/notebook project/notebook.py @@ -0,0 +1,25 @@ +from note import note; +class notebook: + def __init__(self): + self.note_id=0; + self.note_list=[]; + self.counter=0; + self.return_list=[]; + def create_note(self,title,contents,tags=[]): + self.note_id+=1; + self.note_list.append(note(self.note_id,title,contents,tags)); + def search(self,term,where=None): + self.return_list=[];#used for removing traces of previous search + for self.counter in range(self.note_id):#range(x) means to 0 to x-1 + if self.note_list[self.counter].search(term): + self.note_list[self.counter]._print_();#used for debugging + self.return_list.append(self.counter+1);#return_list return a list of id's where search is successfull + return self.return_list; + def open_note(self,id,which="all"): + self.note_list[id-1]._print_(which); + +def main(): + pass + +if __name__ == '__main__': + main() diff --git a/notebook project/notebook_32.py b/notebook project/notebook_32.py new file mode 100644 index 0000000..3e488d1 --- /dev/null +++ b/notebook project/notebook_32.py @@ -0,0 +1,25 @@ +from note_32 import note; +class notebook: + def __init__(self): + self.note_id=0; + self.note_list=[]; + self.counter=0; + self.return_list=[]; + def create_note(self,title,contents,tags=[]): + self.note_id+=1; + self.note_list.append(note(self.note_id,title,contents,tags)); + def search(self,term,where=None): + self.return_list=[];#used for removing traces of previous search + for self.counter in range(self.note_id):#range(x) means to 0 to x-1 + if self.note_list[self.counter].search(term): + self.note_list[self.counter]._print_();#used for debugging + self.return_list.append(self.counter+1);#return_list return a list of id's where search is successfull + return self.return_list; + def open_note(self,id,which="all"): + self.note_list[id-1]._print_(which); + +def main(): + pass + +if __name__ == '__main__': + main() diff --git a/notebook project/version specific.txt b/notebook project/version specific.txt new file mode 100644 index 0000000..e356c6b --- /dev/null +++ b/notebook project/version specific.txt @@ -0,0 +1,4 @@ +Whenever possible, version-unspecific code is written. +If there is a major incompatibility such that no one syntax will provide the same result in both versions, different version of the code is written. +The un-numbered version is supposed to contain 2.7 version specific code during dev time, but from time-to-time it is (if possible) made 3.2 compatible and the version 3.2 is updated (may need slight change). +.pyc files are not needed. \ No newline at end of file diff --git a/obj.py b/obj.py new file mode 100644 index 0000000..d399072 --- /dev/null +++ b/obj.py @@ -0,0 +1,30 @@ +import pyglet as p +list_class=[] +class meta_obj(type): + def __new__(cls,name,base,clsdict): + temp_class=type.__new__(cls,name,base,clsdict) + list_class.append(temp_class) + cls.priority_order=cls.depth=len(list_class) #by default, priority_order and depth depends on "when class was defined" + return temp_class + +class obj(p.sprite.Sprite): + __metaclass__=meta_obj + list_instance=[] + def __init__(self, *args, **kwargs): + super(PhysicalObject, self).__init__(*args, **kwargs) + list_instance.append(self) + self.velocity_x, self.velocity_y = 0.0, 0.0 # Velocity + self.list_update=[] + + def update(self, dt): + """This method should be called every frame.""" + + # Update position according to velocity and time + self.x += self.velocity_x * dt + self.y += self.velocity_y * dt + + for update_func in self.list_update: + update_func(dt) + + def remove_update(self,update_func): + self.list_update.remove(update_func) \ No newline at end of file diff --git a/outside_ball_detection.py b/outside_ball_detection.py new file mode 100644 index 0000000..2696295 --- /dev/null +++ b/outside_ball_detection.py @@ -0,0 +1,12 @@ +import SimpleCV as s +img=s.Image(r"http://i.imgur.com/8vrJAWN.png") # Replace with local copy for faster processing +img2=img.hueDistance(s.Color.YELLOW) # get hueDistance image +low=35 # Use step 7 to get these variables +high=50 +i2_stretched=img2.stretch(low,high) # Keep only the ball in greyscale (not black or white) and convert rest to black or white +i2_diff=img-i2_stretched.stretch(high,high) # Subtract white part of the previous image from original image +i2_stretched_2= i2_stretched.invert().stretch(255-low,255-low) +i_new=(i2_diff-i2_stretched_2) # Subtract black part of i2_stretched image from original image +blob_ball=i_new.morphOpen().findBlobs()[-1:] # Find the largest blob +blob_ball.draw(width=3,color=s.Color.AQUAMARINE) # Draw blob with width 3 +blob_ball.show() # Show detected blob \ No newline at end of file diff --git a/part.py b/part.py new file mode 100644 index 0000000..af89673 --- /dev/null +++ b/part.py @@ -0,0 +1,54 @@ +# all imports +import math; +import pygame; +from pygame.locals import * + +# init +pygame.init() + +# setting display +surf=pygame.display.set_mode((400,400)) +pygame.display.set_caption("Wtf is this??") + +class part(): + list=[]; + def __init__(self,x,y,sprite_filename,life): + self.x=x; + self.y=y; + self.xprevious=x; + self.yprevious=y; + self.life=life; + self.sprite=pygame.image.load(sprite_filename).convert(); + part.list.append(self); + + def draw_self(self): + surf.blit(self.sprite,(self.x-self.sprite.get_width()/2,self.y-self.sprite.get_height()/2)); + + +# game startup code +#a=part(200,200,"a.png"); +c=pygame.time.Clock(); + +# main game loop +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); + + c.tick(); + pygame.display.set_caption(str(c.get_fps())); + + surf.fill((255,255,255)); + x,y=pygame.mouse.get_pos(); + for count in range(1): + part(x,y,"a.png",600); + for count in part.list: + count.life-=1; + count.draw_self(); + if count.life<=0: + part.list.remove(count); + del count; + #print("Haha") + #a.draw_self(); + pygame.display.update(); \ No newline at end of file diff --git a/pass.py b/pass.py new file mode 100644 index 0000000..6664b7f --- /dev/null +++ b/pass.py @@ -0,0 +1,10 @@ +numb=0; +print("Type your super awesome password") +i=raw_input() +i.lower() +for letters in i: + l=ord(letters)-ord('a')+1 + for count in range(l): + numb=numb*10+1 + #print numb +print ("Take this bitch!! : "+str(numb)) diff --git a/pixelize.py b/pixelize.py new file mode 100644 index 0000000..4c12f39 --- /dev/null +++ b/pixelize.py @@ -0,0 +1,13 @@ +import SimpleCV as s +import math as m +import random +c=s.Camera() +d=s.Display() +i1=c.getImage() + +while d.isNotDone: + i2=c.getImage() + #i2=i2.pixelize(10) + i3=i1-i2 + i1=i2 + i3.save(d) \ No newline at end of file diff --git a/practise.py b/practise.py new file mode 100644 index 0000000..e3db668 --- /dev/null +++ b/practise.py @@ -0,0 +1,9 @@ +f=open(r"pyFun\base.py") +count=0 +numb=[] +for index,line in enumerate(f): + if line.strip()=="" or line.strip().startswith("#") or line.strip().startswith("'''") or line.strip().startswith("@"): + numb.append(index+1) + count+=1; +print str(numb) +print "Total useless lines "+str(count) \ No newline at end of file diff --git a/prime.py b/prime.py new file mode 100644 index 0000000..ef2044f --- /dev/null +++ b/prime.py @@ -0,0 +1,21 @@ +import math as m +tot=0 +def is_prime(x): + for count in range(2,int(m.sqrt(x))+1): + if x%count==0: + #print(count) + return False + else: + return True +def is_odd(x): + return not (x%2==0) + +max=300 + +for count1 in range(1,max): + if is_odd(count1) and not is_prime(count1): + print(count1) + tot+=1 + + +print(tot) \ No newline at end of file diff --git a/pyFun/Upcoming implementations.markdown b/pyFun/Upcoming implementations.markdown new file mode 100644 index 0000000..d956613 --- /dev/null +++ b/pyFun/Upcoming implementations.markdown @@ -0,0 +1,34 @@ +Upcoming in pyFun +----------------- +*** + +1. Circle class (__Doing__) and Tilted rect and Line class (subclassed from rect) +2. Image module (similar to GM sprites) + + Make a custom image object which should support + + Sprites and shapes, with good query hooks + + Easy shape drawing functions, may look at codes in turtle module and other similar ones. + + Animation (no. of frame, speed of frame, start(), pause(),resume(),stop()) + + Origin + + Strips + + Masking + + Collision query + + Cursor sprites + + Support backgrounds somehow and provide easy-to-use update-only-required-part-of-screen functions +3. Instance query module + + Support query about other classes and instances easily. + + Let use coding for other instances from another instance. Similar to with(other){do_it;} + + Provide interaction methods based on image module like + + Collision detection (between one object and another object|point|image) + + Outside room + + Is mouse click on this object? +4. Timer (alarm) module + * Support arbitrary number of timers and also tracking them with id. +5. Add other keyboard and mouse module extras like GM +6. Room support +6. Add events mentioned in GM "Other" event dropdown. +7. Surfaces +8. Particles +9. Sound module +10. Path module +11. Timeline module +12. Highscore api \ No newline at end of file diff --git a/pyFun/Upcoming implementations.txt b/pyFun/Upcoming implementations.txt new file mode 100644 index 0000000..d5fa3bc --- /dev/null +++ b/pyFun/Upcoming implementations.txt @@ -0,0 +1,33 @@ +Upcoming in pyFun +----------------- +*** + +1. Circle class (__Doing__) and Angled rect class (subclassed from rect) +2. Image module (similar to GM sprites) + + Make a custom image object which should support + + Sprites and shapes, with good query hooks + + Easy shape drawing functions, may look at codes in turtle module and other similar ones. + + Animation (no. of frame, speed of frame, start(), pause(),resume(),stop()) + + Origin + + Strips + + Masking + + Collision query + + Cursor sprites + + Support backgrounds somehow and provide easy-to-use update-only-required-part-of-screen functions +3. Instance query module + + Support query about other classes and instances easily. + + Let use coding for other instances from another instance. Similar to with(other){do_it;} + + Provide interaction methods based on image module like + + Collision detection (between one object and another object|point|image) + + Outside room + + Is mouse click on this object? +4. Timer (alarm) module + * Support arbitrary number of timers and also tracking them with id. +5. Add other keyboard and mouse module extras like GM +6. Add events mentioned in GM "Other" event dropdown. +7. Surfaces +8. Particles +9. Sound module +10. Path module +11. Timeline module +12. Highscore api \ No newline at end of file diff --git a/pyFun/base.py b/pyFun/base.py new file mode 100644 index 0000000..8a54700 --- /dev/null +++ b/pyFun/base.py @@ -0,0 +1,814 @@ +# only for python 2.x +from uniquelist import * # imports uniquelist +import pygame +import pygame.gfxdraw +from pygame.locals import * # imports the constants +from math import * +#Mouse constants +B_LEFT_CLICK=1 +B_RIGHT_CLICK=3 +B_MIDDLE_CLICK=2 +B_SCROLLUP=4 +B_SCROLLDOWN=5 + +# Direction constants +TOP=1 +LEFT=2 +BOTTOM=3 +RIGHT=4 + +class fun_Game(object): + list_class=uniquelist() + list_event=[] # event_list of this step + list_event_old=[] # event_list of the previous step + list_state_all_buttons=[] # A sequence of boolean representing the state of every key + list_state_all_buttons_old=[] # A sequence of boolean representing the state of every key of previous step + def __init__(self,width,height,fps=30): + pygame.init() + self.fps=fps + self.clock=pygame.time.Clock() + self.width=width + self.height=height + + def update_all_class(self): + for temp_cls in fun_Game.list_class: + for temp_count in temp_cls.list_instance: + temp_count.update() + + def _cache_event_list(self): + ''' Cache event_list in every step. + All events in fun_Game.list_event have a "type" property which are the usual constants. ''' + fun_Game.list_event_old=fun_Game.list_event # move current list to old list + fun_Game.list_state_all_buttons_old=fun_Game.list_state_all_buttons + + fun_Game.list_event=pygame.event.get() + fun_Game.list_state_all_buttons=pygame.key.get_pressed() #Returns a sequence of boolean representing the state of every key. Use key constant values for indexing. + #print fun_Game.list_event # debug message + # control access to list_event + # with getter, do something crazy for filtering + # or a filtering function + + def run(self): + self.screen=pygame.display.set_mode([self.width,self.height]) + while True: + self._cache_event_list() # Todo: Add other update-related functions + self.update_all_class() + # VERY IMPORTANT: Do a spare first step so that every variable / list gets initialised well. Start instant creation and execution from second step. + # IMPORTANT: First do all fun_Game related stuff before dealing with game objects. + self.clock.tick(self.fps) + self.screen.fill([50,100,150]) # Todo: Remove this debug statement + pygame.display.flip() # debug statement + #print(event) + #print(fun_Game.list_event_old) + # Todo - Add crazy functions to allow other objects and instances finding like GM + + #class fun_Game ends here + +class meta_fun_Class(type): + def __new__(cls,name,base,clsdict): + temp_class=type.__new__(cls,name,base,clsdict) + fun_Game.list_class.append(temp_class) + cls.priority_order=cls.depth=len(fun_Game.list_class) #by default, priority_order and depth depends on "when class was defined" + return temp_class + +class fun_Class(object): + __metaclass__=meta_fun_Class + list_instance=uniquelist() + #list_update_functions stores the list of functions to call in the given order. + #It can be used for injecting custom user functions (remember order). + list_update_functions=uniquelist() #action_draw not added as it depends on depth + list_check_functions=uniquelist() # all the check functions added here. what they do: if event_: action_ + + def __init__(self,x,y,img=None): + self.x=0 + self.y=0 + self.img=img #img should be a fun_Image, but lets do that later + fun_Class.list_instance.append(self) + self.action_create() + + def update(self): + '''calls all functions in list_update_functions in the given order''' + temp=None + for temp in fun_Class.list_update_functions: + temp(self) + + def draw(self): + # do some blitting depending on self.img + pass + + def register(list_to_register=None): + ''' Used as decorator: Adds the function to list_to_register ''' + def temp_func(what_to_register): + list_to_register.append(what_to_register) + return what_to_register + return temp_func + + @register(list_update_functions) + def action_begin_step(self): + pass + @register(list_update_functions) + def action_step(self): + tmp=self.event_mouse_click() + if tmp: + print tmp + print(self.mouse_get_focused()) + @register(list_update_functions) + def action_end_step(self): + pass + # creation and destroy event + def action_create(self): + ''' Better to use this function than overloading __init__() ''' + pass + def action_destroy(self): + ''' Executed when the instance is destroyed ''' + pass + def destroy(self): + action_destroy(self) + + # checks for all standard events -- functions named like check_ + # what they do: if event_: action_ + # so lets define event_,action_,check_ for each + + # keyboard handling (later move to keyboard module) + + # occurs if the key was held down continously since the last step + def event_key_pressed(self,key_value):#check if it works + if get_event_list(list_to_get=fun_Game.list_state_all_buttons)[key_value] \ + and get_event_list(list_to_get=fun_Game.list_state_all_buttons_old)[key_value]\ + and (not get_event_list(event_types=KEYUP,further_check_variable_name="key",further_check_value=key_value))\ + and (not get_event_list(event_types=KEYUP,further_check_variable_name="key",further_check_value=key_value,list_to_get=fun_Game.list_event_old)): + return True + + def action_key_pressed(self,key_value): + pass + def check_key_pressed(self): + pass # Todo: think about how to do it + + # occurs if the key is held at the moment (live) + def event_key_pressed_live(self,key_value):#check if it works + ''' Returns True if the key (represented by key_code) is currently pressed. + Problem is that this function is live. Returns True if the key is pressed at that moment. + So, for example, two calls in two consecutive steps may return True although the key has been left in the meantime. ''' + temp_all_buttons=get_event_list(list_to_get=fun_Game.list_state_all_buttons) #Returns a sequence of boolean representing the state of every key. Use key constant values for indexing. + if temp_all_buttons[key_value]: # indexing by key_value + return True + def action_key_pressed_live(self,key_value): + pass + def check_key_pressed_live(self): + temp_all_buttons=get_event_list(list_to_get=fun_Game.list_state_all_buttons) #Returns a sequence of boolean representing the state of every key. Use key constant values for indexing. + for temp in range(len(temp_all_buttons)): # temp represents the key code in numbers as it is the index of list_state_all_buttons indirectly + if temp_all_buttons[temp]: + self.action_key_pressed_live(temp) #temp is the keycode + + # occurs if a key press occurs (i.e. pushed down) + # key repetations may occur as the list is cached per step and there might be multiple (same key)press per step. + def event_key_down(self,key=None): + if key == None: + return get_event_list(KEYDOWN) + else: + return get_event_list(KEYDOWN,"key",key) + def action_key_down(self,key): + pass + def check_key_down(self): + for temp in get_event_list(KEYDOWN): + action_key_down(self,temp.key) + + + #probably wierd thing to do - define all <>_key_down as equivalent to <>_key_press + event_key_press = event_key_down + action_key_press = action_key_down + check_key_press = check_key_down + + # occurs if key is released + def event_key_up(self,key=None): + if key==None: + return get_event_list(KEYUP) + else: + return get_event_list(KEYUP,"key",key) + def action_key_up(self,key): + pass + def check_key_up(self): + for temp in get_event_list(KEYUP): + action_key_up(self,temp.key) + # Todo: Do other key and keyboard related functions (look at GM for related functions) + # Mouse handling (later move it to mouse module) + #Mouse constants (defined at top - move them to a constants module, which will be imported in the global namespace) + #mouse click + def event_mouse_click(self,button=None): + if button==None: + return get_event_list(event_types=MOUSEBUTTONDOWN) + else: + return get_event_list(event_types=MOUSEBUTTONDOWN,further_check_variable_name="button",further_check_value=button) + def action_mouse_click(self,button): + pass + def check_mouse_click(self): + list_temp=get_event_list(event_types=MOUSEBUTTONDOWN) + for temp in list_temp: + action_mouse_click(temp.button) + #mouse get pressed + def event_mouse_get_pressed(self,button=None): + ''' event_mouse_get_pressed() -> tuple looking like (1,0,0) i.e. ( left_click_state, middle_click_state, right_click_state ). + Use an index which is (corresponding_constant - 1). For eg event_mouse_get_pressed()[0] returns left click state. + event_mouse_get_pressed(button) -> Returns 0 or 1 depending on pressed or not. ''' + if button==None: + return pygame.mouse.get_pressed() + else: + return pygame.mouse.get_pressed()[button-1] # because the tuple returned has o-based indexing + # end of mouse handling + # other mouse-based functions + def mouse_get_focused(self): + return pygame.mouse.get_focused() + def mouse_set_visible(self,bool_value): + return pygame.mouse.set_visible(bool_value) + def mouse_get_rel(self): + ''' Returns relative movement of the mouse since the last call to this function. + mouse_get_rel() -> (x,y) ''' + return pygame.mouse.get_rel() + def mouse_set_cursor_image(self,image=None): + pass # todo: complete after the image part is done + # implement mouse_pos as variable + @property + def mouse_pos(self): + ''' mouse_pos -> (x,y) + mouse_pos = [x,y] -> Sets cursor position ''' + return pygame.mouse.get_pos() + @mouse_pos.setter + def mouse_pos(self,val): + ''' val should be a list [x,y] ''' + if not isinstance(val,list): + raise TypeError("val should be a list [x,y]") + pygame.mouse.set_pos(val) + + # implement mouse_x as variable + @property + def mouse_x(self): + ''' mouse_x -> x + mouse_x = some_x -> Sets cursor x position ''' + return pygame.mouse.get_pos()[0] # get_pos -> (x,y) + @mouse_x.setter + def mouse_x(self,x): + pygame.mouse.set_pos([x,mouse_y]) + + # implement mouse_y as variable + @property + def mouse_y(self): + ''' mouse_y -> y + mouse_y = some_y -> Sets cursor y position ''' + return pygame.mouse.get_pos()[1] # get_pos -> (x,y) + @mouse_y.setter + def mouse_y(self,y): + pygame.mouse.set_pos([mouse_x,y]) + # end of mouse-related function + #other various events + + def event_intersect_room_boundary(self): # todo: test after image part is done + ''' Checks if the object (its image bounding box) is intersecting the room boundary, but not totally outside the room. + Returns direction constants like TOP, LEFT, BOTTOM, RIGHT. ''' + if (self.x+self.image.bbox.width/2)>fun_Game.room_width and not (self.x-self.image.bbox.width/2)>fun_Game.room_width: + return RIGHT # all constants defined at global level + elif (self.y+self.image.bbox.height/2)>fun_Game.room_height and not (self.y-self.image.bbox.height/2)>fun_Game.room_height: + return BOTTOM + elif (self.x-self.image.bbox.width/2)<0 and not (self.x+self.image.bbox.width/2)<0: + return LEFT + elif (self.y-self.image.bbox.height/2)<0 and not (self.y+self.image.bbox.height/2)<0: + return TOP + def action_intersect_room_boundary(self): + pass + def check_intersect_room_boundary(self): + if event_intersect_room_boundary(self): + action_intersect_room_boundary(self) + + def event_outside_room_boundary(self): + ''' Checks if the object (its image bounding box) is totally outside room. + Returns direction constants like TOP, LEFT, BOTTOM, RIGHT. ''' + if (self.x-self.image.bbox.width/2)>fun_Game.room_width: + return RIGHT # all constants defined at global level + elif (self.y-self.image.bbox.height/2)>fun_Game.room_height: + return BOTTOM + elif (self.x+self.image.bbox.width/2)<0: + return LEFT + elif (self.y+self.image.bbox.height/2)<0: + return TOP + + # end of fun_Class +# Other classes +class Circle(object): + def __init__(self,(x,y),radius,color=None): + self.center=[x,y] + self.radius=radius + self.color=color + + @property + def center_x(self): + return self.center[0] + @property + def center_y(self): + return self.center[1] + @center_x.setter + def center_x(self,new_x): + self.center[0]=new_x + @center_y.setter + def center_y(self,new_y): + self.center[1]=new_y + @property + def bbox(self): + left=self.center_x-self.radius + top=self.center_y-self.radius + width=self.radius*2 + height=self.radius*2 + return pygame.Rect(left, top, width, height) + # todo: remember about the colour. document - center is list unlike tuple in case of rect. + def __repr__(self): + return "{0.__class__}( center={0.center}, radius={0.radius}, color={0.color})".format(self) + + def copy(self): + return Circle((self.center_x,self.center_y),self.radius,self.color) + + def move(self,move_x,move_y): + return Circle((self.center_x+move_x,self.center_y+move_y),self.radius,self.color) + + def move_ip(self,move_x,move_y): + self.center_x+=move_x + self.center_y+=move_y + + def inflate(self,inflate_radius): + return Circle((self.center_x,self.center_y),self.radius+inflate_radius,self.color) + + def inflate_ip(self,inflate_radius): + self.radius+=inflate_radius + + def is_inside(self,another_circle): + ''' Checks if this circle is fully inside another_circle ''' + return distance( self.center, another_circle.center )another_rect.right or (self.center_y+self.radius)another_rect.bottom ) + + def collide_list_rect(self,list_rect): + ''' Returns True if collides with any of the rect in the list. ''' + for temp_rect in list_rect: + if collide_rect(self,temp_rect): + return True + else: + return False + + def collide_list_all_rect(self,list_rect): + ''' Returns True if collides with all the rect in the list. ''' + for temp_rect in list_rect: + if not collide_rect(self,temp_rect): + return False + else: + return True + + @classmethod + def get_circumcircle_from_rect(cls,another_rect):# create a circle with same center and radius=sqrt(w^2+h^2) + import math + return cls(another_rect.center, math.sqrt(another_rect.width**2+another_rect.height**2)/2) + + @classmethod + def get_incircle_from_rect(cls,another_rect): # radius of incircle is same as the min of width and height (as it's not a square) + import math + return cls(another_rect.center,min(another_rect.width,another_rect.height)) + + # union -needs to be a circle *within* which the union of the bounding box of all the circles can be fit. + # warning about all the union functions: The circles returned are not necessarily the most optimum union circle, but it will surely contain the others. + def _union(self,circle_1,circle_2): + ''' self.__union((new_center_x,new_center_y),new_radius) -> ([x,y],radius) which are the resultant values. ''' + return self.circumcircle_from_rect(circle_1.bbox.union(circle_2.bbox)) + + def union(self,new_circle): + ''' Returns a new circle which is the union of these two circles ''' + return self._union(self,new_circle) + + def union_ip(self,new_circle): + ''' Turns this circle into a circle which is a union of these two circles. ''' + temp_circle=self._union(self,new_circle) + self.center, self.radius = temp_circle.center, temp_circle.radius + + def _unionall(self,circle_1,seq_circle): # list_circle_params : [((x1,y1),radius_1), ((x2,y2),radius_2), ...] + ''' returns ([x,y],radius) for the resultant union of all circles. + sequence_circle must be a sequence of circles. ''' + return self.circumcircle_from_rect(circle_1.bbox.unionall([temp_circle.bbox for temp_circle in seq_circle])) + + def unionall(self,seq_circle): #seq_circle: sequence of circles + return self._unionall(self,seq_circle) + + def unionall_ip(self,seq_circle): + ''' Turns this circle into a circle which is a union of this circles with all circles in seq_circle''' + temp_circle=self._unionall(self,seq_circle) + self.center, self.radius = temp_circle.center, temp_circle.radius + + # draw functions + def draw(self,surface,(x,y)=(None,None),color=None,width=1,use_antialiasing=False): + ''' Draws this Circle on surface. It must be of width and height greater than or equal to its bbox. + (x,y)->co-ordinates whether the center of the Circle should be drawn on the surface. + width argument doesnt work with antialiasing. width=0 makes it filled. + antialiasing may break in later versions as the backend pygame.gfxdraw is experimental. + color falls back first to Circle.color (if present) and then to blue color.''' + if (x,y)==(None,None): + (x,y)=self.center + if not color: + if self.color: + color=self.color + else: + color=pygame.Color("blue") + + if not use_antialiasing: + pygame.draw.circle(surface, color,(x,y), self.radius, width) + else: + pygame.gfxdraw.aacircle(surface, x, y, self.radius, color) + + def get_surface(self,surface=None,flags=0): + ''' Returns a new surface with dimensions of (Circle.bbox.width,Circle.bbox.width) and other properties as surface. + This Circle can be safely drawn on it.''' + if surface: + return pygame.Surface((self.bbox.width,self.bbox.height),flags,surface) + else: + return pygame.Surface((self.bbox.width,self.bbox.height),flags) + + def get_surface_drawn(self,(x,y)=(None,None),color=None,width=1,use_antialiasing=False,surface=None,flags=0): + ''' Returns a surface which has the tiltedRect drwan on it. ''' + temp_surf=self.get_surface(surface,flags) + self.draw(temp_surf,(x,y),color,width,use_antialiasing) + return temp_surf + + # end of Circle class + #start of tiltedRect class +class tiltedRect(pygame.Rect): + # make a metaclass which wraps a lot of functions just like move is defined below. + # functions to be wrapped - move,inflate + # Think about them - clamp,clip,union,fit,contains,collide + # the metaclass can probably also change the __str__ of the class. + # About drawing - use pygame.transform.rotate to get a rotated surface to be drawed. + def __init__(self,(left,top),(width,height),angle,centered_coords=False,color=None): + ''' Angle in degrees. + centered_coords -> whether the (left,top) is actually intended to be (center_x,center_y) or not. + I.e. if centered_coords==True the (left,top) co-ordinates are used as (center_x,center_y) co-ordinates of the tiltedRect''' + self.angle=angle + self.color=color + if centered_coords==True: + left=left-width/2 + top=top-height/2 + super(tiltedRect,self).__init__((left,top),(width,height)) + def __copy__(self): + return tiltedRect((self.left,self.top),(self.width,self.height),self.angle) + def __repr__(self): + return "{0.__class__.__name__}((top={0.top}, left={0.left}), (width={0.width}, height={0.height}), angle={0.angle}, color={0.color})".format(self) + @classmethod + def create_from_rect(cls,another_rect,angle): + return cls((another_rect.left,another_rect.top),(another_rect.width,another_rect.height),angle) + def get_rect(self): + return pygame.Rect((left,top),(width,height)) + def move(self,x,y): + return self.create_from_rect(super(tiltedRect,self).move(x,y),self.angle) + def inflate(self,x,y): + return self.create_from_rect(super(tiltedRect,self).inflate(x,y),self.angle) + def normalize(self): # not sure what this one does - ask others + return self.create_from_rect(super(tiltedRect,self).normalize(),self.angle) + def rotate(self,some_angle): + temp_return=self.__copy__() + temp_return.angle+=some_angle + return temp_return + def rotate_ip(self,some_angle): + self.angle+=some_angle + + def rotate_point_relative(self,x,y,theta=None):#generalise the parameters to accept x1,y1,x2,y2,rot_angle + ''' x,y -> Absolute co-ords of the point to be rotated wrt to the rectangles center. self.centerx,self.centery are internally substracted from them. + theta -> angle (in degrees) by which the point is to be rotated. Default value is self.angle. + Returns absolute positions of the points after rotation. ''' + if theta==None: + theta=self.angle + return self.rotate_point(x,y,self.centerx,self.centery,theta) + + @classmethod + def rotate_point(cls,x,y,origin_x,origin_y,theta): # to be allowed as rotate_point(class) + ''' x,y -> Absolute co-ords of the point to be rotated. origin_x,origin_y are internally substracted from them. + (origin_x,origin_y) -> Absolute co-ords of the origin wrt to which the point will be rotated + theta -> angle (in degrees) by which the point is to be rotated. + Returns absolute positions of the points after rotation. ''' + import math + x_diff=x-origin_x + y_diff=y-origin_y + y_diff=-y_diff # -y_diff because of the inverted nature of y co-ordinate system in pygame + r=math.sqrt(x_diff**2+y_diff**2) + initial_angle=math.atan2(y_diff,x_diff) + final_angle=initial_angle+math.radians(theta) + rotated_x_diff=r*math.cos(final_angle) + rotated_y_diff=r*math.sin(final_angle) + rotated_y_diff = -rotated_y_diff # - used for same reason as above + rotated_x = rotated_x_diff + origin_x + rotated_y = rotated_y_diff + origin_y + return (rotated_x,rotated_y) + + def rotate_point_polar(self,r,initial_angle,theta=None): + ''' theta and initial_angle in radians. + initial_angle ->angle r makes with horizontal. + theta -> angle to be rotated by. ''' + if theta==None: + theta=self.angle + final_angle=initial_angle+theta + rotated_x=r*math.cos(final_angle) + rotated_y=r*math.sin(final_angle) + return (rotated_x,rotated_y) + + @property + def bottomleft_rotated(self): + temp=self.bottomleft + return self.rotate_point_relative(temp[0],temp[1]) + @property + def topleft_rotated(self): + temp=self.topleft + return self.rotate_point_relative(temp[0],temp[1]) + @property + def bottomright_rotated(self): + temp=self.bottomright + return self.rotate_point_relative(temp[0],temp[1]) + @property + def topright_rotated(self): + temp=self.topright + return self.rotate_point_relative(temp[0],temp[1]) + @property + def midleft_rotated(self): + temp=self.midleft + return self.rotate_point_relative(temp[0],temp[1]) + @property + def midright_rotated(self): + temp=self.midright + return self.rotate_point_relative(temp[0],temp[1]) + @property + def midtop_rotated(self): + temp=self.midtop + return self.rotate_point_relative(temp[0],temp[1]) + @property + def midbottom_rotated(self): + temp=self.midbottom + return self.rotate_point_relative(temp[0],temp[1]) + + # related to bounding box + @property + def bbox(self): + list_x=[self.topleft_rotated[0],self.topright_rotated[0],self.bottomleft_rotated[0],self.bottomright_rotated[0]] + list_y=[self.topleft_rotated[1],self.topright_rotated[1],self.bottomleft_rotated[1],self.bottomright_rotated[1]] + min_x=floor(min(list_x)) + max_x=ceil(max(list_x)) + min_y=floor(min(list_y)) + max_y=ceil(max(list_y)) + return pygame.Rect((min_x,min_y),(max_x-min_x,max_y-min_y)) + @property + def bbox_fixed(self): + diagonal=sqrt(self.width**2+self.height**2) + diagonal=ceil(diagonal) + return pygame.Rect((floor(self.centerx-diagonal/2),floor(self.centery-diagonal/2)),(diagonal+1,diagonal+1)) #diagonal+1 is used to redue corner issues, which still might be here. + # corners + @property + def corners(self): + ''' List of actual (rotated) corners. ''' + return [self.topleft_rotated,self.topright_rotated,self.bottomright_rotated,self.bottomleft_rotated] + @property + def corners_relative(self): + return [(temp[0]-self.centerx,temp[1]-self.centery) for temp in self.corners] + + # circles related to the rect + def get_circumcircle(self): + Circle.get_circumcircle_from_rect(self.bbox) + def get_incircle(self): + Circle.get_incircle_from_rect(self.bbox) + + # collision events + def collide_point(self,*args): + ''' collidepoint(x,y) -> + collidepoint((x,y)) -> ''' + temp_len=len(args) + temp_x=None + temp_y=None + if temp_len==2: + temp_x=args[0] + temp_y=args[1] + elif temp_len==1: + if len(args[0])==2: + temp_x,temp_y=args[0] + else: + raise TypeError("Arguments are of incorrect type") + else: + raise TypeError("Arguments are of incorrect type") + if temp_x==None or temp_y==None: + raise TypeError("argument must contain two numbers") + return pygame.Rect((self.left,self.top),(self.width,self.height)).collidepoint(self.rotate_point_relative(temp_x,temp_y)) + + def collide_rect(self,rect): + ''' Tests if it collides with rect, which should be instance of rect class. ''' + # First test:whether bbox collides with rect. If not, no collision. + if not self.bbox.colliderect(rect): + return False + else: + # Todo: Else sure test: Need to do line class first. Test if any line of titedRect collides with any line of (instead, the whole) rect. + pass + + # draw functions + def draw(self,surface,(x,y)=(None,None),color=None,width=1,centered=False,use_antialiasing=False,blend=True): + ''' Draws this tiltedRect on surf_to_draw_on. It must be of width and height greater or equal to its bbox. + (x,y)->co-ordinates whether the lefttop point of its bbox should be drawn on the surface. Use centered=True to provide co-ords of the center instead. + If centered=True, by default, it draws at the center of the surface provided. + width argument doesnt work with antialiasing. width=0 makes it filled. + blend argument works only with antialiasing. The boolean blend argument set to true will blend the shades with existing shades instead of overwriting them. + color falls back first to tiltedRect.color (if present) and then to blue color.''' + if not centered: + if (x,y)==(None,None): + (x,y)=(0,0) + iter_corners=[(temp[0]+x-self.bbox.left,temp[1]+y-self.bbox.top) for temp in self.corners] + else: + if (x,y)==(None,None): + x,y=surface.get_width()/2,surface.get_height()/2 + iter_corners=[(temp[0]+x,temp[1]+y) for temp in self.corners_relative] + if not color: + if self.color: + color=self.color + else: + color=pygame.Color("blue") + if not use_antialiasing: + pygame.draw.polygon(surface, color, iter_corners, width) + #pygame.gfxdraw.polygon(surface, iter_corners, color)#gfxdraw module doesnt work + else: + pygame.draw.aalines(surface, color, True, iter_corners, blend) + def get_surface(self,surface=None,flags=0,fixed=False): + ''' Returns a new surface with dimensions of (tiltedRect.bbox.width,tiltedRect.bbox.width) and other properties as surface. + This tiltedRect can be safely drawn on it.''' + if not fixed: + width,height=self.bbox.width,self.bbox.height + else: + width,height=self.bbox_fixed.width,self.bbox_fixed.height + + return pygame.Surface((width,height),flags,surface) + def get_surface_drawn(self,(x,y)=(None,None),color=None,width=1,fixed=False,use_antialiasing=False,blend=True,surface=None,flags=0): + ''' Returns a surface which has the tiltedRect drwan on it. ''' + temp_surf=self.get_surface(surface,flags,fixed) + if not fixed: + self.draw(temp_surf,(x,y),color,width,False,use_antialiasing,blend) + else: + self.draw(temp_surf,(x,y),color,width,True,use_antialiasing,blend) + return temp_surf + + def collide_tiltedRect(self,another_tiltedRect): + '''Checks whether this tiltedRect collides with another_titltedrect, which must be a instance of titledRect. ''' + # Rotates both tiltedRect by -another_tiltedRect.angle. So, another_tiltedRect becomes a Rect called temp_Rect. + # Then check if the rotated version of this tiltedRect (temp_tiltedRect) collides with the obtained Rect. + temp_tiltedRect=self.rotate(-another_tiltedRect.angle) + temp_Rect=another_tiltedRect.get_rect() + return temp_tiltedRect.colliderect(temp_Rect) + +# functions outside all classes +def get_event_list(event_types=None,further_check_variable_name=None,further_check_value=None,list_to_get=None):#list_to_get is attached to a constant list here + ''' Get the required events from the event_list. + get_event_list([event_types],[further_check_variable_name],further_check_value=None,list_to_get=fun_Game.list_event): + event_types (optional): event_name|list[event_name] + get_event_list() -> returns whole event_list(to be precise, list_to_get) + get_event_list(events) -> returns event_list(to be precise, list_to_get) filtered to contain only "events" + get_event_list([events],further_check_variable_name="var_name",further_check_value=value) -> + returns sub-list containing those elements of get_event_list([events]) for which var_name=value + Potential candidates for list_to_get -> fun_Game.list_event, fun_Game.list_event_old, fun_Game.list_state_all_buttons, fun_Game.list_state_all_buttons_old''' + if list_to_get==None: + list_to_get=fun_Game.list_event_old + if further_check_variable_name: + further_check_enabled=True + else: + further_check_enabled=False + if event_types: + if not hasattr(event_types,"__iter__"): + event_types=[event_types] # if not iterable, make a list out of it + def func_filter(): + list_return=[] + if not event_types: + return list_to_get + for temp_1 in list_to_get: # all events in fun_Game.list_event have a "type" property + for temp_2 in event_types: + if temp_1.type==temp_2: + list_return.append(temp_1) + return list_return + def further_check_filter(temp_list): # returns part of temp_list which passes further_check + list_return=[] + if further_check_enabled: + for temp in temp_list: + if getattr(temp,further_check_variable_name)==further_check_value:# may raise error if further_check_variable_name is not present for all members of the list + list_return.append(temp) + else: + list_return=temp_list + return list_return + return further_check_filter(func_filter()) # returns elements common in fun_Game.list_events and events which are accepted after further_check +# end of get_event_list() + +def distance((x1,y1),(x2,y2)): # Maybe make a non-square rooted function for comparison (faster) + import math + return(math.sqrt((x2-x1)**2+(y2-y1)**2)) + +#following constants are required for the next function +UNION=1 +INTERSECTION=2 +DIFFERENCE=3 +ADD=4 +MAKE_IT_VARIABLE_LIST=5 # for each member (usually objects) in the list, it is replaced by one of its variables +def operation_on_lists(operation,list1,list2=None,variable_name=None): + ''' operation_on_lists(operation, list1, list2) -> list + Does operation involving list1 and list2. + variable_name is required only for MAKE_IT_VARIABLE_LIST operation. It is a string representing the variable name + Valid operations are UNION, INTERSECTION, DIFFERENCE, ADD, MAKE_IT_VARIABLE_list ''' + def intersection(): + if list2==None: + raise TypeError("second argument i.e. list2 should be a list") + list_return=[] + for temp1 in list1: + for temp2 in list2: + if temp1==temp2: + list_return.append(temp1) + return list_return + def union(): + if list2==None: + raise TypeError("second argument i.e. list2 should be a list") + list_return = uniquelist() + list_return.extend(list1) + list_return.extend(list2) + return list_return + def add(): + if list2==None: + raise TypeError("second argument i.e. list2 should be a list") + list_return=[] + list_return.append(list1) + list_return.append(list2) + return list_return + def difference(): + if list2==None: + raise TypeError("second argument i.e. list2 should be a list") + list_return=[] + list_intersection=intersection() + for temp1 in list1: + if temp1 not in list_intersection: + list_return.append(temp1) + return list_return + def make_it_variable_list(): # for each member (usually objects) in the list, it is replaced by one of its variables + if variable_name==None: + raise TypeError("variable_name should be a string") + if not list2==None: + raise TypeError("list2 should be None") + return_list=[getattr(temp,variable_name) for temp in list1] + + if operation==UNION: + return union() + elif operation==INTERSECTION: + return intersection() + elif operation==DIFFERENCE: + return difference() + elif operation==ADD: + return add() + elif operation==MAKE_IT_VARIABLE_LIST: + return make_it_variable_list() + else: + raise ValueError("Invalid operation name. Valid operations are UNION, INTERSECTION, DIFFERENCE.") +# end of operation_on_lists() +#Todo: see below +# 1. Allow rect-like and circle-like constructs wherever rect and circle are expected. +# 2. Do all sort of type-checking. +# Design tips I will use later +# IMP: always derive classes from object. Else, in python 2.x, they become old-style class which sucks. +# use tuples instead of lists wherver possible because they are usually faster to create +# learn about generators +# named tuples, arrays are better. use more of them. named tuples can be accessed. +# refactor code into proper modules as-well-as use better named functions and variables +# use enumerate() for getting the index and value of elements while looping through lists. This mistake done atleast 1 time. +# use xrange instead of range. It produces one at a time. range is replaced by xrange in python 3.x +# use reversed() for backward loops, sorted() for sorted order. +# instead of zip(), use izip(). +# use key instead of comparator +# use iter(iter_type,sentinel_value) instead of for loops +# partial() makes a function with more number of argument to less number of argument +# use for/else instead of exit based on flags +# look at dict.iteritems() and dict.setdefaults +# learn defaultdicts and collections module \ No newline at end of file diff --git a/pyFun/continuos_rotation_rect.py b/pyFun/continuos_rotation_rect.py new file mode 100644 index 0000000..e0dcc80 --- /dev/null +++ b/pyFun/continuos_rotation_rect.py @@ -0,0 +1,48 @@ +import pygame, sys +from pygame.locals import * +import base as fun +import time as t +from random import * +pygame.init() +surf= pygame.display.set_mode((600, 450)) +pygame.display.set_caption('Hello World!') +c1=t.clock() +c=[] +size=500 +r=[] +for count in range(size): + r.append(None) + r[count]=fun.tiltedRect((randint(0,600),randint(0,450)),(randint(0,600),randint(0,450)),randrange(0,360)) + r[count].rotate_step=random()-random() + r[count].rotate_time=randrange(500) + r[count].draw_pos=(randrange(600),randrange(450)) + +def calc_avg(): + sum=0 + for count in c: + sum+=count + avg=sum/len(c) + return avg + +for count in range(100): # main game loop + for event in pygame.event.get(): + if event.type == QUIT: + pygame.quit() + sys.exit() + surf.fill(pygame.Color("black")) + c2=t.clock() + c_diff=c2-c1 + c.append(c_diff) + print(c_diff) + c1=c2 + surf.lock() + for count in range(size): + r[count].rotate_time-=1 + if r[count].rotate_time<=0: + r[count].rotate_step=random()-random() + r[count].rotate_time=randrange(500) + r[count].rotate_ip(r[count].rotate_step) + r[count].draw(surf,r[count].draw_pos,centered=True) + surf.unlock() + pygame.display.flip() + diff --git a/pyFun/doing both obj.foo() and foo(obj).py b/pyFun/doing both obj.foo() and foo(obj).py new file mode 100644 index 0000000..3051e06 --- /dev/null +++ b/pyFun/doing both obj.foo() and foo(obj).py @@ -0,0 +1,6 @@ +def a(self): + print self + +class b(): + def a(self): + a(self) \ No newline at end of file diff --git a/pyFun/trial.py b/pyFun/trial.py new file mode 100644 index 0000000..553759a --- /dev/null +++ b/pyFun/trial.py @@ -0,0 +1,19 @@ +import wx +class MenuExample(wx.Frame): + def __init__(self, parent, id, title): + wx.Frame.__init__(self, parent, id, title, size=(250, 150)) + menubar = wx.MenuBar() + file = wx.Menu() + quit = wx.MenuItem(file, 1, 'Qu&it\tCtrl+q \tCtrl+t') + #quit.SetBitmap(wx.Bitmap('icons/exit.png')) + file.AppendItem(quit) + self.Bind(wx.EVT_MENU, self.OnQuit, id=1) + menubar.Append(file, '&File') + self.SetMenuBar(menubar) + self.Centre() + self.Show(True) + def OnQuit(self, event): + self.Close() +app = wx.App() +MenuExample(None, -1, '') +app.MainLoop() diff --git a/pyFun/uniquelist.py b/pyFun/uniquelist.py new file mode 100644 index 0000000..0561bab --- /dev/null +++ b/pyFun/uniquelist.py @@ -0,0 +1,20 @@ +class uniquelist(list): + ''' A list whose every value is unique. + uniquelist.append(val) or __setitem__(pos,val) i.e. uniquelist[pos]=val is ignored if val is already in uniquelist. + Returns True if the value is added, else returns False. ''' + def __setitem__(self,pos,val): + if val not in self: + super(uniquelist,self).__setitem__(pos,val) + return True + else: + return False + def append(self,val): + if val not in self: + super(uniquelist,self).append(val) + return True + else: + return False + def extend(self,iterable): + for temp in iterable: # todo: use yield so that it is not copied into memory + self.append(temp) + # Todo: Allow for type checking by allowing a type_of_members to be set \ No newline at end of file diff --git a/pyFun/useless_loc_count.py b/pyFun/useless_loc_count.py new file mode 100644 index 0000000..6993a88 --- /dev/null +++ b/pyFun/useless_loc_count.py @@ -0,0 +1,9 @@ +f=open(r"E:\Babu\pytry\pyFun\base.py") +count=0 +numb=[] +for index,line in enumerate(f): + if line.strip()=="" or line.strip().startswith("#") or line.strip().startswith("'''") or line.strip().startswith("@"): + numb.append(index+1) + count+=1; +print str(numb) +print "Total useless lines "+str(count) \ No newline at end of file diff --git a/pyganim.py b/pyganim.py new file mode 100644 index 0000000..80cb131 --- /dev/null +++ b/pyganim.py @@ -0,0 +1,846 @@ +# Pyganim (pyganim.py, ver 1) +# A sprite animation module for Pygame. +# +# By Al Sweigart al@inventwithpython.com +# http://inventwithpython.com/pyganim +# Released under a "Simplified BSD" license +# +# There's a tutorial (and sample code) on how to use this library at http://inventwithpython.com/pyganim +# NOTE: This module requires Pygame to be installed to use. Download it from http://pygame.org +# +# This should be compatible with both Python 2 and Python 3. Please email any +# bug reports to Al at al@inventwithpython.com +# + + +# TODO: Feature idea: if the same image file is specified, re-use the Surface object. (Make this optional though.) + +import pygame, time + +# setting up constants +PLAYING = 'playing' +PAUSED = 'paused' +STOPPED = 'stopped' + +# These values are used in the anchor() method. +NORTHWEST = 'northwest' +NORTH = 'north' +NORTHEAST = 'northeast' +WEST = 'west' +CENTER = 'center' +EAST = 'east' +SOUTHWEST = 'southwest' +SOUTH = 'south' +SOUTHEAST = 'southeast' + + +class PygAnimation(object): + def __init__(self, frames, loop=True): + # Constructor function for the animation object. Starts off in the STOPPED state. + # + # @param frames + # A list of tuples for each frame of animation, in one of the following format: + # (image_of_frame, duration_in_seconds) + # (filename_of_image, duration_in_seconds) + # Note that the images and duration cannot be changed. A new PygAnimation object + # will have to be created. + # @param loop Tells the animation object to keep playing in a loop. + + # _images stores the pygame.Surface objects of each frame + self._images = [] + # _durations stores the durations (in seconds) of each frame. + # e.g. [1, 1, 2.5] means the first and second frames last one second, + # and the third frame lasts for two and half seconds. + self._durations = [] + # _startTimes shows when each frame begins. len(self._startTimes) will + # always be one more than len(self._images), because the last number + # will be when the last frame ends, rather than when it starts. + # The values are in seconds. + # So self._startTimes[-1] tells you the length of the entire animation. + # e.g. if _durations is [1, 1, 2.5], then _startTimes will be [0, 1, 2, 4.5] + self._startTimes = None + + # if the sprites are transformed, the originals are kept in _images + # and the transformed sprites are kept in _transformedImages. + self._transformedImages = [] + + self._state = STOPPED # The state is always either PLAYING, PAUSED, or STOPPED + self._loop = loop # If True, the animation will keep looping. If False, the animation stops after playing once. + self._rate = 1.0 # 2.0 means play the animation twice as fast, 0.5 means twice as slow + self._visibility = True # If False, then nothing is drawn when the blit() methods are called + + self._playingStartTime = 0 # the time that the play() function was last called. + self._pausedStartTime = 0 # the time that the pause() function was last called. + + if frames != '_copy': # ('_copy' is passed for frames by the getCopies() method) + self.numFrames = len(frames) + assert self.numFrames > 0, 'Must contain at least one frame.' + for i in range(self.numFrames): + # load each frame of animation into _images + frame = frames[i] + assert type(frame) in (list, tuple) and len(frame) == 2, 'Frame %s has incorrect format.' % (i) + assert type(frame[0]) in (str, pygame.Surface), 'Frame %s image must be a string filename or a pygame.Surface' % (i) + assert frame[1] > 0, 'Frame %s duration must be greater than zero.' % (i) + if type(frame[0]) == str: + frame = (pygame.image.load(frame[0]), frame[1]) + self._images.append(frame[0]) + self._durations.append(frame[1]) + self._startTimes = self._getStartTimes() + + + def _getStartTimes(self): + # Internal method to get the start times based off of the _durations list. + # Don't call this method. + startTimes = [0] + for i in range(self.numFrames): + startTimes.append(startTimes[-1] + self._durations[i]) + return startTimes + + + def reverse(self): + # Reverses the order of the animations. + self.elapsed = self._startTimes[-1] - self.elapsed + self._images.reverse() + self._transformedImages.reverse() + self._durations.reverse() + + + def getCopy(self): + # Returns a copy of this PygAnimation object, but one that refers to the + # Surface objects of the original so it efficiently uses memory. + # + # NOTE: Messing around with the original Surface objects will affect all + # the copies. If you want to modify the Surface objects, then just make + # copies using constructor function instead. + return self.getCopies(1)[0] + + + def getCopies(self, numCopies=1): + # Returns a list of copies of this PygAnimation object, but one that refers to the + # Surface objects of the original so it efficiently uses memory. + # + # NOTE: Messing around with the original Surface objects will affect all + # the copies. If you want to modify the Surface objects, then just make + # copies using constructor function instead. + retval = [] + for i in range(numCopies): + newAnim = PygAnimation('_copy', loop=self.loop) + newAnim._images = self._images[:] + newAnim._transformedImages = self._transformedImages[:] + newAnim._durations = self._durations[:] + newAnim._startTimes = self._startTimes[:] + newAnim.numFrames = self.numFrames + retval.append(newAnim) + return retval + + + def blit(self, destSurface, dest): + # Draws the appropriate frame of the animation to the destination Surface + # at the specified position. + # + # NOTE: If the visibility attribute is False, then nothing will be drawn. + # + # @param destSurface + # The Surface object to draw the frame + # @param dest + # The position to draw the frame. This is passed to Pygame's Surface's + # blit() function, so it can be either a (top, left) tuple or a Rect + # object. + if self.isFinished(): + self.state = STOPPED + if not self.visibility or self.state == STOPPED: + return + frameNum = findStartTime(self._startTimes, self.elapsed) + destSurface.blit(self.getFrame(frameNum), dest) + + + def getFrame(self, frameNum): + # Returns the pygame.Surface object of the frameNum-th frame in this + # animation object. If there is a transformed version of the frame, + # it will return that one. + if self._transformedImages == []: + return self._images[frameNum] + else: + return self._transformedImages[frameNum] + + + def getCurrentFrame(self): + # Returns the pygame.Surface object of the frame that would be drawn + # if the blit() method were called right now. If there is a transformed + # version of the frame, it will return that one. + return self.getFrame(self.currentFrameNum) + + + def clearTransforms(self): + # Deletes all the transformed frames so that the animation object + # displays the original Surfaces/images as they were before + # transformation functions were called on them. + # + # This is handy to do for multiple transformation, where calling + # the rotation or scaling functions multiple times results in + # degraded/noisy images. + self._transformedImages = [] + + def makeTransformsPermanent(self): + self._images = [pygame.Surface(surfObj.get_size(), 0, surfObj) for surfObj in self._transformedImages] + for i in range(len(self._transformedImages)): + self._images[i].blit(self._transformedImages[i], (0,0)) + + def blitFrameNum(self, frameNum, destSurface, dest): + # Draws the specified frame of the animation object. This ignores the + # current playing state. + # + # NOTE: If the visibility attribute is False, then nothing will be drawn. + # + # @param frameNum + # The frame to draw (the first frame is 0, not 1) + # @param destSurface + # The Surface object to draw the frame + # @param dest + # The position to draw the frame. This is passed to Pygame's Surface's + # blit() function, so it can be either a (top, left) tuple or a Rect + # object. + if self.isFinished(): + self.state = STOPPED + if not self.visibility or self.state == STOPPED: + return + destSurface.blit(self.getFrame(frameNum), dest) + + + def blitFrameAtTime(self, elapsed, destSurface, dest): + # Draws the frame the is "elapsed" number of seconds into the animation, + # rather than the time the animation actually started playing. + # + # NOTE: If the visibility attribute is False, then nothing will be drawn. + # + # @param elapsed + # The amount of time into an animation to use when determining which + # frame to draw. blitFrameAtTime() uses this parameter rather than + # the actual time that the animation started playing. (In seconds) + # @param destSurface + # The Surface object to draw the frame + # @param dest + # The position to draw the frame. This is passed to Pygame's Surface's + # blit() function, so it can be either a (top, left) tuple or a Rect + # object. elapsed = int(elapsed * self.rate) + if self.isFinished(): + self.state = STOPPED + if not self.visibility or self.state == STOPPED: + return + frameNum = findStartTime(self._startTimes, elapsed) + destSurface.blit(self.getFrame(frameNum), dest) + + + def isFinished(self): + # Returns True if this animation doesn't loop and has finished playing + # all the frames it has. + return not self.loop and self.elapsed >= self._startTimes[-1] + + + def play(self, startTime=None): + # Start playing the animation. + + # play() is essentially a setter function for self._state + # NOTE: Don't adjust the self.state property, only self._state + + if startTime is None: + startTime = time.time() + + if self._state == PLAYING: + if self.isFinished(): + # if the animation doesn't loop and has already finished, then + # calling play() causes it to replay from the beginning. + self._playingStartTime = startTime + elif self._state == STOPPED: + # if animation was stopped, start playing from the beginning + self._playingStartTime = startTime + elif self._state == PAUSED: + # if animation was paused, start playing from where it was paused + self._playingStartTime = startTime - (self._pausedStartTime - self._playingStartTime) + self._state = PLAYING + + + def pause(self, startTime=None): + # Stop having the animation progress, and keep it at the current frame. + + # pause() is essentially a setter function for self._state + # NOTE: Don't adjust the self.state property, only self._state + + if startTime is None: + startTime = time.time() + + if self._state == PAUSED: + return # do nothing + elif self._state == PLAYING: + self._pausedStartTime = startTime + elif self._state == STOPPED: + rightNow = time.time() + self._playingStartTime = rightNow + self._pausedStartTime = rightNow + self._state = PAUSED + + + def stop(self): + # Reset the animation to the beginning frame, and do not continue playing + + # stop() is essentially a setter function for self._state + # NOTE: Don't adjust the self.state property, only self._state + if self._state == STOPPED: + return # do nothing + self._state = STOPPED + + + def togglePause(self): + # If paused, start playing. If playing, then pause. + + # togglePause() is essentially a setter function for self._state + # NOTE: Don't adjust the self.state property, only self._state + + if self._state == PLAYING: + if self.isFinished(): + # the one exception: if this animation doesn't loop and it + # has finished playing, then toggling the pause will cause + # the animation to replay from the beginning. + #self._playingStartTime = time.time() # effectively the same as calling play() + self.play() + else: + self.pause() + elif self._state in (PAUSED, STOPPED): + self.play() + + + def areFramesSameSize(self): + # Returns True if all the Surface objects in this animation object + # have the same width and height. Otherwise, returns False + width, height = self.getFrame(0).get_size() + for i in range(len(self._images)): + if self.getFrame(i).get_size() != (width, height): + return False + return True + + + def getMaxSize(self): + # Goes through all the Surface objects in this animation object + # and returns the max width and max height that it finds. (These + # widths and heights may be on different Surface objects.) + frameWidths = [] + frameHeights = [] + for i in range(len(self._images)): + frameWidth, frameHeight = self._images[i].get_size() + frameWidths.append(frameWidth) + frameHeights.append(frameHeight) + maxWidth = max(frameWidths) + maxHeight = max(frameHeights) + + return (maxWidth, maxHeight) + + + def getRect(self): + # Returns a pygame.Rect object for this animation object. + # The top and left will be set to 0, 0, and the width and height + # will be set to what is returned by getMaxSize(). + maxWidth, maxHeight = self.getMaxSize() + return pygame.Rect(0, 0, maxWidth, maxHeight) + + + def anchor(self, anchorPoint=NORTHWEST): + # If the Surface objects are of different sizes, align them all to a + # specific "anchor point" (one of the NORTH, SOUTH, SOUTHEAST, etc. constants) + # + # By default, they are all anchored to the NORTHWEST corner. + if self.areFramesSameSize(): + return # nothing needs to be anchored + # This check also prevents additional calls to anchor() from doing + # anything, since anchor() sets all the image to the same size. + # The lesson is, you can only effectively call anchor() once. + + self.clearTransforms() # clears transforms since this method anchors the original images. + + maxWidth, maxHeight = self.getMaxSize() + halfMaxWidth = int(maxWidth / 2) + halfMaxHeight = int(maxHeight / 2) + + for i in range(len(self._images)): + # go through and copy all frames to a max-sized Surface object + # NOTE: This makes changes to the original images in self._images, not the transformed images in self._transformedImages + newSurf = pygame.Surface((maxWidth, maxHeight)) # TODO: this is probably going to have errors since I'm using the default depth. + + # set the expanded areas to be transparent + newSurf = newSurf.convert_alpha() + newSurf.fill((0,0,0,0)) + + frameWidth, frameHeight = self._images[i].get_size() + halfFrameWidth = int(frameWidth / 2) + halfFrameHeight = int(frameHeight / 2) + + # position the Surface objects to the specified anchor point + if anchorPoint == NORTHWEST: + newSurf.blit(self._images[i], (0, 0)) + elif anchorPoint == NORTH: + newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, 0)) + elif anchorPoint == NORTHEAST: + newSurf.blit(self._images[i], (maxWidth - frameWidth, 0)) + elif anchorPoint == WEST: + newSurf.blit(self._images[i], (0, halfMaxHeight - halfFrameHeight)) + elif anchorPoint == CENTER: + newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, halfMaxHeight - halfFrameHeight)) + elif anchorPoint == EAST: + newSurf.blit(self._images[i], (maxWidth - frameWidth, halfMaxHeight - halfFrameHeight)) + elif anchorPoint == SOUTHWEST: + newSurf.blit(self._images[i], (0, maxHeight - frameHeight)) + elif anchorPoint == SOUTH: + newSurf.blit(self._images[i], (halfMaxWidth - halfFrameWidth, maxHeight - frameHeight)) + elif anchorPoint == SOUTHEAST: + newSurf.blit(self._images[i], (maxWidth - frameWidth, maxHeight - frameHeight)) + self._images[i] = newSurf + + + def nextFrame(self, jump=1): + # Set the elapsed time to the beginning of the next frame. + # You can jump ahead by multiple frames by specifying a different + # argument for jump. + # Negative values have the same effect as calling prevFrame() + self.currentFrameNum += int(jump) + + + def prevFrame(self, jump=1): + # Set the elapsed time to the beginning of the previous frame. + # You can jump ahead by multiple frames by specifying a different + # argument for jump. + # Negative values have the same effect as calling nextFrame() + self.currentFrameNum -= int(jump) + + + def rewind(self, seconds=None): + # Set the elapsed time back relative to the current elapsed time. + if seconds is None: + self.elapsed = 0.0 + else: + self.elapsed -= seconds + + + def fastForward(self, seconds=None): + # Set the elapsed time forward relative to the current elapsed time. + if seconds is None: + self.elapsed = self._startTimes[-1] - 0.00002 # done to compensate for rounding errors + else: + self.elapsed += seconds + + def _makeTransformedSurfacesIfNeeded(self): + # Internal-method. Creates the Surface objects for the _transformedImages list. + # Don't call this method. + if self._transformedImages == []: + self._transformedImages = [surf.copy() for surf in self._images] + + + # Transformation methods. + # (These are analogous to the pygame.transform.* functions, except they + # are applied to all frames of the animation object. + def flip(self, xbool, ybool): + # Flips the image horizontally, vertically, or both. + # See http://pygame.org/docs/ref/transform.html#pygame.transform.flip + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.flip(self.getFrame(i), xbool, ybool) + + + def scale(self, width_height): + # NOTE: Does not support the DestSurface parameter + # Increases or decreases the size of the images. + # See http://pygame.org/docs/ref/transform.html#pygame.transform.scale + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.scale(self.getFrame(i), width_height) + + + def rotate(self, angle): + # Rotates the image. + # See http://pygame.org/docs/ref/transform.html#pygame.transform.rotate + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.rotate(self.getFrame(i), angle) + + + def rotozoom(self, angle, scale): + # Rotates and scales the image simultaneously. + # See http://pygame.org/docs/ref/transform.html#pygame.transform.rotozoom + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.rotozoom(self.getFrame(i), angle, scale) + + + def scale2x(self): + # NOTE: Does not support the DestSurface parameter + # Double the size of the image using an efficient algorithm. + # See http://pygame.org/docs/ref/transform.html#pygame.transform.scale2x + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.scale2x(self.getFrame(i)) + + + def smoothscale(self, width_height): + # NOTE: Does not support the DestSurface parameter + # Scales the image smoothly. (Computationally more expensive and + # slower but produces a better scaled image.) + # See http://pygame.org/docs/ref/transform.html#pygame.transform.smoothscale + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + self._transformedImages[i] = pygame.transform.smoothscale(self.getFrame(i), width_height) + + + + # pygame.Surface method wrappers + # These wrappers call their analogous pygame.Surface methods on all Surface objects in this animation. + # They are here for the convenience of the module user. These calls will apply to the transform images, + # and can have their effects undone by called clearTransforms() + # + # It is not advisable to call these methods on the individual Surface objects in self._images. + def _surfaceMethodWrapper(self, wrappedMethodName, *args, **kwargs): + self._makeTransformedSurfacesIfNeeded() + for i in range(len(self._images)): + methodToCall = getattr(self._transformedImages[i], wrappedMethodName) + methodToCall(*args, **kwargs) + + # There's probably a more terse way to generate the following methods, + # but I don't want to make the code even more unreadable. + def convert(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.convert + self._surfaceMethodWrapper('convert', *args, **kwargs) + + + def convert_alpha(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.convert_alpha + self._surfaceMethodWrapper('convert_alpha', *args, **kwargs) + + + def set_alpha(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.set_alpha + self._surfaceMethodWrapper('set_alpha', *args, **kwargs) + + + def scroll(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.scroll + self._surfaceMethodWrapper('scroll', *args, **kwargs) + + + def set_clip(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.set_clip + self._surfaceMethodWrapper('set_clip', *args, **kwargs) + + + def set_colorkey(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.set_colorkey + self._surfaceMethodWrapper('set_colorkey', *args, **kwargs) + + + def lock(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.unlock + self._surfaceMethodWrapper('lock', *args, **kwargs) + + + def unlock(self, *args, **kwargs): + # See http://pygame.org/docs/ref/surface.html#Surface.lock + self._surfaceMethodWrapper('unlock', *args, **kwargs) + + + + # Getter and setter methods for properties + def _propGetRate(self): + return self._rate + + def _propSetRate(self, rate): + rate = float(rate) + if rate < 0: + raise ValueError('rate must be greater than 0.') + self._rate = rate + + rate = property(_propGetRate, _propSetRate) + + + def _propGetLoop(self): + return self._loop + + def _propSetLoop(self, loop): + if self.state == PLAYING and self._loop and not loop: + # if we are turning off looping while the animation is playing, + # we need to modify the _playingStartTime so that the rest of + # the animation will play, and then stop. (Otherwise, the + # animation will immediately stop playing if it has already looped.) + self._playingStartTime = time.time() - self.elapsed + self._loop = bool(loop) + + loop = property(_propGetLoop, _propSetLoop) + + + def _propGetState(self): + if self.isFinished(): + self._state = STOPPED # if finished playing, then set state to STOPPED. + + return self._state + + def _propSetState(self, state): + if state not in (PLAYING, PAUSED, STOPPED): + raise ValueError('state must be one of pyganim.PLAYING, pyganim.PAUSED, or pyganim.STOPPED') + if state == PLAYING: + self.play() + elif state == PAUSED: + self.pause() + elif state == STOPPED: + self.stop() + + state = property(_propGetState, _propSetState) + + + def _propGetVisibility(self): + return self._visibility + + def _propSetVisibility(self, visibility): + self._visibility = bool(visibility) + + visibility = property(_propGetVisibility, _propSetVisibility) + + + def _propSetElapsed(self, elapsed): + # NOTE: Do to floating point rounding errors, this doesn't work precisely. + elapsed += 0.00001 # done to compensate for rounding errors + # TODO - I really need to find a better way to handle the floating point thing. + + # Set the elapsed time to a specific value. + if self._loop: + elapsed = elapsed % self._startTimes[-1] + else: + elapsed = getInBetweenValue(0, elapsed, self._startTimes[-1]) + + rightNow = time.time() + self._playingStartTime = rightNow - (elapsed * self.rate) + + if self.state in (PAUSED, STOPPED): + self.state = PAUSED # if stopped, then set to paused + self._pausedStartTime = rightNow + + + def _propGetElapsed(self): + # NOTE: Do to floating point rounding errors, this doesn't work precisely. + + # To prevent infinite recursion, don't use the self.state property, + # just read/set self._state directly because the state getter calls + # this method. + + # Find out how long ago the play()/pause() functions were called. + if self._state == STOPPED: + # if stopped, then just return 0 + return 0 + + if self._state == PLAYING: + # if playing, then draw the current frame (based on when the animation + # started playing). If not looping and the animation has gone through + # all the frames already, then draw the last frame. + elapsed = (time.time() - self._playingStartTime) * self.rate + elif self._state == PAUSED: + # if paused, then draw the frame that was playing at the time the + # PygAnimation object was paused + elapsed = (self._pausedStartTime - self._playingStartTime) * self.rate + if self._loop: + elapsed = elapsed % self._startTimes[-1] + else: + elapsed = getInBetweenValue(0, elapsed, self._startTimes[-1]) + elapsed += 0.00001 # done to compensate for rounding errors + return elapsed + + elapsed = property(_propGetElapsed, _propSetElapsed) + + + def _propGetCurrentFrameNum(self): + # Return the frame number of the frame that will be currently + # displayed if the animation object were drawn right now. + return findStartTime(self._startTimes, self.elapsed) + + + def _propSetCurrentFrameNum(self, frameNum): + # Change the elapsed time to the beginning of a specific frame. + if self.loop: + frameNum = frameNum % len(self._images) + else: + frameNum = getInBetweenValue(0, frameNum, len(self._images)-1) + self.elapsed = self._startTimes[frameNum] + + currentFrameNum = property(_propGetCurrentFrameNum, _propSetCurrentFrameNum) + + + +class PygConductor(object): + def __init__(self, *animations): + assert len(animations) > 0, 'at least one PygAnimation object is required' + + self._animations = [] + self.add(*animations) + + + def add(self, *animations): + if type(animations[0]) == dict: + for k in animations[0].keys(): + self._animations.append(animations[0][k]) + elif type(animations[0]) in (tuple, list): + for i in range(len(animations[0])): + self._animations.append(animations[0][i]) + else: + for i in range(len(animations)): + self._animations.append(animations[i]) + + def _propGetAnimations(self): + return self._animations + + def _propSetAnimations(self, val): + self._animations = val + + animations = property(_propGetAnimations, _propSetAnimations) + + def play(self, startTime=None): + if startTime is None: + startTime = time.time() + + for animObj in self._animations: + animObj.play(startTime) + + def pause(self, startTime=None): + if startTime is None: + startTime = time.time() + + for animObj in self._animations: + animObj.pause(startTime) + + def stop(self): + for animObj in self._animations: + animObj.stop() + + def reverse(self): + for animObj in self._animations: + animObj.reverse() + + def clearTransforms(self): + for animObj in self._animations: + animObj.clearTransforms() + + def makeTransformsPermanent(self): + for animObj in self._animations: + animObj.makeTransformsPermanent() + + def togglePause(self): + for animObj in self._animations: + animObj.togglePause() + + def nextFrame(self, jump=1): + for animObj in self._animations: + animObj.nextFrame(jump) + + def prevFrame(self, jump=1): + for animObj in self._animations: + animObj.prevFrame(jump) + + def rewind(self, seconds=None): + for animObj in self._animations: + animObj.rewind(seconds) + + def fastForward(self, seconds=None): + for animObj in self._animations: + animObj.fastForward(seconds) + + def flip(self, xbool, ybool): + for animObj in self._animations: + animObj.flip(xbool, ybool) + + def scale(self, width_height): + for animObj in self._animations: + animObj.scale(width_height) + + def rotate(self, angle): + for animObj in self._animations: + animObj.rotate(angle) + + def rotozoom(self, angle, scale): + for animObj in self._animations: + animObj.rotozoom(angle, scale) + + def scale2x(self): + for animObj in self._animations: + animObj.scale2x() + + def smoothscale(self, width_height): + for animObj in self._animations: + animObj.smoothscale(width_height) + + def convert(self): + for animObj in self._animations: + animObj.convert() + + def convert_alpha(self): + for animObj in self._animations: + animObj.convert_alpha() + + def set_alpha(self, *args, **kwargs): + for animObj in self._animations: + animObj.set_alpha(*args, **kwargs) + + def scroll(self, dx=0, dy=0): + for animObj in self._animations: + animObj.scroll(dx, dy) + + def set_clip(self, *args, **kwargs): + for animObj in self._animations: + animObj.set_clip(*args, **kwargs) + + def set_colorkey(self, *args, **kwargs): + for animObj in self._animations: + animObj.set_colorkey(*args, **kwargs) + + def lock(self): + for animObj in self._animations: + animObj.lock() + + def unlock(self): + for animObj in self._animations: + animObj.unlock() + + +def getInBetweenValue(lowerBound, value, upperBound): + # Returns the value within the bounds of the lower and upper bound parameters. + # If value is less than lowerBound, then return lowerBound. + # If value is greater than upperBound, then return upperBound. + # Otherwise, just return value as it is. + if value < lowerBound: + return lowerBound + elif value > upperBound: + return upperBound + return value + + +def findStartTime(startTimes, target): + # With startTimes as a list of sequential numbers and target as a number, + # returns the index of the number in startTimes that preceeds target. + # + # For example, if startTimes was [0, 2, 4.5, 7.3, 10] and target was 6, + # then findStartTime() would return 2. If target was 12, returns 4. + assert startTimes[0] == 0 + lb = 0 # "lb" is lower bound + ub = len(startTimes) - 1 # "ub" is upper bound + + # handle special cases: + if len(startTimes) == 0: + return 0 + if target >= startTimes[-1]: + return ub - 1 + + # perform binary search: + while True: + i = int((ub - lb) / 2) + lb + + if startTimes[i] == target or (startTimes[i] < target and startTimes[i+1] > target): + if i == len(startTimes): + return i - 1 + else: + return i + + if startTimes[i] < target: + lb = i + elif startTimes[i] > target: + ub = i diff --git a/rec.py b/rec.py new file mode 100644 index 0000000..148c4af --- /dev/null +++ b/rec.py @@ -0,0 +1,60 @@ +from SimpleCV import * +import time + +# This file shows you how to train Fisher Face Recognition +# Enter the names of the faces and the output file. +cam = Camera(0) # camera +names = ['Alice','Bob'] # names of people to recognize +outfile = "test.csv" #output file +waitTime = 10 # how long to wait between each training session + +def getFaceSet(cam,myStr=""): + # Grab a series of faces and return them. + # quit when we press escape. + iset = ImageSet() + count = 0 + disp = Display((640,480)) + while disp.isNotDone(): + img = cam.getImage() + fs = img.findHaarFeatures('face') + if( fs is not None ): + fs = fs.sortArea() + face = fs[-1].crop().resize(100,100) + fs[-1].draw() + iset.append(face) + count = count + 1 + img.drawText(myStr,20,20,color=Color.RED,fontsize=32) + img.save(disp) + disp.quit() + return iset + +# First make sure our camera is all set up. +#getFaceSet(cam,"Get Camera Ready! - ESC to Exit") +#time.sleep(5) +labels = [] +imgs = [] +# for each person grab a training set of images +# and generate a list of labels. +for name in names: + myStr = "Training for : " + name + iset = getFaceSet(cam,myStr) + imgs += iset + labels += [name for i in range(0,len(iset))] + time.sleep(waitTime) + +# Create, train, and save the recognizer. +f = FaceRecognizer() +print f.train(imgs, labels) +f.save(outfile) +# Now show us the results +disp = Display((640,480)) +while disp.isNotDone(): + img = cam.getImage() + fs = img.findHaarFeatures('face') + if( fs is not None ): + fs = fs.sortArea() + face = fs[-1].crop().resize(100,100) + fs[-1].draw() + name, confidence = f.predict(face) + img.drawText(name,30,30,fontsize=64) + img.save(disp) \ No newline at end of file diff --git a/result.jpg b/result.jpg new file mode 100644 index 0000000..06872fd Binary files /dev/null and b/result.jpg differ diff --git a/result.png b/result.png new file mode 100644 index 0000000..d2d62bc Binary files /dev/null and b/result.png differ diff --git a/right_left_gesture.py b/right_left_gesture.py new file mode 100644 index 0000000..120facc --- /dev/null +++ b/right_left_gesture.py @@ -0,0 +1,76 @@ +import SimpleCV as s +import time +import simulate_keypress as press +c=s.JpegStreamCamera(r"192.168.173.147:8080/videofeed") +#c=s.Camera() +c1=time.clock() +gesture_time=60 +detection_sleep=False +blobs=[None]*gesture_time +#d=s.Display() +i1=c.getImage() +img_width_ori=i1.width +img_height=i1.height +i1=i1.crop(0,0,img_width_ori,img_height/2).flipHorizontal() +img_width=img_width_ori +count=0 +while True: + i2=c.getImage().crop(0,0,img_width_ori,img_height/2).flipHorizontal() + i3=(i2-i1)+(i1-i2) + i1=i2 + i3=i3.stretch(10,255).erode(2).dilate(2) + f=i3.findBlobs(minsize=100) + blobs[count]=f + min_x_list=[] + #min_y_list=[] + max_x_list=[] + #max_y_list=[] + blobs_empty=True + count_blobs=0 + for blobs_temp in blobs: + count_blobs+=1 + if blobs_temp: + min_x_list.append([min(temp[0] for temp in blobs_temp.topLeftCorners()),count_blobs]) + #min_y_list.append([min(temp[1] for temp in blobs_temp.topLeftCorners()),count_blobs]) + max_x_list.append([max(temp[0] for temp in blobs_temp.bottomRightCorners()),count_blobs]) + #max_y_list.append([min(temp[1] for temp in blobs_temp.bottomRightCorners()),count_blobs]) + blobs_empty=False + if not blobs_empty: + min_x=min([temp[0] for temp in min_x_list]) + left_step=min_x_list[[temp[0] for temp in min_x_list].index(min_x)][1] + #min_y=min([temp[0] for temp in min_y_list]) + max_x=max([temp[0] for temp in max_x_list]) + right_step=max_x_list[[temp[0] for temp in max_x_list].index(max_x)][1] + #max_y=max([temp[0] for temp in max_y_list]) + detection_width=abs(max_x-min_x) + if not detection_sleep and detection_width> img_width*0.75: + print("Detected") + print(right_step,left_step) + if right_step>left_step: + print("Left to right") + press.press_up() + else: + print("Right to left") + press.press_down() + print(c1) + detection_sleep=gesture_time + else: + pass + #print("Not detected") + else: + min_x=None + min_y=None + max_x=None + max_y=None + + if detection_sleep: + detection_sleep-=1 + if f: + f.draw(width=2) + #i3.show() + c2=time.clock() + #print(1/(c1-c2)) + c1=c2 + count+=1 + count=count%gesture_time +## i2.findSkintoneBlobs().show() \ No newline at end of file diff --git a/robo1.js.css b/robo1.js.css new file mode 100644 index 0000000..3a20572 --- /dev/null +++ b/robo1.js.css @@ -0,0 +1,50 @@ +/* add your css style rules here */ + + +a { + color: inherit; + text-decoration: none; +} +h2 { + text-align: center; +} +img{ + display: block; + margin-left: auto; + margin-right: auto +} +img.side { + display: inline; +} +body { + background-image: -webkit-linear-gradient(top left, silver, white); + background-image: -moz-linear-gradient(top left, silver, white); + background-image: -ms-linear-gradient(top left, silver, white); + background-image: -o-linear-gradient(top left, silver, white); + background-image: linear-gradient(top left, silver, white); +} + +.step { + width: 900px; + height: 700px; + padding: 40px 60px; + + font-size: 34px; + text-align: left; + + opacity: 0.1; +} + +.step.active { + opacity: 1; +} + +.slide { + background: white; +} + +code { + background-color: yellow; + font-size: 14px; +} + diff --git a/robo1.js.html b/robo1.js.html new file mode 100644 index 0000000..41cfce2 --- /dev/null +++ b/robo1.js.html @@ -0,0 +1,350 @@ + + + + + + + Intro to Autonomous Robotics | by Robodarshan :) + + + + + + + + + + + + +
+ + + +
+ + + + +

Introduction to Robotics

+ +

+ +

+ + +
+ +
+ + +

WELCOME EVERYBODY

+ +

+ +

// To be replaced by live face detected image

+ + +
+ +
+ + +

What is “Robot” ?

+ +

+ + +
+ +
+ + +

Let’s Google it

+ +

+ + +
+ +
+ + +

admin : OK Bot, show us what can you do …

+ +

bot : I can …

+ +
    +
  • Learn Skills ranging from electronics, mechanics, controls, programming, etc …
  • +
  • Work in Industry assembly lines, like a robotic arm used for car-painting, parts assembling, etc…
    +// img
  • +
  • Function as a mobile robot such as terrestial, aerial, aquatic or hybrid vehicle be it manually controlled or autonomous.
  • +
  • Work in swarms to co-ordinate a task
    +// img
  • +
+ + +
+ +
+ + +

So, what will you learn today ?

+ +

How about some robotics ?
+Well, we guess you already knew that :)

+ +
    +
  • +

    First we’ll talk about Manual Robotics, the ones controlled by human (yup, that’s you)

    +
  • +
  • +

    Then, we’ll move on to autonomous bots, the ones which can perform simple tasks on their own. ( Remember Wall-E ? )

    +
  • +
  • +

    If time permits, we’ll talk about robots with “eyes” (err.. cameras).

    +
  • +
+ + +
+ +
+ + +

Mechanical Constructionl

+ +
    +
  • Chassis, i.e. the basic body structure (generally rectangular) +
      +
    • +

      Preferred Material : Flex Board (25 cm x 25 cm) +

      +
    • +
    • +

      Others : Motor Clamps
      +

      +
    • +
    +
  • +
+ + +
+ +
+ + +

Wheels

+ +
    +
  • +

    Normal Wheels , the ones you see in cars … toy cars.
    + +

    +
  • +
  • +

    Castor Wheels , a non-drivable wheel that is mounted at the bottom of a vehicle (or robot, in our case), that can move in any direction. You can find them under the ( legs of ) movable tables.
    + +

    +
  • +
+ + +
+ +
+ + +

DC Motors

+ +
    +
  • Runs on DC input.
  • +
  • Types +
      +
    • Geared Motor :
      +
        +
      • Pros: +
          +
        1. Used for bringing about a change in speed, by the use of gears.
        2. +
        3. Also used to change axis and direction of motion
        4. +
        +
      • +
      • Cons: +
          +
        1. No feedback mechanism.
        2. +
        +
      • +
      +
    • +
    + +

    // insert img

    +
  • +
+ + +
+ +
+ + +

DC Motors (contd.)

+ +
    +
  • Types (contd.) +
      +
    • Servo Motors +
        +
      • Pros: +
          +
        • Used for high torque operations
        • +
        +
      • +
      • Cons: +
          +
        • Costly
        • +
        +
      • +
      +
    • +
    +
  • +
+ + +
+ +
+ + +

Motion Direction Control

+ +
    +
  • H-Bridge Circuit +
      +
    • Simple electrical circuit using which you can change the polarity at the load.
      + // insert img
    • +
    +
  • +
  • Example: +
      +
    • DPDT Switch:
      + Switching device that uses H-Bridge principle to change the polarity of load and hence the motion of the motor whenever needed.
      + // insert img
    • +
    +
  • +
+ + +
+ +
+ + +

Drives

+ +
    +
  • Types of drive we’ll be using: +
      +
    • 2 wheel drive, 2 gearbox with castor wheel
    • +
    • 4 wheel drive, 4 gearbox
    • +
    +
  • +
  • Others +
      +
    • N Wheel Drive
    • +
    • Tank Wheel Drive
    • +
    +
  • +
+ + +
+ +
+ + +

2 wheel drive with castor wheel

+ +

It has

+ +
    +
  • 2 active wheels with gearboxes
  • +
  • 1 castor wheel for balance and free movement
    +// make img
  • +
+ + +
+ +
+ + +

4 wheel drive with 4 gearboxes

+ +

It has 4 wheels connected with 4 gearboxes for fast and agile movement

+ +

//img

+ + +
+ +
+ + +

Locomotion using Differential Drive system

+ +

bot: I wanna move…
+admin: How?
+bot: Well now that you have asked so nicely…

+ +
    +
  • Differential Drive is one way to accomplish this
    +//img
  • +
  • The simplest motions (shown above) occur when all of the wheels are moving
  • +
  • Different motions are also possible if we keep one/many wheels static
  • +
+ + +
+ +
+ + +

SHOW TIME

+ +

We’re pretty sure that you are bored to hell.
+So, here’s a little treat for you.

+ +

Sit back and enjoy :D

+ + +
+ +
+ + +

Question time

+ +

Now, Throw something at us

+ +

Just dont throw an error :P

+ + + +
+ + +
+ + + + + + \ No newline at end of file diff --git a/robocon/all_wheels.jpg b/robocon/all_wheels.jpg new file mode 100644 index 0000000..5a6a930 Binary files /dev/null and b/robocon/all_wheels.jpg differ diff --git a/robocon/apple-touch-icon.png b/robocon/apple-touch-icon.png new file mode 100644 index 0000000..f610016 Binary files /dev/null and b/robocon/apple-touch-icon.png differ diff --git a/robocon/attn.png b/robocon/attn.png new file mode 100644 index 0000000..af60923 Binary files /dev/null and b/robocon/attn.png differ diff --git a/robocon/board.jpg b/robocon/board.jpg new file mode 100644 index 0000000..ed6c706 Binary files /dev/null and b/robocon/board.jpg differ diff --git a/robocon/cas1.jpg b/robocon/cas1.jpg new file mode 100644 index 0000000..a281844 Binary files /dev/null and b/robocon/cas1.jpg differ diff --git a/robocon/cas2.jpg b/robocon/cas2.jpg new file mode 100644 index 0000000..566787c Binary files /dev/null and b/robocon/cas2.jpg differ diff --git a/robocon/clamps.jpg b/robocon/clamps.jpg new file mode 100644 index 0000000..7641c9e Binary files /dev/null and b/robocon/clamps.jpg differ diff --git a/robocon/con_zone.gif b/robocon/con_zone.gif new file mode 100644 index 0000000..06979e0 Binary files /dev/null and b/robocon/con_zone.gif differ diff --git a/robocon/dpdt1.jpg b/robocon/dpdt1.jpg new file mode 100644 index 0000000..72280dc Binary files /dev/null and b/robocon/dpdt1.jpg differ diff --git a/robocon/dpdt2.gif b/robocon/dpdt2.gif new file mode 100644 index 0000000..c108da4 Binary files /dev/null and b/robocon/dpdt2.gif differ diff --git a/robocon/dr1.jpg b/robocon/dr1.jpg new file mode 100644 index 0000000..96c44b6 Binary files /dev/null and b/robocon/dr1.jpg differ diff --git a/robocon/dr2.jpg b/robocon/dr2.jpg new file mode 100644 index 0000000..eae19d0 Binary files /dev/null and b/robocon/dr2.jpg differ diff --git a/robocon/drive.jpg b/robocon/drive.jpg new file mode 100644 index 0000000..6e4f853 Binary files /dev/null and b/robocon/drive.jpg differ diff --git a/robocon/face_detect.jpg b/robocon/face_detect.jpg new file mode 100644 index 0000000..893ebea Binary files /dev/null and b/robocon/face_detect.jpg differ diff --git a/robocon/h-br.gif b/robocon/h-br.gif new file mode 100644 index 0000000..34c8392 Binary files /dev/null and b/robocon/h-br.gif differ diff --git a/robocon/industry.jpg b/robocon/industry.jpg new file mode 100644 index 0000000..6a0db51 Binary files /dev/null and b/robocon/industry.jpg differ diff --git a/robocon/intro_to_robotics.jpg b/robocon/intro_to_robotics.jpg new file mode 100644 index 0000000..4bcc174 Binary files /dev/null and b/robocon/intro_to_robotics.jpg differ diff --git a/robocon/js/impress.js b/robocon/js/impress.js new file mode 100644 index 0000000..d57bc51 --- /dev/null +++ b/robocon/js/impress.js @@ -0,0 +1,800 @@ +/** + * impress.js + * + * impress.js is a presentation tool based on the power of CSS3 transforms and transitions + * in modern browsers and inspired by the idea behind prezi.com. + * + * + * Copyright 2011-2012 Bartek Szopka (@bartaz) + * + * Released under the MIT and GPL Licenses. + * + * ------------------------------------------------ + * author: Bartek Szopka + * version: 0.5.3 + * url: http://bartaz.github.com/impress.js/ + * source: http://github.com/bartaz/impress.js/ + */ + +/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, latedef:true, newcap:true, + noarg:true, noempty:true, undef:true, strict:true, browser:true */ + +// You are one of those who like to know how thing work inside? +// Let me show you the cogs that make impress.js run... +(function ( document, window ) { + 'use strict'; + + // HELPER FUNCTIONS + + // `pfx` is a function that takes a standard CSS property name as a parameter + // and returns it's prefixed version valid for current browser it runs in. + // The code is heavily inspired by Modernizr http://www.modernizr.com/ + var pfx = (function () { + + var style = document.createElement('dummy').style, + prefixes = 'Webkit Moz O ms Khtml'.split(' '), + memory = {}; + + return function ( prop ) { + if ( typeof memory[ prop ] === "undefined" ) { + + var ucProp = prop.charAt(0).toUpperCase() + prop.substr(1), + props = (prop + ' ' + prefixes.join(ucProp + ' ') + ucProp).split(' '); + + memory[ prop ] = null; + for ( var i in props ) { + if ( style[ props[i] ] !== undefined ) { + memory[ prop ] = props[i]; + break; + } + } + + } + + return memory[ prop ]; + }; + + })(); + + // `arraify` takes an array-like object and turns it into real Array + // to make all the Array.prototype goodness available. + var arrayify = function ( a ) { + return [].slice.call( a ); + }; + + // `css` function applies the styles given in `props` object to the element + // given as `el`. It runs all property names through `pfx` function to make + // sure proper prefixed version of the property is used. + var css = function ( el, props ) { + var key, pkey; + for ( key in props ) { + if ( props.hasOwnProperty(key) ) { + pkey = pfx(key); + if ( pkey !== null ) { + el.style[pkey] = props[key]; + } + } + } + return el; + }; + + // `toNumber` takes a value given as `numeric` parameter and tries to turn + // it into a number. If it is not possible it returns 0 (or other value + // given as `fallback`). + var toNumber = function (numeric, fallback) { + return isNaN(numeric) ? (fallback || 0) : Number(numeric); + }; + + // `byId` returns element with given `id` - you probably have guessed that ;) + var byId = function ( id ) { + return document.getElementById(id); + }; + + // `$` returns first element for given CSS `selector` in the `context` of + // the given element or whole document. + var $ = function ( selector, context ) { + context = context || document; + return context.querySelector(selector); + }; + + // `$$` return an array of elements for given CSS `selector` in the `context` of + // the given element or whole document. + var $$ = function ( selector, context ) { + context = context || document; + return arrayify( context.querySelectorAll(selector) ); + }; + + // `triggerEvent` builds a custom DOM event with given `eventName` and `detail` data + // and triggers it on element given as `el`. + var triggerEvent = function (el, eventName, detail) { + var event = document.createEvent("CustomEvent"); + event.initCustomEvent(eventName, true, true, detail); + el.dispatchEvent(event); + }; + + // `translate` builds a translate transform string for given data. + var translate = function ( t ) { + return " translate3d(" + t.x + "px," + t.y + "px," + t.z + "px) "; + }; + + // `rotate` builds a rotate transform string for given data. + // By default the rotations are in X Y Z order that can be reverted by passing `true` + // as second parameter. + var rotate = function ( r, revert ) { + var rX = " rotateX(" + r.x + "deg) ", + rY = " rotateY(" + r.y + "deg) ", + rZ = " rotateZ(" + r.z + "deg) "; + + return revert ? rZ+rY+rX : rX+rY+rZ; + }; + + // `scale` builds a scale transform string for given data. + var scale = function ( s ) { + return " scale(" + s + ") "; + }; + + // `perspective` builds a perspective transform string for given data. + var perspective = function ( p ) { + return " perspective(" + p + "px) "; + }; + + // `getElementFromHash` returns an element located by id from hash part of + // window location. + var getElementFromHash = function () { + // get id from url # by removing `#` or `#/` from the beginning, + // so both "fallback" `#slide-id` and "enhanced" `#/slide-id` will work + return byId( window.location.hash.replace(/^#\/?/,"") ); + }; + + // `computeWindowScale` counts the scale factor between window size and size + // defined for the presentation in the config. + var computeWindowScale = function ( config ) { + var hScale = window.innerHeight / config.height, + wScale = window.innerWidth / config.width, + scale = hScale > wScale ? wScale : hScale; + + if (config.maxScale && scale > config.maxScale) { + scale = config.maxScale; + } + + if (config.minScale && scale < config.minScale) { + scale = config.minScale; + } + + return scale; + }; + + // CHECK SUPPORT + var body = document.body; + + var ua = navigator.userAgent.toLowerCase(); + var impressSupported = + // browser should support CSS 3D transtorms + ( pfx("perspective") !== null ) && + + // and `classList` and `dataset` APIs + ( body.classList ) && + ( body.dataset ) && + + // but some mobile devices need to be blacklisted, + // because their CSS 3D support or hardware is not + // good enough to run impress.js properly, sorry... + ( ua.search(/(iphone)|(ipod)|(android)/) === -1 ); + + if (!impressSupported) { + // we can't be sure that `classList` is supported + body.className += " impress-not-supported "; + } else { + body.classList.remove("impress-not-supported"); + body.classList.add("impress-supported"); + } + + // GLOBALS AND DEFAULTS + + // This is were the root elements of all impress.js instances will be kept. + // Yes, this means you can have more than one instance on a page, but I'm not + // sure if it makes any sense in practice ;) + var roots = {}; + + // some default config values. + var defaults = { + width: 1024, + height: 768, + maxScale: 1, + minScale: 0, + + perspective: 1000, + + transitionDuration: 1000 + }; + + // it's just an empty function ... and a useless comment. + var empty = function () { return false; }; + + // IMPRESS.JS API + + // And that's where interesting things will start to happen. + // It's the core `impress` function that returns the impress.js API + // for a presentation based on the element with given id ('impress' + // by default). + var impress = window.impress = function ( rootId ) { + + // If impress.js is not supported by the browser return a dummy API + // it may not be a perfect solution but we return early and avoid + // running code that may use features not implemented in the browser. + if (!impressSupported) { + return { + init: empty, + goto: empty, + prev: empty, + next: empty + }; + } + + rootId = rootId || "impress"; + + // if given root is already initialized just return the API + if (roots["impress-root-" + rootId]) { + return roots["impress-root-" + rootId]; + } + + // data of all presentation steps + var stepsData = {}; + + // element of currently active step + var activeStep = null; + + // current state (position, rotation and scale) of the presentation + var currentState = null; + + // array of step elements + var steps = null; + + // configuration options + var config = null; + + // scale factor of the browser window + var windowScale = null; + + // root presentation elements + var root = byId( rootId ); + var canvas = document.createElement("div"); + + var initialized = false; + + // STEP EVENTS + // + // There are currently two step events triggered by impress.js + // `impress:stepenter` is triggered when the step is shown on the + // screen (the transition from the previous one is finished) and + // `impress:stepleave` is triggered when the step is left (the + // transition to next step just starts). + + // reference to last entered step + var lastEntered = null; + + // `onStepEnter` is called whenever the step element is entered + // but the event is triggered only if the step is different than + // last entered step. + var onStepEnter = function (step) { + if (lastEntered !== step) { + triggerEvent(step, "impress:stepenter"); + lastEntered = step; + } + }; + + // `onStepLeave` is called whenever the step element is left + // but the event is triggered only if the step is the same as + // last entered step. + var onStepLeave = function (step) { + if (lastEntered === step) { + triggerEvent(step, "impress:stepleave"); + lastEntered = null; + } + }; + + // `initStep` initializes given step element by reading data from its + // data attributes and setting correct styles. + var initStep = function ( el, idx ) { + var data = el.dataset, + step = { + translate: { + x: toNumber(data.x), + y: toNumber(data.y), + z: toNumber(data.z) + }, + rotate: { + x: toNumber(data.rotateX), + y: toNumber(data.rotateY), + z: toNumber(data.rotateZ || data.rotate) + }, + scale: toNumber(data.scale, 1), + el: el + }; + + if ( !el.id ) { + el.id = "step-" + (idx + 1); + } + + stepsData["impress-" + el.id] = step; + + css(el, { + position: "absolute", + transform: "translate(-50%,-50%)" + + translate(step.translate) + + rotate(step.rotate) + + scale(step.scale), + transformStyle: "preserve-3d" + }); + }; + + // `init` API function that initializes (and runs) the presentation. + var init = function () { + if (initialized) { return; } + + // First we set up the viewport for mobile devices. + // For some reason iPad goes nuts when it is not done properly. + var meta = $("meta[name='viewport']") || document.createElement("meta"); + meta.content = "width=device-width, minimum-scale=1, maximum-scale=1, user-scalable=no"; + if (meta.parentNode !== document.head) { + meta.name = 'viewport'; + document.head.appendChild(meta); + } + + // initialize configuration object + var rootData = root.dataset; + config = { + width: toNumber( rootData.width, defaults.width ), + height: toNumber( rootData.height, defaults.height ), + maxScale: toNumber( rootData.maxScale, defaults.maxScale ), + minScale: toNumber( rootData.minScale, defaults.minScale ), + perspective: toNumber( rootData.perspective, defaults.perspective ), + transitionDuration: toNumber( rootData.transitionDuration, defaults.transitionDuration ) + }; + + windowScale = computeWindowScale( config ); + + // wrap steps with "canvas" element + arrayify( root.childNodes ).forEach(function ( el ) { + canvas.appendChild( el ); + }); + root.appendChild(canvas); + + // set initial styles + document.documentElement.style.height = "100%"; + + css(body, { + height: "100%", + overflow: "hidden" + }); + + var rootStyles = { + position: "absolute", + transformOrigin: "top left", + transition: "all 0s ease-in-out", + transformStyle: "preserve-3d" + }; + + css(root, rootStyles); + css(root, { + top: "50%", + left: "50%", + transform: perspective( config.perspective/windowScale ) + scale( windowScale ) + }); + css(canvas, rootStyles); + + body.classList.remove("impress-disabled"); + body.classList.add("impress-enabled"); + + // get and init steps + steps = $$(".step", root); + steps.forEach( initStep ); + + // set a default initial state of the canvas + currentState = { + translate: { x: 0, y: 0, z: 0 }, + rotate: { x: 0, y: 0, z: 0 }, + scale: 1 + }; + + initialized = true; + + triggerEvent(root, "impress:init", { api: roots[ "impress-root-" + rootId ] }); + }; + + // `getStep` is a helper function that returns a step element defined by parameter. + // If a number is given, step with index given by the number is returned, if a string + // is given step element with such id is returned, if DOM element is given it is returned + // if it is a correct step element. + var getStep = function ( step ) { + if (typeof step === "number") { + step = step < 0 ? steps[ steps.length + step] : steps[ step ]; + } else if (typeof step === "string") { + step = byId(step); + } + return (step && step.id && stepsData["impress-" + step.id]) ? step : null; + }; + + // used to reset timeout for `impress:stepenter` event + var stepEnterTimeout = null; + + // `goto` API function that moves to step given with `el` parameter (by index, id or element), + // with a transition `duration` optionally given as second parameter. + var goto = function ( el, duration ) { + + if ( !initialized || !(el = getStep(el)) ) { + // presentation not initialized or given element is not a step + return false; + } + + // Sometimes it's possible to trigger focus on first link with some keyboard action. + // Browser in such a case tries to scroll the page to make this element visible + // (even that body overflow is set to hidden) and it breaks our careful positioning. + // + // So, as a lousy (and lazy) workaround we will make the page scroll back to the top + // whenever slide is selected + // + // If you are reading this and know any better way to handle it, I'll be glad to hear about it! + window.scrollTo(0, 0); + + var step = stepsData["impress-" + el.id]; + + if ( activeStep ) { + activeStep.classList.remove("active"); + body.classList.remove("impress-on-" + activeStep.id); + } + el.classList.add("active"); + + body.classList.add("impress-on-" + el.id); + + // compute target state of the canvas based on given step + var target = { + rotate: { + x: -step.rotate.x, + y: -step.rotate.y, + z: -step.rotate.z + }, + translate: { + x: -step.translate.x, + y: -step.translate.y, + z: -step.translate.z + }, + scale: 1 / step.scale + }; + + // Check if the transition is zooming in or not. + // + // This information is used to alter the transition style: + // when we are zooming in - we start with move and rotate transition + // and the scaling is delayed, but when we are zooming out we start + // with scaling down and move and rotation are delayed. + var zoomin = target.scale >= currentState.scale; + + duration = toNumber(duration, config.transitionDuration); + var delay = (duration / 2); + + // if the same step is re-selected, force computing window scaling, + // because it is likely to be caused by window resize + if (el === activeStep) { + windowScale = computeWindowScale(config); + } + + var targetScale = target.scale * windowScale; + + // trigger leave of currently active element (if it's not the same step again) + if (activeStep && activeStep !== el) { + onStepLeave(activeStep); + } + + // Now we alter transforms of `root` and `canvas` to trigger transitions. + // + // And here is why there are two elements: `root` and `canvas` - they are + // being animated separately: + // `root` is used for scaling and `canvas` for translate and rotations. + // Transitions on them are triggered with different delays (to make + // visually nice and 'natural' looking transitions), so we need to know + // that both of them are finished. + css(root, { + // to keep the perspective look similar for different scales + // we need to 'scale' the perspective, too + transform: perspective( config.perspective / targetScale ) + scale( targetScale ), + transitionDuration: duration + "ms", + transitionDelay: (zoomin ? delay : 0) + "ms" + }); + + css(canvas, { + transform: rotate(target.rotate, true) + translate(target.translate), + transitionDuration: duration + "ms", + transitionDelay: (zoomin ? 0 : delay) + "ms" + }); + + // Here is a tricky part... + // + // If there is no change in scale or no change in rotation and translation, it means there was actually + // no delay - because there was no transition on `root` or `canvas` elements. + // We want to trigger `impress:stepenter` event in the correct moment, so here we compare the current + // and target values to check if delay should be taken into account. + // + // I know that this `if` statement looks scary, but it's pretty simple when you know what is going on + // - it's simply comparing all the values. + if ( currentState.scale === target.scale || + (currentState.rotate.x === target.rotate.x && currentState.rotate.y === target.rotate.y && + currentState.rotate.z === target.rotate.z && currentState.translate.x === target.translate.x && + currentState.translate.y === target.translate.y && currentState.translate.z === target.translate.z) ) { + delay = 0; + } + + // store current state + currentState = target; + activeStep = el; + + // And here is where we trigger `impress:stepenter` event. + // We simply set up a timeout to fire it taking transition duration (and possible delay) into account. + // + // I really wanted to make it in more elegant way. The `transitionend` event seemed to be the best way + // to do it, but the fact that I'm using transitions on two separate elements and that the `transitionend` + // event is only triggered when there was a transition (change in the values) caused some bugs and + // made the code really complicated, cause I had to handle all the conditions separately. And it still + // needed a `setTimeout` fallback for the situations when there is no transition at all. + // So I decided that I'd rather make the code simpler than use shiny new `transitionend`. + // + // If you want learn something interesting and see how it was done with `transitionend` go back to + // version 0.5.2 of impress.js: http://github.com/bartaz/impress.js/blob/0.5.2/js/impress.js + window.clearTimeout(stepEnterTimeout); + stepEnterTimeout = window.setTimeout(function() { + onStepEnter(activeStep); + }, duration + delay); + + return el; + }; + + // `prev` API function goes to previous step (in document order) + var prev = function () { + var prev = steps.indexOf( activeStep ) - 1; + prev = prev >= 0 ? steps[ prev ] : steps[ steps.length-1 ]; + + return goto(prev); + }; + + // `next` API function goes to next step (in document order) + var next = function () { + var next = steps.indexOf( activeStep ) + 1; + next = next < steps.length ? steps[ next ] : steps[ 0 ]; + + return goto(next); + }; + + // Adding some useful classes to step elements. + // + // All the steps that have not been shown yet are given `future` class. + // When the step is entered the `future` class is removed and the `present` + // class is given. When the step is left `present` class is replaced with + // `past` class. + // + // So every step element is always in one of three possible states: + // `future`, `present` and `past`. + // + // There classes can be used in CSS to style different types of steps. + // For example the `present` class can be used to trigger some custom + // animations when step is shown. + root.addEventListener("impress:init", function(){ + // STEP CLASSES + steps.forEach(function (step) { + step.classList.add("future"); + }); + + root.addEventListener("impress:stepenter", function (event) { + event.target.classList.remove("past"); + event.target.classList.remove("future"); + event.target.classList.add("present"); + }, false); + + root.addEventListener("impress:stepleave", function (event) { + event.target.classList.remove("present"); + event.target.classList.add("past"); + }, false); + + }, false); + + // Adding hash change support. + root.addEventListener("impress:init", function(){ + + // last hash detected + var lastHash = ""; + + // `#/step-id` is used instead of `#step-id` to prevent default browser + // scrolling to element in hash. + // + // And it has to be set after animation finishes, because in Chrome it + // makes transtion laggy. + // BUG: http://code.google.com/p/chromium/issues/detail?id=62820 + root.addEventListener("impress:stepenter", function (event) { + window.location.hash = lastHash = "#/" + event.target.id; + }, false); + + window.addEventListener("hashchange", function () { + // When the step is entered hash in the location is updated + // (just few lines above from here), so the hash change is + // triggered and we would call `goto` again on the same element. + // + // To avoid this we store last entered hash and compare. + if (window.location.hash !== lastHash) { + goto( getElementFromHash() ); + } + }, false); + + // START + // by selecting step defined in url or first step of the presentation + goto(getElementFromHash() || steps[0], 0); + }, false); + + body.classList.add("impress-disabled"); + + // store and return API for given impress.js root element + return (roots[ "impress-root-" + rootId ] = { + init: init, + goto: goto, + next: next, + prev: prev + }); + + }; + + // flag that can be used in JS to check if browser have passed the support test + impress.supported = impressSupported; + +})(document, window); + +// NAVIGATION EVENTS + +// As you can see this part is separate from the impress.js core code. +// It's because these navigation actions only need what impress.js provides with +// its simple API. +// +// In future I think about moving it to make them optional, move to separate files +// and treat more like a 'plugins'. +(function ( document, window ) { + 'use strict'; + + // throttling function calls, by Remy Sharp + // http://remysharp.com/2010/07/21/throttling-function-calls/ + var throttle = function (fn, delay) { + var timer = null; + return function () { + var context = this, args = arguments; + clearTimeout(timer); + timer = setTimeout(function () { + fn.apply(context, args); + }, delay); + }; + }; + + // wait for impress.js to be initialized + document.addEventListener("impress:init", function (event) { + // Getting API from event data. + // So you don't event need to know what is the id of the root element + // or anything. `impress:init` event data gives you everything you + // need to control the presentation that was just initialized. + var api = event.detail.api; + + // KEYBOARD NAVIGATION HANDLERS + + // Prevent default keydown action when one of supported key is pressed. + document.addEventListener("keydown", function ( event ) { + if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { + event.preventDefault(); + } + }, false); + + // Trigger impress action (next or prev) on keyup. + + // Supported keys are: + // [space] - quite common in presentation software to move forward + // [up] [right] / [down] [left] - again common and natural addition, + // [pgdown] / [pgup] - often triggered by remote controllers, + // [tab] - this one is quite controversial, but the reason it ended up on + // this list is quite an interesting story... Remember that strange part + // in the impress.js code where window is scrolled to 0,0 on every presentation + // step, because sometimes browser scrolls viewport because of the focused element? + // Well, the [tab] key by default navigates around focusable elements, so clicking + // it very often caused scrolling to focused element and breaking impress.js + // positioning. I didn't want to just prevent this default action, so I used [tab] + // as another way to moving to next step... And yes, I know that for the sake of + // consistency I should add [shift+tab] as opposite action... + document.addEventListener("keyup", function ( event ) { + if ( event.keyCode === 9 || ( event.keyCode >= 32 && event.keyCode <= 34 ) || (event.keyCode >= 37 && event.keyCode <= 40) ) { + switch( event.keyCode ) { + case 33: // pg up + case 37: // left + case 38: // up + api.prev(); + break; + case 9: // tab + case 32: // space + case 34: // pg down + case 39: // right + case 40: // down + api.next(); + break; + } + + event.preventDefault(); + } + }, false); + + // delegated handler for clicking on the links to presentation steps + document.addEventListener("click", function ( event ) { + // event delegation with "bubbling" + // check if event target (or any of its parents is a link) + var target = event.target; + while ( (target.tagName !== "A") && + (target !== document.documentElement) ) { + target = target.parentNode; + } + + if ( target.tagName === "A" ) { + var href = target.getAttribute("href"); + + // if it's a link to presentation step, target this step + if ( href && href[0] === '#' ) { + target = document.getElementById( href.slice(1) ); + } + } + + if ( api.goto(target) ) { + event.stopImmediatePropagation(); + event.preventDefault(); + } + }, false); + + // delegated handler for clicking on step elements + document.addEventListener("click", function ( event ) { + var target = event.target; + // find closest step element that is not active + while ( !(target.classList.contains("step") && !target.classList.contains("active")) && + (target !== document.documentElement) ) { + target = target.parentNode; + } + + if ( api.goto(target) ) { + event.preventDefault(); + } + }, false); + + // touch handler to detect taps on the left and right side of the screen + // based on awesome work of @hakimel: https://github.com/hakimel/reveal.js + document.addEventListener("touchstart", function ( event ) { + if (event.touches.length === 1) { + var x = event.touches[0].clientX, + width = window.innerWidth * 0.3, + result = null; + + if ( x < width ) { + result = api.prev(); + } else if ( x > window.innerWidth - width ) { + result = api.next(); + } + + if (result) { + event.preventDefault(); + } + } + }, false); + + // rescale presentation when window is resized + window.addEventListener("resize", throttle(function () { + // force going to active step again, to trigger rescaling + api.goto( document.querySelector(".active"), 500 ); + }, 250), false); + + }, false); + +})(document, window); + +// THAT'S ALL FOLKS! +// +// Thanks for reading it all. +// Or thanks for scrolling down and reading the last part. +// +// I've learnt a lot when building impress.js and I hope this code and comments +// will help somebody learn at least some part of it. \ No newline at end of file diff --git a/robocon/motor1.jpg b/robocon/motor1.jpg new file mode 100644 index 0000000..5f8aa4d Binary files /dev/null and b/robocon/motor1.jpg differ diff --git a/robocon/motor2.jpg b/robocon/motor2.jpg new file mode 100644 index 0000000..cbf0861 Binary files /dev/null and b/robocon/motor2.jpg differ diff --git a/robocon/p.png b/robocon/p.png new file mode 100644 index 0000000..fdaf77f Binary files /dev/null and b/robocon/p.png differ diff --git a/robocon/robo1.js.css b/robocon/robo1.js.css new file mode 100644 index 0000000..9bd5ab0 --- /dev/null +++ b/robocon/robo1.js.css @@ -0,0 +1,50 @@ +/* add your css style rules here */ + + +a { + color: inherit; + text-decoration: none; +} +h2 { + text-align: center; +} +img{ + display: block; + margin-left: auto; + margin-right: auto +} +img.side { + display: inline; +} +body { + background-image: -webkit-linear-gradient(top left, silver, white); + background-image: -moz-linear-gradient(top left, silver, white); + background-image: -ms-linear-gradient(top left, silver, white); + background-image: -o-linear-gradient(top left, silver, white); + background-image: linear-gradient(top left, silver, white); +} + +.step { + width: 900px; + height: 700px; + padding: 20px 30px; + + font-size: 34px; + text-align: left; + + opacity: 0.1; +} + +.step.active { + opacity: 1; +} + +.slide { + background: white; +} + +code { + background-color: yellow; + font-size: 14px; +} + diff --git a/robocon/robo1.js.html b/robocon/robo1.js.html new file mode 100644 index 0000000..57fc901 --- /dev/null +++ b/robocon/robo1.js.html @@ -0,0 +1,381 @@ + + + + + + + Intro to Autonomous Robotics | by Robodarshan :) + + + + + + + + + + + + +
+ + + +
+ + + + +

Introduction to Robotics

+ +

+ +

+ + +
+ +
+ + +

WELCOME EVERYBODY

+ +

+ +

// To be replaced by live face detected image

+ + +
+ +
+ + +

What is “Robot” ?

+ +

+ + +
+ +
+ + +

Let’s Google it

+ +

+ + +
+ +
+ + +

admin : OK Bot, show us what can you do …

+ +

bot : I can …

+ +
    +
  • Learn Skills ranging from electronics, mechanics, controls, programming, etc …
  • +
  • Work in Industry assembly lines, like a robotic arm used for car-painting, parts assembling, etc…
  • +
+ +

+ + +
+ +
+ + +

Contd…

+ +
    +
  • +

    Function as a mobile robot such as terrestial, aerial, aquatic or hybrid vehicle + be it manually controlled or autonomous.

    +
  • +
  • +

    Work in swarms to co-ordinate a task

    +
  • +
+ +

+ + +
+ +
+ + +

So, what will you learn today ?

+ +

How about some robotics ?
+Well, we guess you already knew that :)

+ +
    +
  • +

    First we’ll talk about Manual Robotics, the ones controlled by human (yup, that’s you)

    +
  • +
  • +

    Then, we’ll move on to autonomous bots, the ones which can perform simple tasks on their own. ( Remember Wall-E ? )

    +
  • +
  • +

    If time permits, we’ll talk about robots with “eyes” (err.. cameras).

    +
  • +
+ + +
+ +
+ + +

Mechanical Construction

+ +
    +
  • Chassis, i.e. the basic body structure (generally rectangular) +
      +
    • +

      Preferred Material : Flex Board (25 cm x 25 cm) +

      +
    • +
    • +

      Others : Motor Clamps
      +

      +
    • +
    +
  • +
+ + +
+ +
+ + +

Wheels

+ +
    +
  • +

    Normal Wheels , the ones you see in cars … toy cars.
    + +

    +
  • +
  • +

    Castor Wheels , a non-drivable wheel that is mounted at the bottom of a vehicle (or robot, in our case), that can move in any direction. You can find them under the ( legs of ) movable tables.
    + +

    +
  • +
+ + +
+ +
+ + +

DC Motors

+ +
    +
  • Runs on DC input.
  • +
  • Types +
      +
    • Geared Motor :
      +
        +
      • Pros: +
          +
        1. Used for bringing about a change in speed, by the use of gears.
        2. +
        3. Also used to change axis and direction of motion
        4. +
        +
      • +
      • Cons: +
          +
        1. No feedback mechanism.
        2. +
        +
      • +
      +
    • +
    +
  • +
+ + +
+ +
+ + +

DC Motors (contd.)

+ +
    +
  • Types (contd.) +
      +
    • Servo Motors +
        +
      • Pros: +
          +
        • Used for high torque operations
        • +
        +
      • +
      • Cons: +
          +
        • Costly
        • +
        +
      • +
      +
    • +
    +
  • +
+ +

+ + +
+ +
+ + +

Motion Direction Control

+ +
    +
  • H-Bridge Circuit +
      +
    • Simple electrical circuit using which you can change the polarity at the load.
    • +
    +
  • +
+ +

+ + +
+ +
+ + +
    +
  • Example: +
      +
    • DPDT Switch:
      + Switching device that uses H-Bridge principle to change the polarity of load and hence the motion of the motor whenever needed.
    • +
    +
  • +
+ +

+

+ + +
+ +
+ + +

Drives

+ +
    +
  • Types of drive we’ll be using: +
      +
    • 2 wheel drive, 2 gearbox with castor wheel
    • +
    • 4 wheel drive, 4 gearbox
    • +
    +
  • +
  • Others +
      +
    • N Wheel Drive
    • +
    • Tank Wheel Drive
    • +
    +
  • +
+ + +
+ +
+ + +

2 wheel drive with castor wheel

+ +

It has

+ +
    +
  • 2 active wheels with gearboxes
  • +
  • 1 castor wheel for balance and free movement
  • +
+ +

+ + +
+ +
+ + +

4 wheel drive with 4 gearboxes

+ +

It has 4 wheels connected with 4 gearboxes for fast and agile movement

+ +

+ + +
+ +
+ + +

Locomotion using Differential Drive system

+ +

bot: I wanna move…
+admin: How?
+bot: Well now that you have asked so nicely…

+ +
    +
  • Differential Drive is one way to accomplish this
    +
  • +
  • The simplest motions (shown above) occur when all of the wheels are moving
  • +
  • Different motions are also possible if we keep one/many wheels static
  • +
+ + +
+ +
+ + +

SHOW TIME

+ +

We’re pretty sure that you are bored to hell.
+So, here’s a little treat for you.

+ +

Sit back and enjoy :D

+ + +
+ +
+ + +

Question time

+ +

Now, Throw something at us

+ +

Just dont throw an error :P

+ + + +
+ + +
+ + + + + + \ No newline at end of file diff --git a/robocon/robo1.js.text b/robocon/robo1.js.text new file mode 100644 index 0000000..2094e7f --- /dev/null +++ b/robocon/robo1.js.text @@ -0,0 +1,259 @@ +title: Intro to Autonomous Robotics +author: Robodarshan :) + + +%%%%% +%% Add some inline style rules... + +%css + +a { + color: inherit; + text-decoration: none; +} +h2 { + text-align: center; +} +img{ + display: block; + margin-left: auto; + margin-right: auto +} +img.side { + display: inline; +} +body { + background-image: -webkit-linear-gradient(top left, silver, white); + background-image: -moz-linear-gradient(top left, silver, white); + background-image: -ms-linear-gradient(top left, silver, white); + background-image: -o-linear-gradient(top left, silver, white); + background-image: linear-gradient(top left, silver, white); +} + +.step { + width: 900px; + height: 700px; + padding: 20px 30px; + + font-size: 34px; + text-align: left; + + opacity: 0.1; +} + +.step.active { + opacity: 1; +} + +.slide { + background: white; +} + +code { + background-color: yellow; + font-size: 14px; +} + +%end + + +%%%%%%%%%%%%%%%%%%% +%% Here we go... + + +!SLIDE x=0 y=0 scale=2 + +##Introduction to *Robotics* + + + + + + +!SLIDE x=2000 y=0 rotate-y=-50 scale=2 + +##WELCOME EVERYBODY + +![](./face_detect.jpg) + +// To be replaced by live face detected image + +!SLIDE x=-2000 y=0 rotate-y=50 scale=2 + +##*What is "Robot"* ? + + + + +!SLIDE x=0 y=-800 scale=1 z=500 rotate-x=-30 + +##Let's ***Google*** it + + + + +!SLIDE x=0 y=1500 rotate-x=45 scale=5 + +_**admin**_ : OK **Bot**, show us what can you do ... + +_**bot**_ : I can ... + +* Learn Skills ranging from electronics, mechanics, controls, programming, etc ... +* Work in Industry assembly lines, like a robotic arm used for car-painting, parts assembling, etc... + + + +!SLIDE x=0 y=-1500 z=-1500 rotate-x=45 scale=5 +##Contd... + +* Function as a mobile robot such as terrestial, aerial, aquatic or hybrid vehicle + be it manually controlled or autonomous. + +* Work in swarms to co-ordinate a task + + + +!SLIDE x=3500 y=1500 rotate-x=45 rotate-z=90 scale=6 + +##**So, what will you learn today ?** + +How about some robotics ? +Well, we guess you already knew that :) + +* First we'll talk about ***Manual Robotics***, the ones controlled by human (yup, that's you) + +* Then, we'll move on to autonomous bots, the ones which can perform simple tasks on their own. ( Remember Wall-E ? ) + +* If time permits, we'll talk about robots with **"eyes"** (err.. cameras). + +!SLIDE x=3500 y=-4000 z=-2500 rotate-x=45 rotate-z=90 scale=4 + +##Mechanical Construction + +- **Chassis**, i.e. the basic body structure (generally rectangular) + - Preferred Material : Flex Board (25 cm x 25 cm) + + + - Others : Motor Clamps + + +!SLIDE x=4600 y=2550 scale=6 rotate-z=0 rotate-x=0 rotate-y=60 z=5000 + +## **Wheels** + +- **Normal Wheels** , the ones you see in cars ... toy cars. + + + +- **Castor Wheels** , a non-drivable wheel that is mounted at the bottom of a vehicle (or robot, in our case), that can move in any direction. You can find them under the ( legs of ) movable tables. + + + + +!SLIDE x=5600 y=3000 z=0 rotate-x=0 rotate-y=-45 rotate-z= scale=6 + +##**DC Motors** + +- Runs on DC input. +- Types + - **Geared Motor :** + - Pros: + 1. Used for bringing about a change in speed, by the use of gears. + 2. Also used to change axis and direction of motion + - Cons: + 1. No feedback mechanism. + + + +!SLIDE x=6000 y=4000 scale=2 + +##**DC Motors (contd.)** + +- Types (contd.) + - **Servo Motors** + - Pros: + - Used for high torque operations + - Cons: + - Costly + + + +!SLIDE x=6200 y=4300 z=-1000 rotate-x=40 rotate-y=-30 scale=1 + +##Motion Direction Control + +- H-Bridge Circuit + - Simple electrical circuit using which you can change the polarity at the load. + + + +!SLIDE x=8000 y=4300 z=-500 rotate-x=20 rotate-y=-45 scale=1 + +- Example: + - DPDT Switch: + Switching device that uses H-Bridge principle to change the polarity of load and hence the motion of the motor whenever needed. + + + + +!SLIDE x=5000 y=4500 scale=10 rotate-y=0 rotate-x=-30 +##Drives + +- Types of drive we'll be using: + - 2 wheel drive, 2 gearbox with castor wheel + - 4 wheel drive, 4 gearbox +- Others + - N Wheel Drive + - Tank Wheel Drive + +!SLIDE x=8000 y=500 z=1000 rotate-y=-15 scale=6 rotate-x=-15 + +##**2 wheel drive with castor wheel** + +It has + +- 2 active wheels with gearboxes +- 1 castor wheel for balance and free movement + + + + +!SLIDE x=13000 y=1500 z=1000 rotate-y=45 scale=10 rotate-x=45 + +##**4 wheel drive with 4 gearboxes** + +It has 4 wheels connected with 4 gearboxes for fast and agile movement + + + +!SLIDE x=18000 y=4500 rotate-y=65 scale=6 rotate-x=135 z=-4500 + +##**Locomotion using Differential Drive system** + +bot: I wanna move... +admin: How? +bot: Well now that you have asked so nicely... + +- Differential Drive is one way to accomplish this + +- The simplest motions (shown above) occur when all of the wheels are moving +- Different motions are also possible if we keep one/many wheels static + +!SLIDE x=7000 + +**SHOW TIME** + +We're pretty sure that you are bored to hell. +So, here's a little treat for you. + +Sit back and enjoy :D + +!SLIDE rotate-x=00 x=5000 y=500 z=-500 rotate-y=-30 +**Question time** + +Now, Throw something at us + +Just dont throw an error :P + +%% The End +%%%%%%%%%%%%%%% \ No newline at end of file diff --git a/robocon/robodarshan.png b/robocon/robodarshan.png new file mode 100644 index 0000000..acbfc98 Binary files /dev/null and b/robocon/robodarshan.png differ diff --git a/robocon/robot_def.jpg b/robocon/robot_def.jpg new file mode 100644 index 0000000..e24d83a Binary files /dev/null and b/robocon/robot_def.jpg differ diff --git a/robocon/swarm.jpg b/robocon/swarm.jpg new file mode 100644 index 0000000..6239d18 Binary files /dev/null and b/robocon/swarm.jpg differ diff --git a/robocon/troll_final.jpg b/robocon/troll_final.jpg new file mode 100644 index 0000000..4623b7f Binary files /dev/null and b/robocon/troll_final.jpg differ diff --git a/robocon/wheel1.jpg b/robocon/wheel1.jpg new file mode 100644 index 0000000..548de7f Binary files /dev/null and b/robocon/wheel1.jpg differ diff --git a/serial_n_scan.py b/serial_n_scan.py new file mode 100644 index 0000000..b4d5cac --- /dev/null +++ b/serial_n_scan.py @@ -0,0 +1,57 @@ +#------------------------------------------------------------------------------- +# Name: serial n scan +# +# Purpose: 1.To scan a image n divide into least possible number of lines +# 2.Send required commands in the serial port(maybe, 2 will be better) as tuples +# (permitted values are -1,0,1 for both wheels) +# +# Author: bendtherules +# +# Created: 21-12-2012 +#------------------------------------------------------------------------------- + +import pygame +from pygame.locals import * +pygame.init(); +milli_start=pygame.time.get_ticks() +surf=pygame.display.set_mode((1,1)); +img=pygame.image.load("a.png").convert_alpha(); +pygame.Surface.lock(img); +arr_3d=pygame.surfarray.pixels3d(img); +arr_2d=pygame.surfarray.pixels_alpha(img); +pygame.Surface.unlock(img); +#loop here +start_x=start_y=None; +all_lists=[]; +count_list=0; +counted=[[False]*arr_2d]*arr_2d[0];#used as an array of the same dimensions as arr_2d to know whether it has been scanned +for x in range(len(arr_2d)): + for y in range(len(arr_2d[0])): + if arr_2d[x][y]>=128: + arr_2d[x][y]=255; + if start_x==None: + start_x=x; + start_y=y; + counted[x][y]=True; + else: + arr_2d[x][y]=0; +def scan(start_x=start_x,start_y=start_y,new=True): + #new should be true when it is a new line or new sub-line + #start_x and start_y needs to be passed in this recursive function in later recursion calls + #Default values are passed to make the function friendlier, but they should be overridden in later calls + global arr_2d; + global counted; + global count_list; + global all_lists; + if new==True: + temp_list=[]; + for count_x in (-1,0,1): + for count_y in (-1,0,1): + if arr_2d[x+count_x][y+count_y]==255 and counted[x][y]==False: + #counted[x][y] check eliminated the (start_x,start_y) pixel + counted[x+count_x][y+count_y]=True; + all_lists.append((x+count_x,y+count_y)) + +#the end +milli_end=pygame.time.get_ticks() +print(milli_end-milli_start); diff --git a/serial_setup.py b/serial_setup.py new file mode 100644 index 0000000..367f355 --- /dev/null +++ b/serial_setup.py @@ -0,0 +1,6 @@ +import serial +port=8 +ser=None +def setup(port=port): + global ser + ser=serial.Serial(port,baudrate=9600) \ No newline at end of file diff --git a/simulate_keypress.py b/simulate_keypress.py new file mode 100644 index 0000000..4b91514 --- /dev/null +++ b/simulate_keypress.py @@ -0,0 +1,29 @@ +import win32com.client as comclt +import win32api, win32con +def click(x,y): + win32api.SetCursorPos((x,y)) + win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) + win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) +from time import sleep +wsh= comclt.Dispatch("WScript.Shell") +def choose(): + #wsh.AppActivate(5020) # select another application + #sleep(.2) + #wsh.SendKeys("{BACKSPACE}") # send the keys you want + #click(50,20) + pass +def press_up(): + choose() + wsh.SendKeys("{UP}") + +def press_down(): + choose() + wsh.SendKeys("{DOWN}") + +def press_left(): + choose() + wsh.SendKeys("{LEFT}") + +def press_right(): + choose() + wsh.SendKeys("{RIGHT}") \ No newline at end of file diff --git a/spr_bullet.png b/spr_bullet.png new file mode 100644 index 0000000..5057ee9 Binary files /dev/null and b/spr_bullet.png differ diff --git a/spr_water.png b/spr_water.png new file mode 100644 index 0000000..1b0924c Binary files /dev/null and b/spr_water.png differ diff --git a/spring_strip8.png b/spring_strip8.png new file mode 100644 index 0000000..48d1722 Binary files /dev/null and b/spring_strip8.png differ diff --git a/sprite19.png b/sprite19.png new file mode 100644 index 0000000..f35b80a Binary files /dev/null and b/sprite19.png differ diff --git a/sprite20.png b/sprite20.png new file mode 100644 index 0000000..b94d501 Binary files /dev/null and b/sprite20.png differ diff --git a/sprite22_strip2.png b/sprite22_strip2.png new file mode 100644 index 0000000..594692b Binary files /dev/null and b/sprite22_strip2.png differ diff --git a/sprite24.png b/sprite24.png new file mode 100644 index 0000000..874410b Binary files /dev/null and b/sprite24.png differ diff --git a/sprite25_strip2.png b/sprite25_strip2.png new file mode 100644 index 0000000..3bca858 Binary files /dev/null and b/sprite25_strip2.png differ diff --git a/sprite8.png b/sprite8.png new file mode 100644 index 0000000..d5236d7 Binary files /dev/null and b/sprite8.png differ diff --git a/sprite9.png b/sprite9.png new file mode 100644 index 0000000..7224856 Binary files /dev/null and b/sprite9.png differ diff --git a/test.py b/test.py new file mode 100644 index 0000000..909efb7 --- /dev/null +++ b/test.py @@ -0,0 +1,12 @@ +import pygame +from pygame.locals import * + +pygame.init() +pygame.display.set_mode((200,200)) +pygame.display.set_caption("wat?") +a=pygame.image.load("a.png"); +while True: + # event check + for event in pygame.event.get(): + if event.type == QUIT: + exit(); diff --git a/testing.py b/testing.py new file mode 100644 index 0000000..ca0b3ac --- /dev/null +++ b/testing.py @@ -0,0 +1,66 @@ +import SimpleCV as s +import time +import time +img = s.Image("C:\Users\Abhas_2\Desktop\miapu.jpg") +iset=s.ImageSet() +total_time=100 # in steps +w=40 +h=40 +c=time.clock() +class Pixel(object): + def __init__(self,(ori_x,ori_y),(start_x,start_y),arr): + self.ori_x=ori_x + self.ori_y=ori_y + self.x=float(start_x) + self.y=float(start_y) + self.angle=s.math.atan2(-(ori_y-start_y),(ori_x-start_x)) + self.dist=distance((ori_x,ori_y),(start_x,start_y)) #float + self.accln=2*self.dist/float((total_time**2)) + self.vel=self.accln*total_time + self.arr=arr + def step(self): + if distance((self.x,self.y),(self.ori_x,self.ori_y))>(w+h)/4: + self.x+=self.vel*s.math.cos(self.angle) + self.y-=self.vel*s.math.sin(self.angle) + else: + self.x=self.ori_x + self.y=self.ori_y + +## if round(self.x)img.width-w/2: +## self.x=img.width-w/2 +## if round(self.y)>img.height-h/2: +## self.y=img.height-h/2 + self.vel-=self.accln + + +def distance((x1,y1),(x2,y2)): + import math + return(math.sqrt((x2-x1)**2+(y2-y1)**2)) + +n1=img.getNumpy() +p_list=[] +from random import randint +for c1 in range(img.width/w): + for c2 in range(img.height/h): + p_list.append( Pixel( ((c1+0.5)*w,(c2+0.5)*h),(randint(img.width/4,img.width*3/4),randint(img.height/4,img.height*3/4)),n1[c1*w:(c1+1)*w,c2*h:(c2+1)*h] ) ) +print("Done "+str(time.clock()-c)) +c=time.clock() + #print((c1+0.5)*w,(c2+0.5)*h) +print(len(p_list)) +for count in range(total_time): + #del n + i1=s.Image((img.width,img.height)) + n=i1.getNumpy() + for p in p_list: + p.step() + #temp=n[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2] + n[round(p.x)-w/2:round(p.x)+w/2,round(p.y)-h/2:round(p.y)+h/2]=p.arr + img=s.Image(n) + iset.append(img) + #img.scale(2).show() +print(time.clock()-c) +iset.save(r"C:\Users\Abhas_2\Desktop\ani.gif",2.5/100) \ No newline at end of file diff --git a/tk_try.py b/tk_try.py new file mode 100644 index 0000000..84a5bb6 --- /dev/null +++ b/tk_try.py @@ -0,0 +1,10 @@ +import wx +class MyFrame(wx.Frame): + """ We simply derive a new class of Frame. """ + def __init__(self, parent, title): + wx.Frame.__init__(self, parent, title=title, size=(200,100)) + self.control = wx.TextCtrl(self, style=wx.TE_MULTILINE) + self.Show(True) +app = wx.App(False) +frame = MyFrame(None, 'Small editor') +app.MainLoop() \ No newline at end of file diff --git a/todo_pyglet.txt b/todo_pyglet.txt new file mode 100644 index 0000000..00c061c --- /dev/null +++ b/todo_pyglet.txt @@ -0,0 +1,12 @@ +1. Schedule_interval with internal_update method in gameObject class + internal_update should include update() to be overridden by sub-class. + internal_update should allow rot_speed and hspeed, vspeed, speed, etc. + ** Better way - use list_class and list_instance and list_batch +2. Handle collision in a novel way +3. Investigate default draw method. Allow for multiple images (already possible - every sprite loaded gets drawn). +4. Use a batch_list internally for drawing. +5. Convert pygame rect, circle, line classes. +6. Seperate resource loading, level loading (with *similar multiple instance* creation helper method). +7. Allow timers. +8. Handle proper deletion. +9. Keep proper track of handlers on level reload. \ No newline at end of file diff --git a/try.py b/try.py new file mode 100644 index 0000000..84ede01 --- /dev/null +++ b/try.py @@ -0,0 +1,96 @@ +import sys,pygame,math; +#from class_ball import ball +pygame.init() +clock = pygame.time.Clock() +size=width,height=640,480 +#x=320 +#y=240 +#speed=3 +#dir=None +black=0,0,0 +class_list=[] +screen=pygame.display.set_mode(size) +#ball=pygame.image.load("gun.png") +#ballrect=ball.get_rect() +#mouse_down=False +#print pygame + +##class ball(object): +## global mouse_down +## def __init__(self,x=320,y=240,speed=3): +## self.x=x +## self.y=y +## self.speed=speed +## self.dir=None +## self.ball=pygame.image.load("gun.png") +## self.ballrect=self.ball.get_rect() +## #global mouse_down +## #mouse_down=False; +## if not mouse_down: +## print 5 +## +## def mouse_handler(self): +## global mouse_down +## if pygame.event.get(pygame.MOUSEBUTTONDOWN) or mouse_down == True: +## self.x=self.mouse_x +## self.y=self.mouse_y +## mouse_down=True +## print 6 +## +## if pygame.event.get(pygame.MOUSEBUTTONUP): +## mouse_down=False +## +## def step(self): +## self.mouse_x,self.mouse_y=pygame.mouse.get_pos() +## self.diff_x=self.mouse_x-self.x +## self.diff_y=self.mouse_y-self.y +## self.diff_rad=math.atan2(self.diff_y,self.diff_x) +## self.x+=self.speed*math.cos(self.diff_rad) +## self.y+=self.speed*math.sin(self.diff_rad) +## self.ballrect.center=(self.x,self.y) +## +## def draw(self): +## screen.blit(self.ball, self.ballrect) +## +## +## def update(self): +## self.step() +## self.mouse_handler() +## self.draw() + + +ball_1=ball(class_lst=class_list) +while 1: + screen.fill(black) + +## if event.type == pygame.MOUSEBUTTONDOWN or mouse_down == True: +## x=mouse_x +## y=mouse_y +## mouse_down=True +## +## if event.type == pygame.MOUSEBUTTONUP: +## mouse_down=False +## +## mouse_x,mouse_y=pygame.mouse.get_pos() +## diff_x=mouse_x-x +## diff_y=mouse_y-y +## diff_rad=math.atan2(diff_y,diff_x) +## x+=speed*math.cos(diff_rad) +## y+=speed*math.sin(diff_rad) +## +## ballrect.center=(x,y) +## if ballrect.left < 0 or ballrect.right > width: +## speed[0] = -speed[0] +## if ballrect.top < 0 or ballrect.bottom > height: +## speed[1] = -speed[1] + + +## screen.blit(ball, ballrect) + + ball_1.update() + clock.tick(120) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: sys.exit() + + pygame.display.flip() \ No newline at end of file diff --git a/tryy.py b/tryy.py new file mode 100644 index 0000000..4a816aa --- /dev/null +++ b/tryy.py @@ -0,0 +1,96 @@ +import sys,pygame,math,class_ball; +#from class_ball import * +pygame.init() +clock = pygame.time.Clock() +size=width,height=640,480 +#x=320 +#y=240 +#speed=3 +#dir=None +black=0,0,0 +class_list=[] +screen=pygame.display.set_mode(size) +#ball=pygame.image.load("gun.png") +#ballrect=ball.get_rect() +#mouse_down=False +#print pygame + +##class ball(object): +## global mouse_down +## def __init__(self,x=320,y=240,speed=3): +## self.x=x +## self.y=y +## self.speed=speed +## self.dir=None +## self.ball=pygame.image.load("gun.png") +## self.ballrect=self.ball.get_rect() +## #global mouse_down +## #mouse_down=False; +## if not mouse_down: +## print 5 +## +## def mouse_handler(self): +## global mouse_down +## if pygame.event.get(pygame.MOUSEBUTTONDOWN) or mouse_down == True: +## self.x=self.mouse_x +## self.y=self.mouse_y +## mouse_down=True +## print 6 +## +## if pygame.event.get(pygame.MOUSEBUTTONUP): +## mouse_down=False +## +## def step(self): +## self.mouse_x,self.mouse_y=pygame.mouse.get_pos() +## self.diff_x=self.mouse_x-self.x +## self.diff_y=self.mouse_y-self.y +## self.diff_rad=math.atan2(self.diff_y,self.diff_x) +## self.x+=self.speed*math.cos(self.diff_rad) +## self.y+=self.speed*math.sin(self.diff_rad) +## self.ballrect.center=(self.x,self.y) +## +## def draw(self): +## screen.blit(self.ball, self.ballrect) +## +## +## def update(self): +## self.step() +## self.mouse_handler() +## self.draw() + + +#ball_1=ball(class_lst=class_list) +while 1: + screen.fill(black) + +## if event.type == pygame.MOUSEBUTTONDOWN or mouse_down == True: +## x=mouse_x +## y=mouse_y +## mouse_down=True +## +## if event.type == pygame.MOUSEBUTTONUP: +## mouse_down=False +## +## mouse_x,mouse_y=pygame.mouse.get_pos() +## diff_x=mouse_x-x +## diff_y=mouse_y-y +## diff_rad=math.atan2(diff_y,diff_x) +## x+=speed*math.cos(diff_rad) +## y+=speed*math.sin(diff_rad) +## +## ballrect.center=(x,y) +## if ballrect.left < 0 or ballrect.right > width: +## speed[0] = -speed[0] +## if ballrect.top < 0 or ballrect.bottom > height: +## speed[1] = -speed[1] + + +## screen.blit(ball, ballrect) + + #ball_1.update() + clock.tick(120) + + for event in pygame.event.get(): + if event.type == pygame.QUIT: sys.exit() + + pygame.display.flip() \ No newline at end of file diff --git a/watcher.py b/watcher.py new file mode 100644 index 0000000..168eb9a --- /dev/null +++ b/watcher.py @@ -0,0 +1,33 @@ +import sys +import time +import subprocess +import os +dir_to_watch=r"E:\Babu\pytry\robocon" +file_to_watch=r"robo1.js.text" +full_path=os.path.join(dir_to_watch,file_to_watch) +def build_cmd(): + a,b= subprocess.Popen(r'slideshow build '+file_to_watch+' -t impress.js', shell=True,cwd=dir_to_watch, stderr=subprocess.PIPE, stdout=subprocess.PIPE ).communicate() + return a +from watchdog.observers import Observer +from watchdog.tricks import LoggerTrick +import watchdog + +print("Watching file "+full_path+" for any changes.. Dont close") + +class rebuild(watchdog.events.FileSystemEventHandler): + def on_any_event(self,event): + if event.src_path==full_path: + print("Re-building") + print(build_cmd()) + +event_handler = rebuild() +observer = Observer() +observer.schedule(event_handler, dir_to_watch, recursive=True) +observer.start() +try: + while True: + time.sleep(1) +except KeyboardInterrupt: + observer.stop() +observer.join() + diff --git a/white ball detect.py b/white ball detect.py new file mode 100644 index 0000000..69bb434 --- /dev/null +++ b/white ball detect.py @@ -0,0 +1,20 @@ +import SimpleCV +display = SimpleCV.Display() +#cam = SimpleCV.Camera() +#normaldisplay = True +while display.isNotDone(): + #if display.mouseRight: + #normaldisplay = not(normaldisplay) + #print "Display Mode:", "Normal" if normaldisplay else "Segmented" + #img = cam.getImage().flipHorizontal() + img=SimpleCV.Image(r"C:\Users\Abhas_2\Documents\Bluetooth Folder\IMAG0355.jpg").scale(.5) + dist = img.colorDistance(SimpleCV.Color.BLACK).dilate(2) + segmented = dist.stretch(150,255) + blobs = segmented.findBlobs() + if blobs: + circles = blobs.filter([b.isCircle(0.2) for b in blobs]) + if circles: img.drawCircle((circles[-1].x, circles[-1].y), circles[-1].radius(),SimpleCV.Color.BLUE,3) + #if normaldisplay: + #img.show() +## else: + segmented.show() \ No newline at end of file