Example #1
0
 def on_mouse_button_down(self, pos, button): 
     if button==3:
         self.blockedkeys=False
     if button==1:
         if self.intervallo_mouse:
             self.mousenow=time.time()
             if 'arco' in self.mag.selezionabili:
                 if self.mag.selezionabili['arco']:
                     utensile=Proiettile(self,pos)
             if 'lasso' in self.mag.selezionabili:
                 if self.mag.selezionabili['lasso']:
                     utensile=Proiettile(self,pos)
             if 'spada' in self.mag.selezionabili:
                 if self.mag.selezionabili['spada']:
                     utensile=UtensileSpada(self,pos)
             if 'piccone' in self.mag.selezionabili:
                 if self.mag.selezionabili['piccone']:
                     utensile=UtensilePiccone(self,pos)
             if 'mappa' in self.mag.selezionabili:
                 if self.mag.selezionabili['mappa']:
                     pgu=PguApp(self,inizio="mappa")
             if 'utensile' in locals():
                 utensile.mostra()
             else:
                 if not 'pgu' in locals():
                     dialog = DialogoAvvisi(testo="Seleziona un'arma o uno strumento da usare! (tasto T) (tasto H)")
Example #2
0
def _processButtonsArray(buttons):
    buttonOrds = []

    if not isinstance(buttons, list):
        buttons = [buttons]

    for button in buttons:
        if isinstance(button, int):
            buttonOrds.append(button)
        elif button in locals() and isinstance(locals()[button], int):
            buttonOrds.append(locals()[button])
        else:
            print("Attempted to bind function with activation button: %s, but could not fine a way to convert to a button ord." % button)

    return set(buttonOrds)
Example #3
0
    def _redraw(self):

        # draw the background image
        bg = self.screen.blit(self.credits_bg, (self.bg_x_pos, 0))

        # blit the continuation of the background image
        if self.bg_x_pos < - (self.credits_bg.get_width() -
                              self.screen.get_width()):

            bg_cont = self.screen.blit(self.credits_bg, (self.bg_x_pos +
                             self.credits_bg.get_width(), 0))

        # draw each text item
        [item.redraw() for item in self.text_items]

        # draw the frame of the window
        fr = self.screen.blit(self.window_frame, (0, 0))

        # pass bg_cont only if defined
        if 'bg_cont' in locals():
            need_update = (bg, bg_cont, fr)
        else:
            need_update = (bg, fr)

        return need_update
Example #4
0
def info():
    form=FORM(TABLE(TR("Codification souche:",INPUT(_type="text",_name="souche",value="None",requires=IS_NOT_EMPTY())),
                    TR("Substrat:",INPUT(_type="text",_name="substrat",value="None",requires=IS_NOT_EMPTY())),
                    TR("Durée de fermentation:",INPUT(_type="text",_name="fermentation",value="10",requires=IS_INT_IN_RANGE(0, 9999))),
                    TR("Interval de temps entre deux photos:",INPUT(_type="text",_name="interval",value="4",requires=IS_INT_IN_RANGE(0, 20))),
                    TR("Commentaires",TEXTAREA(_name="Commentaire",value="Commentaire ici")),
                    TR("",INPUT(_type="submit",_value="SUBMIT"))))
    

    
    if form.accepts(request,session):
        response.flash="Formulaire accepté"
        souche = str(request.vars.souche)
        substrat = str(request.vars.substrat)
        fermentation = str(request.vars.fermentation)
        interval = str(request.vars.interval)
        cx.set('souche', souche)
        cx.set('substrat', substrat)
        cx.set('fermentation', fermentation)
        cx.set('interval', interval)
        #redirect(URL(request.application, 'capture', 'capture'))
        
        return locals()
    elif form.errors:
        response.flash="Formulaire invalide"
    else:
        response.flash="Remplissez le formulaire"
    return dict(form=form)
 def __init__(self, cascade_path, camera=None, haar_flags=None,
         haar_scale=None, min_neighbours=None, min_size=None, scale=None):
     super(FaceDetector, self).__init__()
     set_defaults(self, locals())
     self.cascade = cv.Load(self.cascade_path)
     self.capture = cv.CreateCameraCapture(self.camera)
     print(self.min_size)
 def __init__(self, location, same=None):
     super(FaceTracker, self).__init__()
     set_defaults(self, locals())
     self.num = FaceTracker.next_num
     FaceTracker.next_num += 1
     self.tracked = True
     self.frames = 1
