コード例 #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)")
コード例 #2
0
ファイル: events.py プロジェクト: Alfwich/square-text
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)
コード例 #3
0
 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
コード例 #4
0
 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)
コード例 #5
0
ファイル: credits.py プロジェクト: faif/The-Crime-Tracer
    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
コード例 #6
0
ファイル: form.py プロジェクト: AdrienMereghetti/new
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)
コード例 #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)
コード例 #8
0
ファイル: 2048.py プロジェクト: 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
コード例 #9
0
ファイル: __init__.py プロジェクト: DaneTheory/Py2D
	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)
コード例 #10
0
ファイル: fighters.py プロジェクト: Yamist/Oberon-Anomaly
 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)
コード例 #11
0
ファイル: messagebox.py プロジェクト: ajventer/mirthless
 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('')
コード例 #12
0
ファイル: pygamecontext.py プロジェクト: MaxwellEdison/PyMine
 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()
コード例 #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
コード例 #14
0
ファイル: ui.py プロジェクト: bazk/riverrun-gui
    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
コード例 #15
0
ファイル: inputOutput.py プロジェクト: Paulware/piPair
 def waitFor (self, caption, pollEvent):             
    sprites = self.utilScreen.basicScreen ( caption,['quit'] )
    
    pollEvent = 'self.ready=(' + pollEvent + ')'
    print ( 'waitFor pollEvent: [' + pollEvent + ']' )
    self.ready = False
    while not self.ready:
       exec (pollEvent, locals()) 
       # print ( 'Executing: ' + pollEvent ) 
       eventType,data,addr = self.getKeyOrUdp()    
       if eventType == pygame.MOUSEBUTTONDOWN:          
          sprite = self.utilScreen.getSpriteClick (data,sprites) 
          if sprite != -1: 
             break         
コード例 #16
0
ファイル: widget.py プロジェクト: szpak-forks/castle-combat
    def choices():
        def fget(self):
            return self._choices

        def fset(self, choices):
            selected_element = self._choices[self.index]
            self._choices = choices
            try:
                self.index = choices.index(selected_element)
            except ValueError:
                self.index = 0
            self.update()

        return locals()
コード例 #17
0
def game(player1, player2, width, height, col, ui, synchr, nb_moves, density, test, fps, rng):

    board = Board(width=width, height=height, colors=col, density=density, ui=ui, rng=rng)
    p1 = __import__(player1, globals(), locals(), ['Player'], 0).Player()
    p2 = __import__(player2, globals(), locals(), ['Player'], 0).Player()

    if test:
        board.set_board(p1.test(board.automata, Cell.PLAYER1))

    if ui:
        pygame.init()
        clock = pygame.time.Clock()
        FPS = fps
        board.draw_cells()
        pygame.display.update()

    limit_time(lambda: p1.preprocessing(copy.deepcopy(board.automata), Cell.PLAYER1), 1)
    limit_time(lambda: p2.preprocessing(copy.deepcopy(board.automata), Cell.PLAYER2), 1)

    while True:  # Game loop
        if ui:
            board.draw_cells()
            pygame.display.update()
        p1_move = limit_time(lambda: p1.turn(copy.deepcopy(board.automata), Cell.PLAYER1), 0.2)
        p2_move = limit_time(lambda: p2.turn(copy.deepcopy(board.automata), Cell.PLAYER2), 0.2)
        p1_move, p2_move = sanitize_moves(p1_move, p2_move, board)
        board.play(p1_move, p2_move)
        board.next()
        nb_moves -= 1
        if nb_moves == 0:
            return exit(board)
        if ui:
            for event in pygame.event.get():
                if event.type == QUIT:
                    return exit(board)
        if not synchr and ui:
            clock.tick(FPS)
コード例 #18
0
ファイル: rungame.py プロジェクト: xanalogica/SubChallenge
    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())
コード例 #19
0
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())
コード例 #20
0
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())
コード例 #21
0
ファイル: leveledit.py プロジェクト: PerroTron/HostilPlanet
    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
コード例 #22
0
ファイル: AntWars.py プロジェクト: mcanultyfamily/AntWars
    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())
コード例 #23
0
ファイル: pygamerenderer.py プロジェクト: gregr/uriel
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())
コード例 #24
0
ファイル: bambam.py プロジェクト: magahet/bambam
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())
コード例 #25
0
ファイル: resources.py プロジェクト: blackmius/pgame
 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
コード例 #26
0
def main():
    main = Main()

    pygame.init()
    old_time = pygame.time.get_ticks()

    pygame.display.set_caption("Space Invaders")
    pygame.display.set_icon(main.WINDOW_ICON)

    player_ship = Ship(main.ENEMY_BLUE_SHIP, 1)
    enemy_ship = Ship(main.ENEMY_BLUE_SHIP, 0)

    while True:
        main.draw_background()

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

            # Shooting Player laser
            if event.type == KEYDOWN:
                if event.key == K_SPACE:
                    player_laser = Lasers(player_ship.player_x,
                                          player_ship.player_y,
                                          player_ship.PLAYER_LASER)
                    player_ship.shoot_laser(player_laser, False,
                                            enemy_ship.enemy_x,
                                            enemy_ship.enemy_y,
                                            enemy_ship.enemy_img)

        player_ship.player()
        enemy_ship.enemy()

        if 'player_laser' in locals():
            player_ship.shoot_laser(player_laser, True, enemy_ship.enemy_x,
                                    enemy_ship.enemy_y, enemy_ship.enemy_img)

        main.update_display()
