All the previous files
@@ -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
|
||||||
@@ -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
|
||||||
|
After Width: | Height: | Size: 1.9 KiB |
@@ -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();
|
||||||
|
After Width: | Height: | Size: 12 KiB |
@@ -0,0 +1,5 @@
|
|||||||
|
from SimpleCV import Camera, Display, Image;
|
||||||
|
cam=Camera();
|
||||||
|
disp=Display();
|
||||||
|
img=cam.getImage();
|
||||||
|
img.sample_points(disp);
|
||||||
@@ -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()):
|
||||||
|
temp.update();
|
||||||
|
else:
|
||||||
|
group_name.remove(temp);
|
||||||
|
|
||||||
|
# creating new classes
|
||||||
|
class player(obj):
|
||||||
|
all_instances=pygame.sprite.RenderUpdates();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha)
|
||||||
|
player.all_instances.add(self);
|
||||||
|
|
||||||
|
|
||||||
|
a1=player(surf.get_width()/2,surf.get_height()/2,"a.png",alpha=1)
|
||||||
|
a1.vspeed=.1;
|
||||||
|
a2=player(100,100,"a.png",alpha=1)
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
# 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().__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.image,(self.x-self.image.get_width()/2,self.y-self.image.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()):
|
||||||
|
temp.update();
|
||||||
|
else:
|
||||||
|
group_name.remove(temp);
|
||||||
|
del temp;
|
||||||
|
|
||||||
|
# creating new classes
|
||||||
|
#create two instances player_down and player_up and specific clear functions
|
||||||
|
class player_down(obj):
|
||||||
|
#lower player
|
||||||
|
all_instances=pygame.sprite.RenderUpdates();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha)
|
||||||
|
player_down.all_instances.add(self);
|
||||||
|
|
||||||
|
class player_above(obj):
|
||||||
|
#upper player
|
||||||
|
all_instances=pygame.sprite.RenderUpdates();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha)
|
||||||
|
player_above.all_instances.add(self);
|
||||||
|
|
||||||
|
class obj_static(obj):
|
||||||
|
#objects like obstacles and spikes
|
||||||
|
#They have to be drawn only once i.e. at the start of the game when the level is loaded
|
||||||
|
#So, they don't have any draw or update method,but a destroy method when it clears the background it
|
||||||
|
#was covering with appropiate colour fill...
|
||||||
|
all_instances=pygame.sprite.Group();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha);
|
||||||
|
obj_static.all_instances.add(self);
|
||||||
|
|
||||||
|
def destroy(self):
|
||||||
|
self.kill(); #internal method to remove it from all groups
|
||||||
|
#temp_surf=None;
|
||||||
|
#temp_surf=pygame.Surface(self.image.get_width(),self.image.get_width());
|
||||||
|
#temp_surf.fill(get_colour(self.x,self.y));#get_colour to be implemented, returns appropiate colour- white or bloack depending upon position
|
||||||
|
temp_rect=self.image.get_rect(center=(self.x,self.y));
|
||||||
|
surf.fill(self.get_colour(),rect=temp_rect);#fill the area with appropiate colour
|
||||||
|
#get_colour to be implemented, returns appropiate colour- white or bloack depending upon position
|
||||||
|
pygame.display.update(temp_rect);#update that part of the screen only.
|
||||||
|
del temp_rect;
|
||||||
|
def get_colour(self):
|
||||||
|
return pygame.Color(255,255,255);#returns white colour, to be implemented later.
|
||||||
|
|
||||||
|
|
||||||
|
a1=player_down(surf.get_width()/2,surf.get_height()/2,"a.png",alpha=1)
|
||||||
|
a1.hspeed=1;
|
||||||
|
a2=player_above(100,100,"a.png",alpha=1)
|
||||||
|
a2.vspeed=1
|
||||||
|
b=obj_static(300,300,"a.png",alpha=1);
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# all imports
|
||||||
|
import math;
|
||||||
|
import pygame;
|
||||||
|
from pygame.locals import *
|
||||||
|
import sys
|
||||||
|
|
||||||
|
# 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(a,self).__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:
|
||||||
|
sys.exit();
|
||||||
|
|
||||||
|
# c.tick();
|
||||||
|
#pygame.display.set_caption(str(c.get_fps()));
|
||||||
|
#pygame.display.update();
|
||||||
|
|
||||||
|
a.all_instances.update();
|
||||||
|
for b in a.all_instances.sprites():
|
||||||
|
if b.x>=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---------------------------------------------------#
|
||||||
@@ -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()<surf.get_width():
|
||||||
|
b.update()
|
||||||
|
else:
|
||||||
|
a.all_instances.remove(b);
|
||||||
|
print(12)'''
|
||||||
|
|
||||||
|
#pygame.display.update(a.all_instances.draw(surf));
|
||||||
|
#Events here
|
||||||
|
#--------------------------------------------------------- end---------------------------------------------------#
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
# 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()):
|
||||||
|
temp.update();
|
||||||
|
else:
|
||||||
|
group_name.remove(temp);
|
||||||
|
|
||||||
|
# creating new classes
|
||||||
|
class player(obj):
|
||||||
|
all_instances=pygame.sprite.RenderUpdates();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha)
|
||||||
|
player.all_instances.add(self);
|
||||||
|
|
||||||
|
|
||||||
|
a1=player(surf.get_width()/2,surf.get_height()/2,"a.png",alpha=1)
|
||||||
|
a1.vspeed=.1;
|
||||||
|
a2=player(100,100,"a.png",alpha=1)
|
||||||
|
# game startup code
|
||||||
|
c=pygame.time.Clock();
|
||||||
|
#pygame.display.update()
|
||||||
|
pygame.display.update(surf.fill((0,0,0)))
|
||||||
|
# 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()));
|
||||||
|
update_inside(player.all_instances);
|
||||||
|
player.all_instances.clear(surf,pygame.Surface((400,400)))
|
||||||
|
pygame.display.update(player.all_instances.draw(surf));
|
||||||
|
#Events here
|
||||||
|
#--------------------------------------------------------- end---------------------------------------------------#
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# all imports
|
||||||
|
import math;
|
||||||
|
import pygame;
|
||||||
|
from pygame.locals import *
|
||||||
|
from class_definition import *
|
||||||
|
|
||||||
|
# game startup code
|
||||||
|
c=pygame.time.Clock();
|
||||||
|
|
||||||
|
#pygame.display.update()
|
||||||
|
pygame.display.update(surf.fill((0,0,0)))
|
||||||
|
|
||||||
|
# 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()));
|
||||||
|
update_inside(player.all_instances);
|
||||||
|
player.all_instances.clear(surf,pygame.Surface((400,400)))
|
||||||
|
pygame.display.update(player.all_instances.draw(surf));
|
||||||
|
#Events here
|
||||||
|
#--------------------------------------------------------- end---------------------------------------------------#
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# all imports
|
||||||
|
import math;
|
||||||
|
import pygame;
|
||||||
|
from pygame.locals import *
|
||||||
|
from class_definition import *
|
||||||
|
#from class_definition import player_down
|
||||||
|
|
||||||
|
# game startup code
|
||||||
|
c=pygame.time.Clock();
|
||||||
|
|
||||||
|
#pygame.display.update()
|
||||||
|
pygame.display.update(surf.fill((55,55,55)))
|
||||||
|
steps=0;
|
||||||
|
# main game loop
|
||||||
|
while True:
|
||||||
|
# event check
|
||||||
|
for event in pygame.event.get():
|
||||||
|
if event.type == QUIT:
|
||||||
|
exit();
|
||||||
|
|
||||||
|
c.tick(30);
|
||||||
|
steps+=1;
|
||||||
|
if steps==4000:
|
||||||
|
b.destroy();
|
||||||
|
pygame.display.set_caption(str(c.get_fps()));
|
||||||
|
update_inside(player_down.all_instances);
|
||||||
|
update_inside(player_above.all_instances);
|
||||||
|
|
||||||
|
# code to clear both player_down and player_above
|
||||||
|
if player_down.all_instances:
|
||||||
|
temp_instance=(player_down.all_instances.sprites())[0];
|
||||||
|
temp_surf=None;
|
||||||
|
temp_surf=pygame.Surface((temp_instance.image.get_width(),temp_instance.image.get_height()));
|
||||||
|
temp_surf.fill(pygame.Color(255,0,0));
|
||||||
|
print(1)
|
||||||
|
player_down.all_instances.clear(surf,temp_surf);
|
||||||
|
del temp_surf;
|
||||||
|
|
||||||
|
if player_above.all_instances:
|
||||||
|
temp_instance=(player_above.all_instances.sprites())[0];
|
||||||
|
temp_surf=None;
|
||||||
|
temp_surf=pygame.Surface((temp_instance.image.get_width(),temp_instance.image.get_height()));
|
||||||
|
temp_surf.fill(pygame.Color(0,255,255));
|
||||||
|
print(2)
|
||||||
|
player_above.all_instances.clear(surf,temp_surf);
|
||||||
|
del temp_surf;
|
||||||
|
#"clear code" done
|
||||||
|
a=player_down.all_instances.draw(surf)
|
||||||
|
b=player_above.all_instances.draw(surf)
|
||||||
|
print(a)
|
||||||
|
print(b)
|
||||||
|
pygame.display.update();
|
||||||
|
#pygame.display.update(b);
|
||||||
|
#Events here
|
||||||
|
#--------------------------------------------------------- end---------------------------------------------------#
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
# 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().__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();
|
||||||
|
|
||||||
|
# as it is a derived class of Sprite, it can be directly added to gr group
|
||||||
|
#obj.all_obj_derived.add(super());
|
||||||
|
|
||||||
|
|
||||||
|
#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;
|
||||||
|
|
||||||
|
# creating new classes
|
||||||
|
class a(obj):
|
||||||
|
all=pygame.sprite.Group();
|
||||||
|
def __init__(self,x,y,sprite_filename,alpha=None):
|
||||||
|
super().__init__(x,y,sprite_filename,alpha=None)
|
||||||
|
a.all.add(self);
|
||||||
|
wow=True;
|
||||||
|
|
||||||
|
class b(obj):
|
||||||
|
wow=False;
|
||||||
|
|
||||||
|
a1=a(0,0,"a.png")
|
||||||
|
a2=b(0,0,"a.png")
|
||||||
|
# game startup code
|
||||||
|
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()));
|
||||||
|
pygame.display.update();
|
||||||
|
|
||||||
|
#Events here
|
||||||
|
#--------------------------------------------------------- end---------------------------------------------------#
|
||||||
|
After Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,9 @@
|
|||||||
|
#ToDo A small app to create required rect, circle or mask
|
||||||
|
#ToDo Download a animated gif to joined images creator and code to control the animation
|
||||||
|
#ToDo Create the first platformer with crouch-able ball
|
||||||
|
#ToDo Mix and match rect and circle (lower part rect, upper circle)
|
||||||
|
#ToDo Sprite parts mix-and-match generator to create customizable avatars (Allow logic if possible)
|
||||||
|
#ToDo Take a changing background and make a blur effect at both right and left (use pygame.transform.average_color())
|
||||||
|
#ToDo keep track of all derived objects, superclass to take care of subclass group
|
||||||
|
#ToDo1 Do your own blit
|
||||||
|
Note: Don't use get_fps from first(gives zero division error)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"hi, there ",509,"[89, 25]"␍
|
||||||
|
Can't render this file because it contains an unexpected character in line 1 and column 27.
|
@@ -0,0 +1,73 @@
|
|||||||
|
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=50 # 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+img.width/2
|
||||||
|
self.ori_y=ori_y+img.height/2
|
||||||
|
self.x=float(start_x)
|
||||||
|
self.y=float(start_y)
|
||||||
|
self.angle=s.math.atan2(-(self.ori_y-self.y),(self.ori_x-self.x))
|
||||||
|
self.dist=distance((self.ori_x,self.ori_y),(self.x,self.y)) #float
|
||||||
|
self.accln=2*self.dist/float((total_time**2))
|
||||||
|
#print(self.dist*2/(self.accln*(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)<w/2:
|
||||||
|
## self.x=w/2
|
||||||
|
## if round(self.y)<h/2:
|
||||||
|
## self.y=h/2
|
||||||
|
## 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)
|
||||||
@@ -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)<w/2:
|
||||||
|
## self.x=w/2
|
||||||
|
## if round(self.y)<h/2:
|
||||||
|
## self.y=h/2
|
||||||
|
## 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)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
class class_a():
|
||||||
|
def __init__(self):
|
||||||
|
print(math.cos(0))
|
||||||
|
After Width: | Height: | Size: 3.9 KiB |
@@ -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)
|
||||||
@@ -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---------------------------------------------------#
|
||||||
@@ -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<least:
|
||||||
|
#print(diff)
|
||||||
|
#print(c_)
|
||||||
|
color=c_
|
||||||
|
least=diff
|
||||||
|
#print(color)
|
||||||
|
color=s.Color.hueToRGB(color)
|
||||||
|
#print(color)
|
||||||
|
|
||||||
|
color_name=w.rgb_to_name(color)
|
||||||
|
#print(color_name)
|
||||||
|
#print("9: "+str(1/(time.clock()-clock1)))
|
||||||
|
img.drawLine([bot.x,bot.y],hole_center,s.Color.AQUAMARINE,thickness=5)
|
||||||
|
|
||||||
|
#minimum angle between ball_angle and bot_angle
|
||||||
|
# returns positive angle for anti-clockwise rotation and else negative angle
|
||||||
|
diff_angle = ball_angle-bot_angle
|
||||||
|
diff_angle = (diff_angle + 180) % 360 - 180
|
||||||
|
print(diff_angle)
|
||||||
|
|
||||||
|
#send_signal(diff_angle)
|
||||||
|
#print("10: "+str(1/(time.clock()-clock1)))
|
||||||
|
img.show()
|
||||||
|
|
||||||
|
def send_signal(diff_angle):
|
||||||
|
basic=120
|
||||||
|
total=255
|
||||||
|
mod_angle=abs(diff_angle)
|
||||||
|
sign=diff_angle/mod_angle
|
||||||
|
val=str(sign*(float(mod_angle)/360*(total-basic)+basic))
|
||||||
|
print("Sending: "+val)
|
||||||
|
serial_setup.ser.write(val)
|
||||||
|
|
||||||
|
# Actual code
|
||||||
|
while True:
|
||||||
|
loop()
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
|
||||||
|
a=[5]
|
||||||
|
import practise
|
||||||
|
##for k in globals():
|
||||||
|
## if not k.startswith("__"):
|
||||||
|
## practise.globals()[k]=globals()[k]
|
||||||
|
C=practise.c(globals())
|
||||||
|
print C.pp()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from SimpleCV import Camera, Display, Image;
|
||||||
|
cam=Camera();
|
||||||
|
disp=Display();
|
||||||
|
img=cam.getImage();
|
||||||
|
img.sample_points(disp);
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import SimpleCV as s
|
||||||
|
import time
|
||||||
|
c=s.JpegStreamCamera(r"192.168.173.169:8080/videofeed")
|
||||||
|
c1=time.clock()
|
||||||
|
gesture_time=60
|
||||||
|
detection_sleep=False
|
||||||
|
blobs=[None]*gesture_time
|
||||||
|
#d=s.Display()
|
||||||
|
i1=c.getImage()
|
||||||
|
img_width=i1.width
|
||||||
|
img_height=i1.height
|
||||||
|
i1=i1.crop(0,0,img_width,img_height/2).flipHorizontal()
|
||||||
|
count=0
|
||||||
|
while True:
|
||||||
|
i2=c.getImage().crop(0,0,img_width,img_height/2).flipHorizontal()
|
||||||
|
i3=(i2-i1)+(i1-i2)
|
||||||
|
i1=i2
|
||||||
|
## i3=i3.erode(7).dilate(7).binarize()
|
||||||
|
## i3=i3.invert()
|
||||||
|
## f=i3.findBlobs(minsize=35)
|
||||||
|
## if f:
|
||||||
|
## totalSum=0
|
||||||
|
## areaSum=0
|
||||||
|
## for temp in f:
|
||||||
|
## areaSum+=temp.area()
|
||||||
|
## totalSum+=temp.area()*temp.x
|
||||||
|
## if areaSum!=0:
|
||||||
|
## avgX=totalSum/areaSum
|
||||||
|
## i3.drawText(text="Avg. X="+str(avgX),x=avgX,color=s.Color.AQUAMARINE)
|
||||||
|
## f.draw(width=3)
|
||||||
|
## else:
|
||||||
|
## print("None")
|
||||||
|
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.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()
|
||||||
@@ -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
|
||||||
@@ -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()
|
||||||
|
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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")),
|
||||||
|
)
|
||||||
@@ -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)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from django.contrib import admin
|
||||||
|
from poll.models import Poll
|
||||||
|
admin.site.register(Poll)
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
s = r"print 's = r\"' + s + '\"' + '\nexec(s)'"
|
||||||
|
exec(s)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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<poll_id>\d+)/$", views.detail, name="detail"),
|
||||||
|
url(r"^(?P<poll_id>\d+)/details?/$", views.detail, name="detail"),
|
||||||
|
# ex: /polls/5/results/
|
||||||
|
url(r"^(?P<poll_id>\d+)/results/$", views.results, name="results"),
|
||||||
|
# ex: /polls/5/vote/
|
||||||
|
url(r"^(?P<poll_id>\d+)/vote/$", views.vote, name="vote"),
|
||||||
|
)
|
||||||
@@ -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)
|
||||||
|
|
||||||
|
|
||||||
@@ -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)
|
||||||
|
|
||||||
@@ -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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Create your views here.
|
||||||
|
After Width: | Height: | Size: 1.2 MiB |
@@ -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)
|
||||||
@@ -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()
|
||||||
|
After Width: | Height: | Size: 89 KiB |
|
After Width: | Height: | Size: 11 KiB |
|
After Width: | Height: | Size: 2.1 KiB |
|
After Width: | Height: | Size: 9.5 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
|
After Width: | Height: | Size: 6.3 KiB |
|
After Width: | Height: | Size: 7.2 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
|
After Width: | Height: | Size: 6.1 KiB |
|
After Width: | Height: | Size: 3.3 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 8.3 KiB |
|
After Width: | Height: | Size: 9.3 KiB |
@@ -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"
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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.
|
||||||
@@ -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()
|
||||||
@@ -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
|
||||||
@@ -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();
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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()
|
||||||
@@ -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.
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -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();
|
||||||
@@ -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))
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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_<event_name>: action_<event_name>
|
||||||
|
|
||||||
|
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_<event>
|
||||||
|
# what they do: if event_<event_name>: action_<event_name>
|
||||||
|
# so lets define event_<event_name>,action_<event_name>,check_<event_name> for each <event_name>
|
||||||
|
|
||||||
|
# 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 )<self.radius
|
||||||
|
|
||||||
|
def is_inside_mutual(self,another_circle):
|
||||||
|
''' Checks if this circle is fully inside another_circle and also the opposite.
|
||||||
|
2x Faster than using is_inside for both of them. '''
|
||||||
|
return (distance( self.center, another_circle.center ) < max( self.radius, another_circle.radius) )
|
||||||
|
|
||||||
|
def collide_circle(self,another_circle):
|
||||||
|
''' Checks if this circle intersects with another_circle. '''
|
||||||
|
return (distance( self.center, another_circle.center ) <= (self.radius + another_circle.radius) )
|
||||||
|
|
||||||
|
def collide_point(self, (point_x, point_y)):
|
||||||
|
''' Checks if (point_x, point_y) is inside this circle. '''
|
||||||
|
return (distance(self.center, (point_x,point_y) ) <= self.radius )
|
||||||
|
|
||||||
|
def collide_list_circle(self, list_circle):
|
||||||
|
''' Checks if this circle intersects with any of the circles in circle_list. '''
|
||||||
|
for circle in list_circle:
|
||||||
|
if collide_circle(self,circle):
|
||||||
|
return True
|
||||||
|
else: #else of the for loop
|
||||||
|
return False
|
||||||
|
|
||||||
|
def collide_list_all_circle(self,list_circle):
|
||||||
|
''' Checks if this circle intersects with all of the circles in circle_list. '''
|
||||||
|
for circle in list_circle:
|
||||||
|
if not collide_circle(self,circle):
|
||||||
|
return False
|
||||||
|
else: #else of the for loop
|
||||||
|
return True
|
||||||
|
|
||||||
|
def collide_rect(self,another_rect):
|
||||||
|
''' Checks if this circle collides with another_rect. '''
|
||||||
|
return not ( (self.center_x+self.radius)<another_rect.left or (self.center_x-self.radius)>another_rect.right or (self.center_y+self.radius)<another_rect.top 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
|
||||||
@@ -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()
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
def a(self):
|
||||||
|
print self
|
||||||
|
|
||||||
|
class b():
|
||||||
|
def a(self):
|
||||||
|
a(self)
|
||||||