Example #7
0
 def goto(self,name,value=None):
     if type(name) != str:
         self._goto = name
         return
     if value == None:
         value = self.name
     r = __import__('rooms.%s'%name,globals(),locals(),['Room'])
     self._goto = r.Room(self.game,value)
Example #8
0
File: 2048.py Project: akko963/2048
def gameEND(reached=False):
    animateCounter=25
    posx,posy = 0,0
    closing = pygame.Surface((_MAX,_MAX+_STARTY))  # the size of your rect

    End_msg="Game Over!" if not reached else "You Won!"
    End_msgSurfaceObj = fontObj.render(End_msg,True,granite)
    End_msgRectobj = End_msgSurfaceObj.get_rect()
    End_msgRectobj.center = (_BLOCK_SIZE*2,_BLOCK_SIZE*2)

    Try_msg= "Try Again?"  if not reached else "Continue!"
    Try_msgSurfaceObj = fontObjbox1.render(Try_msg,True,whiteColor)
    Try_msgRectobj = Try_msgSurfaceObj.get_rect()
    Try_msgRectobj.center = End_msgRectobj.move(-_BLOCK_SIZE//2,60).center
    Quit_msg= "Quit"
    Quit_msgSurfaceObj = fontObjbox1.render(Quit_msg,True,whiteColor)
    Quit_msgRectobj = Quit_msgSurfaceObj.get_rect()
    Quit_msgRectobj.center = End_msgRectobj.move(_BLOCK_SIZE,60).center
    if 'fading' not in locals():
        fading = 0  # completely transparent
    while True:
        drawBG(locked,Total)
        if fading <140: fading+=5
        closing.set_alpha(fading)                # alpha level
        closing.fill(lighterblue)               # this fills the entire surface
        windowSurfaceObj.blit(closing, (0,0))    #draw the semi-transparent surface to main surface.
        windowSurfaceObj.blit(End_msgSurfaceObj,End_msgRectobj)
        QuitRect=pygame.draw.rect(windowSurfaceObj,granite,Quit_msgRectobj,0)
        windowSurfaceObj.fill(granite,QuitRect.inflate(15,15))
        windowSurfaceObj.blit(Quit_msgSurfaceObj,Quit_msgRectobj)

        TryRect=pygame.draw.rect(windowSurfaceObj,granite,Try_msgRectobj,0)
        windowSurfaceObj.fill(granite,TryRect.inflate(15,15))
        windowSurfaceObj.blit(Try_msgSurfaceObj,Try_msgRectobj)

        for event in pygame.event.get():
            if event.type == pygame.MOUSEMOTION:
                posx, posy= event.pos
                #soundObj.play()
            elif event.type == pygame.QUIT:
                pygame.event.post(pygame.event.Event(pygame.QUIT))
                _GameOver= True
                return True
            elif  event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                pygame.event.post(pygame.event.Event(pygame.QUIT))
                _GameOver= True
                return True
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                if Try_msgRectobj.collidepoint((posx, posy)):  #Trying again
                    _GameOver=False
                    return False
                elif Quit_msgRectobj.collidepoint((posx, posy)):
                    pygame.event.post(pygame.event.Event(pygame.QUIT))
                    _GameOver= True
                    return True
        pygame.display.update()
        fpsClock.tick(60)
    return True
Example #9
0
	def example_from_string(self, example_name):
		import inspect


		package_name, class_name = example_name.rsplit('.', 1)
		package = __import__(package_name, globals(), locals(), [class_name], 1)

		cls = next((c[1] for c in inspect.getmembers(package, inspect.isclass) if c[0] == class_name))

		return cls(self)
Example #10
0
 def __init__(self, damage = 1):
     self.name = 'bullet'
     self.__dict__.update(locals())
     self.ship_bullet = pygame.image.load('img/bullet_1.png')
     self.distance = 60
     self.range = 0
     self.delete_me = False
     self.bullet_final = self.ship_bullet
     self.damage = damage
     self.rect = self.ship_bullet.get_rect()
     self.hitmask = get_alpha_hitmask(self.ship_bullet, self.rect)
Example #11
0
 def ContextMainLoop( cls, *args, **named ):
     """Initialise the context and start the mainloop"""
     instance = cls( *args, **named )
     if instance.contextDefinition.profileFile:
         # profiling run...
         import cProfile
         return cProfile.runctx(
             "instance.MainLoop()",
             globals(),
             locals(),
             instance.contextDefinition.profileFile
         )
     return instance.MainLoop()
Example #12
0
 def debugcmd(self):
     command = self.debug_console.text
     debug('DEBUG CONSOLE: ', command)
     self.debug_console.text = ''
     try:
         code_locals = locals()
         code_locals.update({'player': self.frontend.game.player, 'game': self.frontend.game, 'frontend':self.frontend, 'messages': self.messages})
         code_globals = globals()
         exec command in code_globals, code_locals
     except Exception as E:
         self.messages.message('')
         self.messages.error('Error executing command: '+str(E))
         self.messages.message('')
Example #13
0
    def __init__(self):
        gui.Container.__init__(self)
        #self.cls = "desktop"
        #self.background = gui.Box(self.style.background)

        self.screen_w = cfg['screen_w']
        self.screen_h = cfg['screen_h']
        self.screen = pygame.display.set_mode((self.screen_w,
            self.screen_h), SWSURFACE)

        self.fname = cfg['fname']
        
        k = cfg['class']
        parts = k.split(".")
        n = ".".join(parts[:-1])
        m = __import__(n,globals(),locals(),parts[-1])
        c = getattr(m,parts[-1])
        self.level = c()

        #self.level = pygame.image.load(self.level_fname)
        #self.level = tilevid.Tilevid()
        #g = self.level = isovid.Isovid()
        
    
        if self.fname != None:
            self.level.tga_load_level(self.fname,1)
        else:
            self.level.resize((cfg['width'],cfg['height']),1)
        #self.level_w, self.level_h = (self.level.get_width(), self.level.get_height())
        self.level_w, self.level_h = len(self.level.tlayer[0]),len(self.level.tlayer)

        self.tiles_last_ctime = None
        self.codes_last_ctime = None

        self.load_tiles_and_codes()
        



        
        
        self.tile = 0
        self.code = 0
        
        self.mode = 'tile'
        self.clipboard = None
        self.history = []
        #self.modrect = pygame.Rect(0xffff,0xffff,-0xffff,-0xffff)
        
        self.changes = []
        self.dirty = 0
Example #14
0
    def load_layers(self, layers):
        self.layers_modules = {}

        for name, params in layers:
            # import the layer module
            # (equivalent to "from layers.<name> import main")
            module = __import__('layers.%s' % name, globals(), locals(),
                                ['main'], -1)
            main = getattr(module, 'main')

            if hasattr(main, 'init'):
                main.init(**params)

            self.layers_modules[name] = main
def keyboard_init():
    keys = pygame.key.get_pressed()
    K_a = 113
    K_z = 119
    K_m = 59
    K_q = 97
    K_w = 122
    K_l = 108
    K_COMMA = 109
    K_LEFTPAREN = 53
    K_RIGHTPAREN = 45
    K_QUOTEDBL = 51
    K_PERIOD = 44
    K_BACKSLASH = 35
    K_COLON = 46
    globals().update(locals())
Example #16
0
    def heading():

        def fget(self):
            return self._heading

        def fset(self, direction):

            #if self._heading is self.HEADING_EAST and direction is self.HEADING_WEST:
            #    self.image = pygame.transform.flip(self.image, 1, 0)

            #if self._heading is self.HEADING_WEST and direction is self.HEADING_EAST:
            #    self.image = pygame.transform.flip(self.image, 1, 0)

            self._heading = direction

        return property(**locals())
Example #17
0
def Install():

	class Clipper:
		def __init__(self, rect):
			screen = renderer.screen
			self.lastrect = screen.get_clip()
			screen.set_clip(rect)
		def __del__(self):
			renderer.screen.set_clip(self.lastrect)

	videoFlags = DOUBLEBUF

	def Resize(resolution):
		renderer.screen = pygame.display.set_mode(resolution
												,renderer.videoFlags)

	def Render(draw=lambda:None):
		renderer.screen.fill(renderer.fillColor)
		draw()
		pygame.display.flip()

	def FillRect(rect):
		renderer.screen.fill(renderer.color, rect)

	def Color(r, g, b, a=1.0):
		return renderer.ScaleNormalToInteger((r,g,b))

	def SetColor(color):
		renderer.color = color

	class Image(object):
		__slots__ = ["surf", "area"]
		def __init__(self, shader, area=None):
			self.surf = shader
			if area is None:
				area = shader.get_rect()
			self.area = area
		def Draw(self, pos):
			renderer.screen.blit(self.surf, pos, self.area)

	def LoadImage(pathname, colorKey=None, area=None):
		return Image(Surface(pathname, colorKey), area)

	renderer.Install(__name__, **locals())
Example #18
0
def input(events, quit_pos):
    
    try:
        for event in events: 
            if event.type == QUIT: 
                sys.exit(0) 
            elif event.type == KEYDOWN or event.type == MOUSEBUTTONDOWN:
                #print "eepos: %s" % (quit_pos)
                
                if event.type == KEYDOWN:
                    if event.key == K_q:
                        quit_pos = 1
                    elif ((event.key == K_u) and (quit_pos == 1)):
                        quit_pos = 2
                    elif event.key == K_i and quit_pos == 2:
                        quit_pos = 3
                    elif event.key == K_t and quit_pos == 3:
                        quit_pos = 4
                    else:
                        quit_pos = 0

                # Clear the background 5% of the time
                if random.randint(0, 20) == 1:
                    screen.blit(background, (0, 0))
                    pygame.display.flip()
                sound = sounds[random.randint(0, len(sounds) -1)]

                if sound.get_length() > 10:
                    if pygame.mixer.get_busy() == 0:
                        sound.play()
                elif pygame.mixer.get_busy() < 3:
                    sound.play()


                if event.type == MOUSEBUTTONDOWN or not(is_alpha(event.key)):
                    print_image()
                else:
                    print_letter(event.key)
                
                pygame.display.flip() 
        return quit_pos
    except:
        pprint.pprint(locals())
Example #19
0
 def __init__(self, imagedir=CHECKENV,
                    mapdir=CHECKENV,
                    fontdir=CHECKENV,
                    zipFile=None):
     l = locals()
     for path in ("image", "map", "font"):
         if l[path + "dir"] == CHECKENV:
             checkPath = "PGAME_" + path.upper() + "S"
             setattr(self, "%sPath" % path, os.environ[checkPath])
         else:
             setattr(self, "%sPath" % path, l[path + "dir"])
     
     if zipFile:
         try:
             Resources.zipFile = zipfile.ZipFile(zipFile, "rb")
         except RuntimeError:
             return
         
         for item in self.zipFile.infolist():
             self.zipDir[item.filename] = item
Example #20
0
	else: #tem mais sprites na tela? então reseta timer
		latchtimerdown = False
		pygame.time.set_timer(USEREVENT+1, 0) # e reseta timer
	#imprime placar
	placar=placarf.render(u"MÉDIA: {:10.3f}".format(avgresptime) ,True,(30,30,60))
	kanapmplacar = placarf.render(u"仮名 POR MINUTO: " + str(KPM)  ,True,(30,30,60))
        screen.blit(placar,(10,10))
        screen.blit(kanapmplacar,(320,10))
	if pygame.key.get_focused():
	   press=pygame.key.get_pressed()
	   for i in xrange(0,len(press)):
	    if press[i]==1:
	     logging.debug(i)
	     zz = listfind(keystr,i) 	     # cria uma lista com os endereços dos locais onde achou o i dentro de keystr
	     if len(zz)==0:		#não achou nenhuma ocorrência
		if 'lasterror' in locals(): # checa se variável já existe para evitar logar coisas repetidas
			if not lasterror == i:
				logging.info("To key num. " + str(i) + " no kana box is assigned.")
		else:
			logging.info("To key num. " + str(i) + " no kana box is assigned.")
		lasterror=i
	     else:
		for kkk in xrange(0,len(zz)):		#se em o press gerar um zz com mais de uma remoção, faz um for pra remover tudo.
			z = zz[kkk]
		     	boxtoditch = z[0]*12+z[1]
			logging.debug("z: " + str(z) + "  keynumber from pygame.key.get_pressed():" + str(i) + "  order on boxes list: " + str(boxtoditch))
			# zera timer, integra tempo, calcula média de tempo de reação
			#as vezes os timers enlouquecem. não sei porque
			# insisti no meu erro e simplesmente colocar um latch aqui; na verdade não é bem um latch, vou testar se o sprite existe, no fim dá no mesmo
			#print "i wanto to remove", boxtoditch
			if boxtoditch in allSprites.kanalindex: 
Example #21
0
    #ser = serial.Serial("COM9", 9600)
    #time.sleep(2)

    ctr = 0

    #Loop until the user clicks the close button.
    done = False

    # -------- Main Program Loop -----------
    while not done:
        pygame.time.wait(1)

        ctr += 1
        if ctr > 200:
            heatList = getHeat()
            if 'ser' in locals():
                updateLEDs(heatList)
            ctr = 0

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()


            elif event.type == pygame.JOYBUTTONDOWN:
                if 0 <= event.button and event.button <=7:
                    coolantup(event.button)

                elif 8 <= event.button and event.button <= 15:
                    coolantdown(event.button - 8)
Example #22
0
 def log(self, action, hex=None):
     if quiet:
         return
         
     if self.state:
         state = self.state.name
     else:
         state = None
     pid = "P%s" % self.current_player.id
     turn = "T%s" % self.turn
     if hex:
         xy = "(%s,%s)" % (hex.x, hex.y)
     else:
         xy = "-"
     elapsed = time.time()-self.log_start_time
     print("[%(elapsed)7.2f] %(xy)7s : [ %(state)-12s %(turn)4s  %(pid)s] %(action)s" % locals())
Example #23
0
def Install():

	class Clipper:
		current = None
		def __init__(self, rect):
			x,y,w,h = rect
			y = renderer.screen.get_height()-(y+h)
			if self.current is None:
				glEnable(GL_SCISSOR_TEST)
			self.lastrect = self.current
			glScissor(x,y,w,h)
			self.__class__.current = (x,y,w,h)
		def __del__(self):
			if self.lastrect is None:
				glDisable(GL_SCISSOR_TEST)
			else:
				glScissor(*self.lastrect)
			self.__class__.current = self.lastrect

	videoFlags = OPENGL|DOUBLEBUF

	def Resize(resolution, zdepth=10.0):
		renderer.screen = pygame.display.set_mode(resolution
												,renderer.videoFlags)
		SetViewport(resolution)

	def SetViewport(resolution):
		width,height = resolution
		if height == 0:
			height = 1
		glViewport(0, 0, width, height)
		SetProjection(resolution, zdepth)
		Initialize()

	def SetProjection(resolution, zdepth):
		width,height = resolution
		if height == 0:
			height = 1
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		glOrtho(0.0, width, height, 0.0, 0.0, zdepth)
		glMatrixMode(GL_MODELVIEW)

	def SetClearColor():
		glClearColor(*renderer.fillColor)
		glClearDepth(1.0)

	def SetDepthTest():	# a lot of this stuff will be meant for the GUI mode
		glEnable(GL_DEPTH_TEST)
		glDepthFunc(GL_LEQUAL)

	def Initialize():
		# a lot of this stuff won't actually be on by default
		glLoadIdentity()
		glEnable(GL_TEXTURE_2D)	##
		glShadeModel(GL_SMOOTH)	##
		SetClearColor()
		SetDepthTest()
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)	##
	#	glEnable(GL_ALPHA_TEST)
	#	glAlphaFunc(GL_GREATER, 0.0)