コード例 #27
0
    def _redraw(self):
        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))

        tuple(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
コード例 #28
0
 def __init__(self,
              items,
              DIS,
              max_list=3,
              pos=(0, 0),
              COLOR=(0, 0, 0),
              BGCOLOR=(0, 200, 200),
              HCOLOR=(200, 200, 0),
              height=50,
              width=200):
     ##        self.items=items
     ##        self.DIS=display
     ##        self.pos=pos
     ##        self.max_list=max_list
     ##
     ##        self.height=50
     ##        self.width=200
     max_list = min(max_list, len(items))
     self.__dict__.update(locals())
     del self.__dict__['self']
     self.SURF = pygame.surface.Surface(
         (self.width, self.height * max_list))
     self.BGSURF = pygame.surface.Surface(
         (self.width, self.height * max_list))
     self.BGSURF.fill(BGCOLOR)
     #FontObj=pygame.font.Font('STXINWEI.ttf',20)
     myfonts = ['stliti', 'stkaiti', '华文新魏', 'arial']
     sys_fonts = pygame.font.get_fonts()
     for font in myfonts:
         if font in sys_fonts:
             break
     else:
         print("Can't get system's appropriate font.")
     FontObj = pygame.font.SysFont(font, 20)
     self.TEXTS = list(
         map(lambda txt: FontObj.render(txt, True, COLOR), items))
     self.focus = self.head = 0
     self.update()
     return
コード例 #29
0
 def parse_scene(self):
     with open(self.scene_path, 'r') as fh:
         data = yaml.load(fh, Loader=yaml.SafeLoader)
     self.data = data
     # parse global: section
     global_d = data.get('global', {})
     width = global_d.get('width', 1200)
     height = global_d.get('height', 900)
     title = global_d.get('title', 'default title')
     music = global_d.get('background_music', None)
     framerate = global_d.get('framerate', os.environ.get('FR', 25))
     self.background_color_generator = eval(
         str(
             global_d.get('background_color',
                          'utils.default_generator((0, 0, 0, 255))')),
         globals(), locals())
     self.default_background_color_generator = self.background_color_generator
     self.background_color = next(self.background_color_generator)
     self.width = width
     self.height = height
     self.title = title
     self.framerate = framerate
     self.background_music = music
コード例 #30
0
 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')]
コード例 #31
0
ファイル: map_editor.py プロジェクト: Clarabel/PyIsoX3
    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)
コード例 #32
0
	
	pygame.display.update()


# initial player
player = Snake_Head(screen, [100, 100])

# bonus and score settings
sc = fontObj_score.render('Score: {:d}'.format(player.score), True, RED)

# initial body
for i in range(1, player.length):
	if i == 1:
		pre = player
	else:
		pre = locals()['body'+str(i-1)]

	if pre.direction == 1:
		X = pre.pos[0] - pre.width
		Y = pre.pos[1]
	elif pre.direction == 2:
		X = pre.pos[0]
		Y = pre.pos[1] - pre.width
	elif pre.direction == 3:
		X = pre.pos[0] + pre.width
		Y = pre.pos[1]
	elif pre.direction == 4:
		X = pre.pos[0]
		Y = pre.pos[1] + pre.width
	locals()['body'+str(i)] = Snake_Body(screen, [X,Y], pre.direction)
コード例 #33
0
super_man.rect.midbottom = grid_sprite_group.sprites()[0].rect.centerx, \
                            grid_sprite_group.sprites()[0].rect.bottom
shadow_man.rect.midbottom = super_man.rect.midbottom

is_sample = False  # 出牌开关
# 创建按钮
button = Button(screen, 195, 388, 150, 64,  text = "Click", \
                font=pygame.font.Font("font/songti.otf", 40,), fontSize = 30, \
                textColour = pygame.Color('green'), onClick = buttonOnClick,\
                margin = 6, textVAlign = "left", pressedColour = pygame.Color('red'), \
                hoverColour = pygame.Color('blue'), \
                onClickParams = [is_sample, ], )
# button.setImage(image = pygame.image.load("img/button.png").convert_alpha())
# 创建筛子
local_var = locals()
sieve_group = pygame.sprite.Group()
for i in range(1, 7):
    obj = local_var["num_0" + str(i)] = Ele_Sprite("img/" + str(i) * 2 + ".png")
    obj.num = i
    obj.rect.center = 670, 300
    sieve_group.add(obj)
show_obj = sieve_group.sprites()[0]  # 所要显示的筛子对象
swing_num = 0                        # 摇筛子的 次数
random_num = 0                       # 筛子的点数
random_switch = False                # 摇筛子的开关
game_switch = True                   # 游戏的开关
last_time = pygame.time.get_ticks()  # 时间
# 创建字体对象
font = freetype.Font("font/songti.otf", 30, )
コード例 #34
0
#             group.update_liberties()
#         if added_stone:
#             added_stone.group.update_liberties()


# def main():
    while True:
        pygame.time.wait(250)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and board.outline.collidepoint(event.pos):
                    x = int(round(((event.pos[0] - 5) / 40.0), 0))
                    y = int(round(((event.pos[1] - 5) / 40.0), 0))
                    stone = board.search(point=(x, y))
                    if stone:
                        stone.remove()
                    else:
                        added_stone = Stone(board, (x, y), board.turn())
        board.update_liberties(locals().get('added_stone', ''))


# if __name__ == '__main__':
#     pygame.init()
#     pygame.display.set_caption('Goban')
#     screen = pygame.display.set_mode(BOARD_SIZE, 0, 32)
#     background = pygame.image.load(BACKGROUND).convert()
#     board = Board()
#     main()
コード例 #35
0
ファイル: main.py プロジェクト: PingouinsECL/application
    init = 0
    play = 0
    number_turn = 0
    table_button = []
    players_lost = [0, 0, 0, 0]

    # HOME
    """
        DECIDE TO PLAY GAME OR TUTORIAL
    """

    while mode_home:

        # creating cursor if not exists
        if not('cursor' in locals() or 'cursor' in globals()):
            cursor = [0, 0]

        if not(pygame.mixer.music.get_busy()):
            pygame.mixer.music.load(sound_path)
            pygame.mixer.music.play()

        # displaying background
        window.blit(background, pos_background)
        window.blit(logo, pos_logo)
        window.blit(club, pos_club)
        
        # displaying buttons        
        but_play.show(window, cursor)
        but_tuto.show(window, cursor)
        but_sound.show(window, cursor)
コード例 #36
0
ファイル: EngKnappar.py プロジェクト: NiKiZe/ArtemisSBS
    #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)