#		glEnable(GL_BLEND)
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # transparency blend
		texture.Reload()

	def Render(draw=lambda:None):
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
		draw()
		pygame.display.flip()

	def FillRect(rect):
		x,y,w,h = rect
		glRecti(x,y,x+w,y+h)
	
	def CorrectedY(y, h):
		return renderer.screen.get_height()-(y+h)

	SetColor = glColor4fv

	Image = texture.Image

	LoadImage = texture.LoadImage

	Font = imagefont.LoadImageFont

	renderer.Install(__name__, **locals())
Example #24
0
    def run(self, arm, control_shell, video=None, video_time=None):

        self.arm = arm
        self.shell = control_shell

        # load arm images 
        arm1 = ArmPart('img/three_link/svgupperarm2.png', 
                        scale = .7)
        arm2 = ArmPart('img/three_link/svgforearm2.png', 
                        scale = .8)
        arm3 = ArmPart('img/three_link/svghand2.png', 
                        scale= 1)

        scaling_term = np.ones(2) * 105
        upperarm_length = self.arm.L[0] * scaling_term[0]
        forearm_length = self.arm.L[1] * scaling_term[0]
        hand_length = self.arm.L[2] * scaling_term[0]
        line_width = .15 * scaling_term[0]

        # create transparent arm lines
        line_upperarm_base = pygame.Surface((upperarm_length, line_width),
                pygame.SRCALPHA, 32)
        line_forearm_base = pygame.Surface((forearm_length, line_width),
                pygame.SRCALPHA, 32)
        line_hand_base = pygame.Surface((hand_length, line_width),
                pygame.SRCALPHA, 32)

        white = (255, 255, 255)
        red = (255, 0, 0)
        black = (0, 0, 0)
        arm_color = (75, 75, 75)
        line_color = (50, 50, 50, 200) # fourth value is transparency

        # color in transparent arm lines
        line_upperarm_base.fill(line_color)
        line_forearm_base.fill(line_color)
        line_hand_base.fill(line_color)

        fps = 20 # frames per second
        fpsClock = pygame.time.Clock()

        # constants for magnify plotting
        magnify_scale = 1.75
        magnify_window_size = np.array([200, 200])
        first_target = np.array([321, 330])
        magnify_offset = first_target * magnify_scale - magnify_window_size / 2

        # setup pen trail and appending functions
        self.trail_data = []
        def pen_down1():
            self.pen_lifted = False
            x,y = self.arm.position()
            x = int( x[-1] * scaling_term[0] + self.base_offset[0]) 
            y = int(-y[-1] * scaling_term[1] + self.base_offset[1])
            self.trail_data.append([[x,y],[x,y]])

            self.trail_data[self.trail_index].append(points[3])
            self.pen_down = pen_down2
        def pen_down2():
            self.trail_data[self.trail_index].append(points[3])

        pygame.init()
        self.display = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption(self.title)

        background = pygame.image.load('img/whiteboard.jpg')

        # enter simulation / plotting loop
        while True: 

            self.display.fill(white)

            self.target = self.shell.controller.target * np.array([1, -1]) * \
                            scaling_term + self.base_offset
           
            # before drawing
            for j in range(self.display_steps):            
                # update control signal
                if self.sim_step % self.control_steps == 0 or \
                    'tau' not in locals():
                        tau = self.shell.control(self.arm)
                # apply control signal and simulate
                self.arm.apply_torque(u=tau, dt=self.dt)

                self.sim_step +=1

            # get (x,y) positions of the joints
            x,y = self.arm.position()
            points = [(int(a * scaling_term[0] + self.base_offset[0]), 
                       int(-b * scaling_term[1] + self.base_offset[1])) 
                       for a,b in zip(x,y)]

            arm1_image, arm1_rect = arm1.rotate(self.arm.q[0])
            arm2_image, arm2_rect = arm2.rotate(self.arm.q[1] + arm1.rotation)
            arm3_image, arm3_rect = arm3.rotate(self.arm.q[2] + arm2.rotation)

            # recenter the image locations appropriately
            transform(arm1_rect, points[0], arm1)
            transform(arm2_rect, points[1], arm2)
            transform(arm3_rect, points[2], arm3)
            arm3_rect.center += np.array([np.cos(arm3.rotation),
                                          -np.sin(arm3.rotation)]) * -10

            # transparent upperarm line
            line_upperarm = pygame.transform.rotozoom(line_upperarm_base, np.degrees(arm1.rotation), 1)
            rect_upperarm = line_upperarm.get_rect()
            transform_lines(rect_upperarm, points[0], arm1)

            # transparent forearm line
            line_forearm = pygame.transform.rotozoom(line_forearm_base, np.degrees(arm2.rotation), 1)
            rect_forearm = line_forearm.get_rect()
            transform_lines(rect_forearm, points[1], arm2)

            # transparent hand line
            line_hand = pygame.transform.rotozoom(line_hand_base, np.degrees(arm3.rotation), 1)
            rect_hand = line_hand.get_rect()
            transform_lines(rect_hand, points[2], arm3)

            # update trail
            if self.shell.pen_down is True:
                self.pen_down()
            elif self.shell.pen_down is False and self.pen_lifted is False:
                self.pen_down = pen_down1
                self.pen_lifted = True
                self.trail_index += 1

            # draw things! 
            self.display.blit(background, (0,0)) # draw on the background

            for trail in self.trail_data:
                pygame.draw.aalines(self.display, black, False, trail, True)

            # draw arm images
            self.display.blit(arm1_image, arm1_rect)
            self.display.blit(arm2_image, arm2_rect)
            self.display.blit(arm3_image, arm3_rect)

            # draw original arm lines 
            # pygame.draw.lines(self.display, arm_color, False, points, 18)

            # draw transparent arm lines
            self.display.blit(line_upperarm, rect_upperarm) 
            self.display.blit(line_forearm, rect_forearm)
            self.display.blit(line_hand, rect_hand)

            # draw circles at shoulder
            pygame.draw.circle(self.display, black, points[0], 30)
            pygame.draw.circle(self.display, arm_color, points[0], 12)

            # draw circles at elbow 
            pygame.draw.circle(self.display, black, points[1], 20)
            pygame.draw.circle(self.display, arm_color, points[1], 7)

            # draw circles at wrist
            pygame.draw.circle(self.display, black, points[2], 15)
            pygame.draw.circle(self.display, arm_color, points[2], 5)

            # draw target
            pygame.draw.circle(self.display, red, [int(val) for val in self.target], 10)

            # now display magnification of drawing area
            magnify = pygame.Surface(magnify_window_size)
            magnify.blit(background, (-200,-200)) # draw on the background
            # magnify.fill(white)
            # put a border on it
            pygame.draw.rect(magnify, black, (2.5, 2.5, 195, 195), 1)
            # now we need to rescale the trajectory and targets
            # using the first target position, which I know to be the 
            # desired center of the magnify area
            for trail in self.trail_data:
                pygame.draw.aalines(magnify, black, False, 
                        np.asarray(trail) * magnify_scale - magnify_offset, True)
            pygame.draw.circle(magnify, red, 
                    np.array(self.target * magnify_scale - magnify_offset, 
                        dtype=int), 5)

            # now draw the target and hand line 
            self.display.blit(magnify, (32, 45))

            # check for quit
            for event in pygame.event.get():
                if event.type == pygame.locals.QUIT:
                    pygame.quit()
                    sys.exit()

            pygame.display.update()
            fpsClock.tick(fps)
 def __init__(self, face_tracker, mode=None):
     super(SbFace, self).__init__()
     set_defaults(self, locals())
     self.players = [pygame.image.load(image) for image in
             ('sb.gif', 'p.gif', 's.png', 'k.gif')]
 def __init__(self, face_detector, lag=None, same=None):
     super(MultiFaceTracker, self).__init__()
     set_defaults(self, locals())
     self.faces = []