コード例 #37
0
ファイル: inputOutput.py プロジェクト: Paulware/piPair
   def getKeyOrUdp(self):
     shiftKeys = { '\\':'|', ']':'}', '[':'{', '/':'?', '.':'>', ',':'<', '-':'_', '=':'+', ';':':',  \
                   '`':'~',  '1':'!', '2':'@', '3':'#', '4':'$', '5':'%', '6':'^', '7':'&', '8':'*', '9':'(', '0':')' }
     key = None
     upperCase = False
     typeInput = ''
     data = ''
     addr = ''
     
     # Note: If timeout is too close to time.time() 
     #       udp could be lost
     timeEvent = time.time() + 1
     move = None
     
     while data == '':
       if time.time() > self.udpTimeout:  
          if len(self.udpMessages) > len (self.acks): # Some messages have not been acked.
             print ( 'udpTimeout [len(udpMessages),len(acks)]: [' + \
                  str(len(self.udpMessages)) + ',' +  str(len(self.acks)) + \
                  '] elapsedTime: ' + str(time.time() - self.messageStartTime))    
             message = self.udpMessages [len(self.acks)]
             self.sendTo (message )
             self.waitingCount = self.waitingCount + 1
             self.udpTimeout = time.time() + (self.UDPTIMEOUT * self.waitingCount)
             print ( 'Sending: ' + message + ' waitingCount: ' + str(self.waitingCount))
             if self.waitingCount >= 100:
                print ( 'Wondering if other player is actually there still?' )
          else:
             self.waitingCount = 0       
             self.udpTimeout = time.time() + self.UDPTIMEOUT
                   
       rightClick = False
       
       ev = pygame.event.get()
       for event in ev:
          if event.type == VIDEORESIZE:
             DISPLAYSURF = pygame.display.set_mode(event.dict['size'],HWSURFACE|DOUBLEBUF|RESIZABLE)
          elif event.type == pygame.KEYDOWN:
             #print( "Got a keydown with value: " + str(event.key) )
             if (event.key == 303) or (event.key == 304): #shift
                upperCase = True
             # chr(273), 'w', chr(274), 's',  chr(275), 'd', chr (276), 'a']             
             elif (event.key == 273):
                data = 'w'
                typeInput = 'key'
             elif (event.key == 274): 
                data = 's'
                typeInput = 'key'
             elif (event.key == 275):
                data = 'd'
                typeInput = 'key'
             elif (event.key == 276):
                data = 'a'
                typeInput = 'key'             
             else:
                key = chr(event.key)
                if upperCase: 
                   if key in shiftKeys.keys():
                      key = shiftKeys[key]
                   else:                     
                      key = key.upper()
                
                typeInput = 'key'
                data=key
          elif event.type == pygame.KEYUP:
             data = ' '
             typeInput = pygame.KEYUP
             addr = 'key'
          elif event.type == pygame.QUIT:
             data = 'quit'
             typeInput = pygame.QUIT
             addr = 'key'
          elif event.type == pygame.MOUSEBUTTONUP:
             data = pygame.mouse.get_pos()
             typeInput = pygame.MOUSEBUTTONUP
             addr = 'mouse'
          elif event.type == pygame.MOUSEBUTTONDOWN:
             #print ( 'Detected a mouse down yo' )
             data = pygame.mouse.get_pos()
             typeInput = pygame.MOUSEBUTTONDOWN
             addr = 'mouse'
             rightClick = (event.button == 3)
             if rightClick:
                print ("right click detected")
          elif event.type == pygame.MOUSEMOTION:
             data = pygame.mouse.get_pos()
             typeInput = pygame.MOUSEMOTION
             addr = 'mouse'
          #   
          #else:
          #   print ( 'Got a event: ' + str(event.type)) 
                
       if data == '':
          if self.tcpConnection != None: 
             i,o,e = select.select ([self.tcpConnection], [], [], 0.0001)
          elif self.tcpSocket != None:
             i,o,e = select.select ([self.tcpSocket], [], [], 0.0001)
          else: #udp
             i,o,e = select.select ([self.client], [], [], 0.0001)
             
          for s in i:
             if s == self.client:
                data, addr = self.client.recvfrom (1024)
                data = data.decode();
                addr = str(addr[0])
                if (addr == '192.168.4.1') and (self.myIpAddress == '127.0.1.1'): 
                   data = ''
                elif (addr == self.myIpAddress):
                   data = ''
                else:  
                   print ( '[addr,myIpAddress]: [' + addr + ',' + self.myIpAddress + ']' )
                   ind = data.find ( ':' )
                   if data != '':
                      if data[0:3] == 'ack': # I received an ACK of a previous send
                         ackCount = data[4:] 
                         ackCount = int(ackCount)
                         if ackCount == len(self.acks): 
                            self.acks.append (data)
                         self.commLogWrite ( str(datetime.datetime.now().time()) + ' Got an ' + data + '\n')
                         data = '' # Do not send this forward
                      else:                       
                         udpCount = int(data[0:ind])
                         message = 'ack:' + str(udpCount) 
                         if data != self.lastMessage: 
                            # print ( '[lastMessage,data]: [' + self.lastMessage + ',' + data + ']' )
                            self.commLogWrite ( str(datetime.datetime.now().time()) + ':rcv:' + data + ' from: ' + addr + '\n')
                            
                         print ( 'acking...[' + message + '] lastMessage: [' + self.lastMessage + ']')                         
                         self.sendTo (message) 
                         if data != self.lastMessage:                             
                            self.lastMessage = data
                            data = data[(ind+1):]                   
                            ind = data.find ( 'exec:')
                            if ind > -1: # joining=, self.games=, self.move=, self.opponentDeck
                               command = data[ind+5:]
                               exec (command, locals())
                               
                               if command.find ('self.move') > -1: 
                                  self.moves.append (self.move)

                               print ( 'Executing command: ' + command ) 
                                  
                            typeInput = 'udp'                        
                         else:
                            print ( 'Not executing this message: [' + data + '] because it is identical to the last message' )                      
                   
             elif s == self.tcpConnection: 
                data, addr = self.tcpConnection.recvfrom (1024)
                data = data.decode();
                #print ("Received tcp data:" + data)
                addr = str(addr[0])
                typeInput = 'tcp'
             elif s == self.tcpSocket:
                data, addr = self.tcpSocket.recvfrom (1024)
                data = data.decode();
                #print ("Received tcp data:" + data)
                typeInput = 'tcp'
                addr = str(addr[0])
                
       if (data == '') and (time.time() > timeEvent): 
          addr = socket.gethostbyname(socket.gethostname())
          if (self.myIpAddress != addr ): 
             self.commLogWrite ( str(datetime.datetime.now().time()) + ':change ip address to: ' + addr + '\n') 
             assert False, 'My ip address has changed, please start over.' 
             '''
             self.myIpAddress = addr     
             self.client.close()
             self.initClient()
             self.acks = []
             '''
             
          typeInput = 'time'
          data = ' '
          addr = 'clock'  
          
     # print ( 'returning typeInput: ' + str(typeInput))   
     return typeInput,data,addr
コード例 #38
0
        with torch.no_grad():
            #Collect list of model subnetworks inference results
            for iterator in range(sample_size_drop):
                theta_0_sin, theta_0_cos, theta_1_sin, theta_1_cos = model.forward(
                    input_to_model)

                theta_0 = np.arctan2(theta_0_sin.item(), theta_0_cos.item())
                theta_1 = np.arctan2(theta_1_sin.item(), theta_1_cos.item())
                theta_0, theta_1 = helpers.convert_normal_angle(
                    theta_0, theta_1)
                lst_theta0.append(theta_0)
                lst_theta1.append(theta_1)

        #Plot uncertainty_graphs
        if 'uncertainty_graphs' in locals():
            plt.clf()
        uncertainty_graphs = helpers.make_uncertainty_plots(
            sorted(lst_theta0[:-1]), sorted(lst_theta1[:-1]), lst_theta0[-1],
            lst_theta1[-1])
        del (lst_theta0[:])
        del (lst_theta1[:])

        #Inference model using all connections and calc rotation for upper arm and lower arm
        model.eval()
        theta_0_sin, theta_0_cos, theta_1_sin, theta_1_cos = model.forward(
            input_to_model)

        theta_0 = np.arctan2(theta_0_sin.data[0], theta_0_cos.data[0])
        theta_1 = np.arctan2(theta_1_sin.data[0], theta_1_cos.data[0])
        theta_0, theta_1 = helpers.convert_normal_angle(theta_0, theta_1)
コード例 #39
0
ファイル: openglrenderer.py プロジェクト: gregr/uriel
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())
コード例 #40
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)
コード例 #41
0
# Command handlers all have the name command_foo (called on key down) or
# command_foo_off (called on key up).
# If one of these is missing it's simply not called.

# Set up the command handlers for simple methods on the drone that just take
# 'speed' as their sole argument, with 0 meaning to stop doing the thing.
# The use of partial() here is necessary because if we just use `command` in the
# lambda body without making it an argument, all of the handlers will close over
# the same binding of `command` and will end up implementing whatever value
# `command` had last (in this case take_picture from the second loop below).
for command in [
        'forward', 'backward', 'left', 'right', 'up', 'down',
        'counter_clockwise', 'clockwise'
]:
    locals()["command_%s" % command] = partial(
        lambda command, drone, state: getattr(drone, command)(state.speed),
        command)
    locals()["command_%s_off" % command] = partial(
        lambda command, drone, state: getattr(drone, command)(0), command)

# Command handlers for methods on the drone that take no arguments.
for command in ['takeoff', 'land', 'palm_land', 'take_picture']:
    locals()["command_%s" % command] = partial(
        lambda command, drone, _: getattr(drone, command)(), command)

# Command handlers that require special handling on the client.


def command_faster(drone, state):
    state.speed = min(100, state.speed + 10)
コード例 #42
0
    e11.delete(0, 'end');e12.delete(0, 'end');e13.delete(0, 'end');e14.delete(0, 'end');e15.delete(0, 'end');
    e16.delete(0, 'end');e17.delete(0, 'end');e18.delete(0, 'end');e19.delete(0, 'end');e20.delete(0, 'end');
    e21.delete(0, 'end');e22.delete(0, 'end');e23.delete(0, 'end');e24.delete(0, 'end');e25.delete(0, 'end');
    e26.delete(0, 'end');e27.delete(0, 'end');e28.delete(0, 'end');e29.delete(0, 'end');e30.delete(0, 'end');
    e31.delete(0, 'end');e32.delete(0, 'end');e33.delete(0, 'end');e34.delete(0, 'end');e35.delete(0, 'end');
    e36.delete(0, 'end');e37.delete(0, 'end');e38.delete(0, 'end');e39.delete(0, 'end');e40.delete(0, 'end');
    e41.delete(0, 'end');e42.delete(0, 'end');e43.delete(0, 'end');e44.delete(0, 'end');e45.delete(0, 'end');
    e46.delete(0, 'end');
def cls_pay():
    global e47,e48,e49,e50,e51,e52,e53,e54
    e47.delete(0, 'end');e48.delete(0, 'end');e49.delete(0, 'end');e50.delete(0, 'end');
    e51.delete(0, 'end');e52.delete(0, 'end');e53.delete(0, 'end');e54.delete(0, 'end');
for i in range(len(QU1)):
    tk.Label(master,
             text=QU1[i]).grid(row=i)
    locals()["e%s"%i] = tk.Entry(master)
    locals()["e%s"%i].grid(row=i, column=1)

for i in range(len(QU3)):
    tk.Label(master,
             text=QU3[i]).grid(row=8, column=i)

a=9
z=7
for j in range(5):
    for i in range(len(QU3)):
        if i==1:
            locals()["e%s"%(z)] = tk.Entry(master,width=60)
            locals()["e%s"%(z)].grid(row=a+3*j, column=i);z+=1
            locals()["e%s"%(z)] = tk.Entry(master,width=60)
            locals()["e%s"%(z)].grid(row=a+3*j+1, column=i);z+=1
コード例 #43
0
ファイル: opengl_info.py プロジェクト: Complex501/visionegg
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
コード例 #44
0
ファイル: main.py プロジェクト: mjs/ldnpydojo
def profile(command):
    import cProfile
    filename = 'pyweek10-ldnpydojo.profile'
    cProfile.runctx(command, globals(), locals(), filename=filename)
    subprocess.call(['runsnake', filename])