Example #27
0
print " GL_ACCUM_RED_BITS =",glGetIntegerv( GL_ACCUM_RED_BITS )
print " GL_ACCUM_GREEN_BITS =",glGetIntegerv( GL_ACCUM_GREEN_BITS )
print " GL_ACCUM_BLUE_BITS =",glGetIntegerv( GL_ACCUM_BLUE_BITS )
print " GL_ACCUM_ALPHA_BITS =",glGetIntegerv( GL_ACCUM_ALPHA_BITS )

print

### Test OpenGL extensions

print "Testing PyOpenGL extension support"

for ext in ARB_exts:
    print " GL_ARB_%s:"%ext,
    module_name = "OpenGL.GL.ARB.%s"%ext
    try:
        mod = __import__(module_name,globals(),locals(),[])
        components = string.split(module_name, '.') # make mod refer to deepest module
        for comp in components[1:]:
            mod = getattr(mod, comp)
        init_name = "glInit%sARB"%string.join(map(capitalize_word,string.split(ext,'_')),'')
        init_func = getattr(mod,init_name)
        if init_func():
            print "OK"
        else:
            print "Failed"
    except Exception, x:
        print "Failed (exception raised):",x
        
for ext in EXT_exts:
    print " GL_EXT_%s:"%ext,
    module_name = "OpenGL.GL.EXT.%s"%ext