コード例 #45
0
         continuer = False
     elif evenement.type == KEYDOWN and evenement.key == K_c:
         box.move = False
         box2.move = False
         i_type = str(input("quel type d'objet voulez vous ? (bloc ou objet) \n"))
         print(i_type)
         if i_type == "objet":
             nbBoites += 1
             i_name = "box" + str(nbBoites)
             i_posX = int(input("entrez la position X de départ\n"))
             i_posY = int(input("entrez la position Y de départ\n"))
             i_angle = int(input("entrez l'angle de l'objet\n"))
             i_angle *= 3.14/180
             i_masse = int(input("entrez la masse de l'objet\n"))
             i_velocite = int(input("entrez la vélocité de l'objet\n"))
             v = locals()
             v["box%d" % nbBoites] = Objet(i_name, i_posX, i_posY, i_angle, i_masse, i_velocite)
             print(allBoxes)
             print(box3.name)
             
     
         
 box.eventScan()
 box2.eventScan()
 #/BOX_2-----------------------------------------------------------------------------------------------------------------------------------------------------------------
         
 #/EVENTS -----------------------------
         
 #PROCESSING -------------------------
 clock.tick(60)
 t = time.get_ticks()
コード例 #46
0
 def parse_generators(self, generators):
     parsed = {}
     for gen, evalstr in generators.items():
         parsed[gen] = eval(str(evalstr), globals(), locals())
     return parsed
コード例 #47
0
 def __init__(self, face_detector, lag=None, same=None):
     super(MultiFaceTracker, self).__init__()
     set_defaults(self, locals())
     self.faces = []
コード例 #48
0
ファイル: SS_Game_BCI.py プロジェクト: kstandvoss/BCI17
# Emergency looks
left_time_IC = time.time()
right_time_IC = time.time()
right_IC_color = alienColorRight
left_IC_color = alienColorLeft
IC_side = int(round(0.1 * ScreenHeight))

# Music
pygame.mixer.init(44100, -16, 2, 2048)
pygame.mixer.music.load(assetpath + "space.mp3")
pygame.mixer.music.set_volume(1)
pygame.mixer.music.play(-1)

# Text inits
if 'font' not in locals():
    font = pygame.font.Font(None, int(
        ScreenHeight *
        0.04))  # Python crashes if SysFont is called > 1 XOR specified font
    font_FPS = pygame.font.Font(None, int(ScreenHeight * 0.1))

text_y = int(round(ScreenHeight * 0.01))
x_time = int(round(ScreenWidth * 0.025))
x_static = int(round(ScreenWidth * 0.2))
x_shots = int(round(ScreenWidth * 0.21))
x_static2 = int(round(ScreenWidth * 0.35))
x_score = int(round(ScreenWidth * 0.36))
x_static3 = int(round(ScreenWidth * 0.43))
x_accuracy = int(round(ScreenWidth * 0.44))

textColor = (150, 150, 150)  # So the bullet over it don't hide the text
コード例 #49
0
ファイル: rl.py プロジェクト: lkingsford/AtlasWarriors
                            "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:           
コード例 #50
0
ファイル: emulationhub.py プロジェクト: AlonsoLP/EmulationHub
        if not hasattr(event, 'key'): continue
        if (event.key == K_RIGHT and event.type == KEYDOWN): roll = 2
        elif (event.key == K_LEFT and event.type == KEYDOWN): roll = 1
        elif (event.key == K_ESCAPE and event.type == KEYDOWN): sys.exit(0)
        elif (event.key == K_RETURN and event.type == KEYDOWN):
            p = subprocess.Popen("exec " + emulator_list[0].get_command(),
                                 stdout=subprocess.PIPE,
                                 shell=True)
        elif (event.key == K_TAB and event.type == KEYDOWN):
            p = subprocess.Popen("exec " + emulator_list[3].get_command(),
                                 stdout=subprocess.PIPE,
                                 shell=True)
        elif (event.key == K_TAB and event.type == KEYDOWN):
            p.terminate()

    if 'device' in locals():
        if (device.active_keys() == [314, 315]):
            p.terminate()
        print device.active_keys()

    if hasattr(event, 'key'):
        pygame.draw.rect(screen, (255, 255, 255),
                         (0, (resolution[3]) - 130, resolution[0], 260))
        screen.blit(background, (0, 0))  # remove when label test ends

    if (roll == 1):  # LEFT
        emulator_selection = rotate(emulator_selection, 'left')
        roll = 0
    elif (roll == 2):  # RIGHT
        emulator_selection = rotate(emulator_selection, 'right')
        ntmp = roll
コード例 #51
0
ファイル: kanawars.py プロジェクト: mysablehats/kanawars
	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: 
コード例 #52
0
ファイル: AntWars.py プロジェクト: mcanultyfamily/AntWars
 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())
コード例 #53
0
class Sounds(object):
    # you are not expected to understand this
    for filename in glob.glob(os.path.join(os.path.dirname(__file__),
                                           '*.wav')):
        sound_id, _ = os.path.splitext(os.path.basename(filename))
        locals()[sound_id] = pygame.mixer.Sound(filename)
コード例 #54
0
                # Ask for Player input
                pos_x = event.pos[0] # Zeroeth element is horizontal axis, first element is vertical axis
                pos_y = event.pos[1]

                if SQUARE_SIZE < pos_y < SQUARE_SIZE*(DIM+1)  and SQUARE_SIZE < pos_x < SQUARE_SIZE*(DIM+1) :          
                    u_row = int(math.floor(pos_y/SQUARE_SIZE))-1
                    u_col = int(math.floor(pos_x/SQUARE_SIZE))-1

                    # Check for valid location and drop piece
                    if is_vacant(board, u_row, u_col, turn) and orthello(board, u_row, u_col, turn, False):
                        flip_num = orthello(board, u_row, u_col, turn, True)
                        playable_list = availoc(board, available_board, next_turn)
                        draw_avaiBoard(available_board, next_turn)
                    else:
                        error = True
                        print_special_message(board, available_board, turn,(f"Error. Position not valid. Player {turn} go again." % locals()))
                        playable_list = availoc(board, available_board, turn)
                        draw_avaiBoard(available_board, turn)
                    
                    # Print and draw board.                     
                    print_board(board, flip_num)
                    draw_board(board)

                    # Check for end game
                    if is_end_game(board):
                        print("End Game. Who wins?")
                        if (p2_score > p1_score):
                            print_special_message(board, available_board, turn, "Player 2 wins!")
                        elif (p2_score == p1_score):
                            print_special_message(board, available_board, turn, "It's a tie! You're both winners/ losers!")
                        else:
コード例 #55
0
ファイル: main.py プロジェクト: mjs/ldnpydojo
def profile(command):
    import cProfile
    filename = 'pyweek10-ldnpydojo.profile'
    cProfile.runctx( command, globals(), locals(), filename=filename )
    subprocess.call( ['runsnake', filename] )
コード例 #56
0
ファイル: flappy.py プロジェクト: lucianzhong/torcspilot
def playIt(movementInfo, decider):
    global iters, games, FPS
    itercount = 0
    score = playerIndex = loopIter = 0
    playerIndexGen = movementInfo['playerIndexGen']
    playerx, playery = int(SCREENWIDTH * 0.2), movementInfo['playery']

    basex = movementInfo['basex']
    baseShift = IMAGES['base'].get_width() - IMAGES['background'].get_width()

    # get 2 new pipes to add to upperPipes lowerPipes list
    newPipe1 = getRandomPipe()
    newPipe2 = getRandomPipe()

    # list of upper pipes
    upperPipes = [
        {
            'x': 150,
            'y': newPipe1[0]['y']
        },
        {
            'x': 150 + (SCREENWIDTH / 2),
            'y': newPipe2[0]['y']
        },
    ]

    # list of lowerpipe
    lowerPipes = [
        {
            'x': 150,
            'y': newPipe1[1]['y']
        },
        {
            'x': 150 + (SCREENWIDTH / 2),
            'y': newPipe2[1]['y']
        },
    ]
    pipeVelX = -4

    # player velocity, max velocity, downward accleration, accleration on flap
    playerVelY = -9  # player's velocity along Y, default same as playerFlapped
    playerMaxVelY = 10  # max vel along Y, max descend speed
    playerMinVelY = -8  # min vel along Y, max ascend speed
    playerAccY = 1  # players downward accleration
    playerFlapAcc = -9  # players speed on flapping
    playerFlapped = False  # True when player flaps

    while True:
        eventLog = None
        for event in pygame.event.get():
            if event.type == KEYDOWN and (event.key == K_UP):
                if playery > -2 * IMAGES['player'][0].get_height():
                    playerVelY = playerFlapAcc
                    playerFlapped = True
            if event.type == KEYDOWN and (event.key == K_SPACE):
                if FPS == 3000:
                    FPS = 4
                elif FPS == 4:
                    FPS = 30
                else:
                    FPS = 3000
        # check for crash here
        crashTest = checkCrash(
            {
                'x': playerx,
                'y': playery,
                'index': playerIndex
            }, upperPipes, lowerPipes)

        if crashTest[0]:
            iters = iters + itercount
            if itercount > 140:
                print str(itercount) + "versus " + str(iters / games)
            return {
                'y': playery,
                'groundCrash': crashTest[1],
                'basex': basex,
                'upperPipes': upperPipes,
                'lowerPipes': lowerPipes,
                'score': score,
                'playerVelY': playerVelY,
            }
        # check for score
        playerMidPos = playerx + IMAGES['player'][0].get_width() / 2
        for pipe in upperPipes:
            pipeMidPos = pipe['x'] + IMAGES['pipe'][0].get_width() / 2
            if pipeMidPos <= playerMidPos < pipeMidPos + 4:
                score += 1
                if FPS != 3000:
                    SOUNDS['point'].play()

        # playerIndex basex change
        if (loopIter + 1) % 3 == 0:
            playerIndex = playerIndexGen.next()
        loopIter = (loopIter + 1) % 30
        basex = -((-basex + 100) % baseShift)

        # player's movement
        if playerVelY < playerMaxVelY and not playerFlapped:
            playerVelY += playerAccY
        if playerFlapped:
            playerFlapped = False
        playerHeight = IMAGES['player'][playerIndex].get_height()
        playery += min(playerVelY, BASEY - playery - playerHeight)

        # move pipes to left
        for uPipe, lPipe in zip(upperPipes, lowerPipes):
            uPipe['x'] += pipeVelX
            lPipe['x'] += pipeVelX

        # add new pipe when first pipe is about to touch left of screen
        if 0 < upperPipes[0]['x'] < 5:
            newPipe = getRandomPipe()
            upperPipes.append(newPipe[0])
            lowerPipes.append(newPipe[1])

        # remove first pipe if its out of the screen
        if upperPipes[0]['x'] < -IMAGES['pipe'][0].get_width():
            upperPipes.pop(0)
            lowerPipes.pop(0)

        # draw sprites
        if FPS != 3000 or (itercount + iters) % 1000 == 0:
            SCREEN.blit(IMAGES['background'], (0, 0))

            for uPipe, lPipe in zip(upperPipes, lowerPipes):
                SCREEN.blit(IMAGES['pipe'][0], (uPipe['x'], uPipe['y']))
                SCREEN.blit(IMAGES['pipe'][1], (lPipe['x'], lPipe['y']))

            SCREEN.blit(IMAGES['base'], (basex, BASEY))
            # print score so player overlaps the score
            showScore(score)
            SCREEN.blit(IMAGES['player'][playerIndex], (playerx, playery))

            pygame.display.update()
        worldState = {
            'x': playerx,
            'y': playery,
            'upperPipes': upperPipes,
            'lowerPipes': lowerPipes,
            'playerVelY': playerVelY
        }
        action = decider.handleActions(locals())
        if action is not None:
            pygame.event.post(action)
        itercount = itercount + 1
        FPSCLOCK.tick(FPS)