Example #28
0
    def main(self):
        """main loop of editor"""
        #screen initialise
        screen = self.screen
        map_screen = self.screen.subsurface(self.map_screen_rect)
        #rect of the view
        screen_rect = self.map_screen_rect.copy()
        #orange background
        self.screen.fill(EditorIso.COLOR_BGD)
        #initialise event
        pygame.event.clear()
        pygame.key.set_repeat(200, 50)
        #thumb & tile window
        
        windows = self.init_windows()
        #Name of the map
        
        pygame.display.flip()
        continuer = True
        #initialise state button
        map_left_button_pressed = False
        start_time = time.time()
        horloge = pygame.time.Clock()
        while continuer:
            for event in pygame.event.get():
                ctrl = pygame.key.get_mods() & KMOD_CTRL
                if event.type == pygame.QUIT or\
                   event.type == KEYDOWN and event.key == K_ESCAPE:
                    continuer = False
                    return
                elif event.type == MOUSEMOTION:
                    if self.map_screen_rect.collidepoint(event.pos):
                        if pygame.mouse.get_pressed()[1]:
                            screen_rect.move_ip(event.rel[0], event.rel[1])
                        elif not('last_roll'in locals() and\
                                time.time() - last_roll < 0.5):
                            x, y = event.pos
                            x -= screen_rect.x
                            x -= windows['map'].contents_rect.x
                            y -= screen_rect.y
                            y -= windows['map'].contents_rect.y
                            self.cursor.move_to_screen(x, y)
                        
                elif event.type == MOUSEBUTTONDOWN:
                    button = event.button
                    if windows['tilesets'].onclick(event) or\
                       windows['thumb'].update_onclick(event):
                        pass
                    elif windows['map'].rect.collidepoint(event.pos):
                        if button in [4, 5]:
                            last_roll = time.time()
                            dh = (5 == button) - (4 == button)
                            self.cursor.h += dh
                            x, y = event.pos
                            y -= 8*dh
                            pygame.mouse.set_pos([x,y])
                        elif button == 3:
                            self.set_tile_infos(windows['thumb'])
                        elif button == 1 :
                            map_left_button_pressed = True 
                    elif windows['name'].rect.collidepoint(event.pos):
                        self.rename_map()

                elif event.type == MOUSEBUTTONUP and event.button == 1:
                    map_left_button_pressed = False
                elif pygame.key.get_pressed()[K_SPACE]:
                        map_left_button_pressed = True
                elif event.type == KEYDOWN:
                    key = event.key
                    if key == K_F11:
                        pygame.display.toggle_fullscreen()
                    elif event.key == K_s and ctrl:
                        self.save_mapdata()
                    elif event.key == K_l and ctrl:
                        self.load_map()
                        windows['map'].map = self.map
                    elif ctrl and event.key == K_n :
                        self.new_map(screen)
                        windows['map'].map = self.map
                    elif key == K_q and ctrl:
                       pygame.event.post(pygame.event.Event(QUIT, {}))
                    elif key in [K_DOWN, K_UP, K_LEFT, K_RIGHT]:
                        self.cursor.update(event)
                    elif key in [K_KP_PLUS, K_KP_MINUS]:
                        dh = (K_KP_PLUS == key) - (K_KP_MINUS == key)
                        self.cursor.h += dh
                    elif key == K_c:
                        self.set_tile_infos(windows['thumb'])
                    elif key == K_v:
                        self.cursor.square_infos = windows['thumb'].tile_infos
                elif event.type == KEYUP:
                    if event.key == K_SPACE:
                        map_left_button_pressed = False
            if map_left_button_pressed:
                #left clic on the map
                tset, tref, h = windows['thumb'].tile_infos
                if not(ctrl):
                    h = self.cursor.h
                self.cursor.square_infos = tset, tref, h
            windows['name'].update(self.map.name)
            windows['map'].update(screen_rect, self.cursor)
            
            for win in windows.values():
                win.draw(screen)
            pygame.display.flip()
            horloge.tick(60)