コード例 #57
0
def isset(var):
    return (var in locals() or var in globals())
コード例 #58
0
            game_over = True

        # Next move
        # If error = False
        if turn == PLAYER and player_valid == True:
            turn = AI
            next_turn = PLAYER
        elif turn == AI and AI_valid == True:
            turn = PLAYER
            next_turn = AI
        else:
            pass

    else:  # If either player cannot move, then move on to next player. Blit available locations for next player.
        cant_move += 1
        print_special_message(board, available_board, turn, (
            f"Can't Move! Player {turn} cannot move. It is player {next_turn}'s turn."
            % locals()))
        if turn == PLAYER:
            turn = AI
            next_turn = PLAYER
        else:
            turn = PLAYER
            next_turn = AI
        playable_list = availoc(board, available_board, turn)
        draw_avaiBoard(available_board, turn)
        draw_board(board)
        if cant_move > 2:
            terminate_game(board)
            game_over = True
コード例 #59
0
    def populate_scene(self):
        self.objects = {}
        self.effects = {}
        self.overall_effects = {}
        self.scenes = []
        self.scene_counter = 0
        data = self.data
        fobjects = data.get('objects', {})
        for objname, objdata in fobjects.items():
            o_type = objdata.get('type', None)
            base_size = objdata.get('base_size', None)
            generators = objdata.get('generators', {})
            if base_size:
                base_size = tuple(base_size)
            generators = self.parse_generators(generators)
            if o_type not in dir(shapes):
                raise RuntimeError("I don't know shape " + o_type)
            evalstr = "shapes.{o_type}(base_size=base_size, generators=generators)".format(
                o_type=o_type)

            obj = eval(evalstr, globals(), locals())
            self.objects[objname] = obj
        feffects = data.get('effects', {})
        for objname, objdata in feffects.items():
            o_type = objdata.get('type', None)
            generators = objdata.get('generators', {})
            target_s = objdata.get('target', None)
            target = self.objects[target_s]
            if o_type not in dir(effects):
                raise RuntimeError("I do not know effect " + o_type)
            evalstr = "effects.{o_type}(other_sprite=target, generators=generators)".format(
                o_type=o_type)
            obj = eval(evalstr, globals(), locals())
            self.effects[objname] = obj
        fovreff = data.get('overall_effects', {})
        for objname, objdata in fovreff.items():
            o_type = objdata.get('type', None)
            generators = objdata.get('generators', {})
            target = self.screen_wrapper
            if o_type not in dir(effects):
                raise RuntimeError("I do not know effect " + o_type)
            evalstr = "effects.{o_type}(other_sprite=target, generators=generators)".format(
                o_type=o_type)

            obj = eval(evalstr, globals(), locals())
            self.overall_effects[objname] = obj
        for scene in data.get('scenes', []):
            title = scene.get('title', None)
            duration = scene.get('duration', 0)
            music = scene.get('music', None)
            scene_objlist = scene.get('objects', [])
            scene_efflist = scene.get('effects', [])
            scene_ovreflist = scene.get('overall_effects', [])
            scene_objs = tuple([self.objects[a] for a in scene_objlist])
            scene_effects = tuple([self.effects[a] for a in scene_efflist])
            scene_overall_effects = tuple(
                [self.overall_effects[a] for a in scene_ovreflist])
            background_color = eval(str(scene.get('background_color', 'None')),
                                    globals(), locals())
            self.scenes.append(
                Scene(title=title,
                      duration=duration,
                      objects=scene_objs,
                      effects=scene_effects,
                      overall_effects=scene_overall_effects,
                      music=music,
                      background_color=background_color))