Example #29
0
def profile(command):
    import cProfile
    filename = 'pyweek10-ldnpydojo.profile'
    cProfile.runctx( command, globals(), locals(), filename=filename )
    subprocess.call( ['runsnake', filename] )
Example #30
0
                            "Autopickup has been enabled"))
                    else:
                        messageLog.append(Message.Message(\
                            "Autopickup has been disabled."))
                    
                if event.key == pygame.K_b:
                    background = not(background)
                    ForceDraw = True
                
                if cheatMode == True:                              
                    if event.key == pygame.K_F1:
                        ShowMapCheat = not ShowMapCheat
                        ForceDraw = True

                    if event.key == pygame.K_F2:
                        code.interact(local=locals())
                        
                    if event.key == pygame.K_F3:
                        PC.ChangeMap(Maps[PC.currentMap.level-1])
                        PC.currentMap.UpdateVisibility(PC, PC.x, PC.y)
                        ForceDraw = True
                        
                    if event.key == pygame.K_F4:
                        PC.ChangeMap(Maps[PC.currentMap.level+1])
                        PC.currentMap.UpdateVisibility(PC, PC.x, PC.y)
                        ForceDraw = True
                        
        else:
            dialog[0].process(event)
        
        if event.type == MOUSEBUTTONDOWN: