Esempio n. 1
0
	def _check_events(self):		
		playboard = self.playboard
		events = pygame.event.get()    
		# Android-specific:
		if ANDROID and android.check_pause():
			android.wait_for_resume()		    
		# Handle events
		for e in events:	
			if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
				return False
			elif e.type == KEYDOWN and e.key == pygame.K_b:
				if self.is_game_over:
					return False
				else:
					self.is_game_over = True
					self._check_high_scores()
			elif e.type == MOUSEBUTTONDOWN:					
				if self.is_level_complete:
					self.level += 1
					self._start_level()
				elif self.is_game_over and e.type == MOUSEBUTTONDOWN:
					if self.start_button.is_pressed(e.pos):
						self.start()
				else:
					self._on_touch(e.pos)									
		return True
Esempio n. 2
0
def main():
    # Mapeando o botao voltar do android como K_ESCAPE (ESC)
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Usando timer para controlar os FPS
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # A cor da tela
    global color
    controle = Controle(LARGURA, ALTURA)
    while True:

        ev = pygame.event.wait()

        # Especifico para android
        if android:
            if android.check_pause():
                android.wait_for_resume()

        if ev.type == TIMEREVENT:
            screen.fill(color)
            controle.desenha(screen)
            pygame.display.flip()
        else:
            controle.evento(ev, color)

        if (ev.type == pygame.KEYDOWN
                and ev.key == pygame.K_ESCAPE) or ev.type == pygame.QUIT:
            break
Esempio n. 3
0
def wait_event():
    # Wait for input, then return it when it comes.
    ev = pygame.event.wait()

    # Android-specific:
    if android:
        if android.check_pause():
            android.wait_for_resume()

    # Record if a quit event took place
    if ev.type == pygame.QUIT:
        my_state.got_quit = True
    elif ev.type == TIMEREVENT:
        pygame.event.clear(TIMEREVENT)
    elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_PRINT:
        pygame.image.save(my_state.screen, util.user_dir("out.png"))
    elif ev.type == pygame.VIDEORESIZE:
        my_state.screen = pygame.display.set_mode(
            (max(ev.w, 800), max(ev.h, 600)), pygame.RESIZABLE)

    # Inform any interested widgets of the event.
    my_state.widget_clicked = False
    if my_state.widgets_active:
        for w in my_state.widgets:
            w.respond_event(ev)

    return ev
Esempio n. 4
0
    def update(self):
        if android:
            if android.check_pause():
                android.wait_for_resume()
                
        self.fps_clock.tick(60)

        
        
        for evt in pygame.event.get():
            if evt.type == pygame.QUIT:
                program_quit()
                
            elif evt.type == pygame.MOUSEBUTTONDOWN:
                self.evm.post(ev.LMBDOWN(evt.pos))
                
                if android:
                    self.evm.post(ev.MOUSEDRAG())
                    
                if evt.button == 3:
                    self.evm.post(ev.CreatePlanet(evt.pos, 50))

            elif evt.type == pygame.MOUSEBUTTONUP:
                self.evm.post(ev.LMBUP(evt.pos))

            elif evt.type == pygame.KEYDOWN:
                if evt.key == pygame.K_ESCAPE:
                    program_quit()
                elif evt.key == pygame.K_SPACE:
                    self.evm.post(ev.ClearGame())
                    self.evm.post(ev.StartGame())
Esempio n. 5
0
 def run(self):
     self.play_music()
     self.total_time_passed = 0
     fps_limit = 60
     if android:
         fps_limit = 40
     while True: #main game loop
         if android:
             if android.check_pause():
                 self.pause()
                 #self.pause_music()
                 self.stop_music()
                 android.wait_for_resume()
                 self.pause(resume=True)
                 self.play_music()
                 #self.pause_music(resume=True)
         time_passed = self.clock.tick(fps_limit) / 1000.0
         self.total_time_passed += time_passed
         # If too long has passed between two frames, don't update 
         # (the game must have suspended for some reason, and we don't want it to "jump forward" suddenly)
         if time_passed > 0.05:
             time_passed = 0.05
         input = self.process_input()
         
         self.update(time_passed, input, moveToPos = android)
         
         self.draw()
Esempio n. 6
0
    def update(self):
        # check for android pause event
        if android:
            if android.check_pause():
                android.wait_for_resume()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.direction = "up"
                elif event.key == pygame.K_DOWN:
                    self.direction = "down"
                elif event.key == pygame.K_LEFT:
                    self.direction = "left"
                elif event.key == pygame.K_RIGHT:
                    self.direction = "right"
                elif event.key == pygame.K_SPACE:
                    self.direction = "stop"
                elif event.key == pygame.K_q:
                    self.direction = "lup"
                elif event.key == pygame.K_w:
                    self.direction = "rup"
                elif event.key == pygame.K_a:
                    self.direction = "ldown"
                elif event.key == pygame.K_s:
                    self.direction = "rdown"   
# Mouse Event Handleling
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.game_buttons()
Esempio n. 7
0
    def run(self):
        pygame.init()
        self.load()
        self.gameinput = {"singleplayer": input.playerSplitScreen, "multiplayer": input.playerOnline}

        self.loadMenu()
        gfx.menu.draw()
        while self.running:
            if android:
                if android.check_pause():
                    android.wait_for_resume()
            input.general()
            if not self.inGame:
                input.inMenu(gfx.menu.location)
                gfx.menu.draw()
            else:
                input.inGame()
                self.gameinput[self.mode]()
                if self.settings['game']['hippie']:
                    gfx.game.ball.hippie()
                if gfx.game.playing:
                    if self.mode == "singleplayer":
                        gfx.game.ball.ballEvent()
                gfx.game.draw()

            gfx.newFrame()

        self.quit()
Esempio n. 8
0
def wait_event():
    # Wait for input, then return it when it comes.
    ev = pygame.event.wait()

    # Android-specific:
    if android:
        if android.check_pause():
            android.wait_for_resume()

    # Record if a quit event took place
    if ev.type == pygame.QUIT:
        my_state.got_quit = True
    elif ev.type == TIMEREVENT:
        pygame.event.clear(TIMEREVENT)
    elif ev.type == pygame.MOUSEMOTION:
        my_state.update_mouse_pos()
    elif ev.type == pygame.KEYDOWN:
        if ev.key == pygame.K_PRINT:
            pygame.image.save(my_state.screen, util.user_dir("out.png"))
        elif ev.key in my_state.get_keys_for("next_widget"):
            my_state.active_widget_hilight = True
            my_state.activate_next_widget()
    elif ev.type == pygame.VIDEORESIZE:
        # PG2 Change
        # pygame.display._resize_event(ev)
        my_state.set_size(max(ev.w, 800), max(ev.h, 600))

    # Inform any interested widgets of the event.
    my_state.widget_clicked = False
    if my_state.widgets_active:
        for w in my_state.widgets:
            w.respond_event(ev)

    return ev
Esempio n. 9
0
    def handleEvents(self):
        if android:
            if android.check_pause():
                android.wait_for_resume()
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()

            if event.type == KEYDOWN and event.key == K_q:
                if not self.capture_video:
                    self.capture_video = True
                else:
                    self.capture_video = False
            
            if self.state == STATE.game:
                self.stage.player.handleEvents(event, self.stage.grid)
                self.overlay.handleEvents(event)

            if self.state == STATE.title_screen:
                self.hud.handleEvents(event)
            if self.state == STATE.gameover:
                self.gameover.handleEvents(event)
                if self.gameover.retry:
                    self.reset()
                elif self.gameover.quit:
                    pygame.quit()
                    sys.exit()
        if self.hud.active:
            self.state = STATE.title_screen       
        else:
            self.state = STATE.game
Esempio n. 10
0
    def update(self):
        # check for android pause event
        if android:
            if android.check_pause():
                android.wait_for_resume()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.direction = "up"
                elif event.key == pygame.K_DOWN:
                    self.direction = "down"
                elif event.key == pygame.K_LEFT:
                    self.direction = "left"
                elif event.key == pygame.K_RIGHT:
                    self.direction = "right"
                elif event.key == pygame.K_SPACE:
                    self.direction = "stop"
                elif event.key == pygame.K_q:
                    self.direction = "lup"
                elif event.key == pygame.K_w:
                    self.direction = "rup"
                elif event.key == pygame.K_a:
                    self.direction = "ldown"
                elif event.key == pygame.K_s:
                    self.direction = "rdown"
# Mouse Event Handleling
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.game_buttons()
Esempio n. 11
0
 def loop(self):
     while True:
         event = pygame.event.wait()
         if android:
             if android.check_pause():
                 android.wait_for_resume()
         if self[event.type](event): break
Esempio n. 12
0
def wait_event():
    # Wait for input, then return it when it comes.
    ev = pygame.event.wait()

    # Android-specific:
    if android:
        if android.check_pause():
            android.wait_for_resume()

    # Record if a quit event took place
    if ev.type == pygame.QUIT:
        my_state.got_quit = True
    elif ev.type == TIMEREVENT:
        pygame.event.clear( TIMEREVENT )
    elif ev.type == pygame.KEYDOWN:
        if ev.key == pygame.K_PRINT:
            pygame.image.save( my_state.screen, util.user_dir( "out.png" ) )
        elif ev.key in my_state.get_keys_for("next_widget"):
            my_state.active_widget_hilight = True
            my_state.activate_next_widget()
    elif ev.type == pygame.VIDEORESIZE:
        my_state.screen = pygame.display.set_mode( (max(ev.w,800),max(ev.h,600)), pygame.RESIZABLE )

    # Inform any interested widgets of the event.
    my_state.widget_clicked = False
    if my_state.widgets_active:
        for w in my_state.widgets:
            w.respond_event(ev)

    return ev
Esempio n. 13
0
def main():
    # Mapeando o botao voltar do android como K_ESCAPE (ESC)
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Usando timer para controlar os FPS
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # A cor da tela
    global color
    controle = Controle(LARGURA,ALTURA)
    while True:

        ev = pygame.event.wait()

        # Especifico para android
        if android:
            if android.check_pause():
                android.wait_for_resume()

        if ev.type == TIMEREVENT:
            screen.fill(color)
            controle.desenha(screen)
            pygame.display.flip()
        else:
            controle.evento(ev, color)

        if (ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE) or ev.type == pygame.QUIT:
            break
Esempio n. 14
0
    def do_about(self):
        lines = [line.strip() for line in '''*match 3

        Score with groups of three
        (or more) matching pieces.

        Drag adjacent pieces to swap.

        Can only swap to make groups.


        A Game by Richard Jones
        _http://mechanicalcat.net/richard
        <version 1.2.4


        (tap to continue)'''.splitlines()]

        clock = pygame.time.Clock()

        while 1:
            fh = self.font.get_linesize() #+ int(32 * self.dp)
            x = self.screen_width // 2
            y = self.screen_height // 2 - (len(lines) * fh) // 2

            self.screen.fill((230, 230, 230))
            for line in lines:
                if line.startswith('*'):
                    text = self.bold_font.render(line[1:], True, (50, 50, 50))
                elif line.startswith('<'):
                    text = self.small_font.render(line[1:], True, (150, 150, 150))
                else:
                    if line.startswith('_'):
                        line = line[1:]
                        link_rect = pygame.rect.Rect((x - tw//2, y), (tw, th))
                    text = self.font.render(line, True, (50, 50, 50))
                tw, th = text.get_size()
                self.screen.blit(text, (x - tw//2, y))
                y += fh
            pygame.display.flip()

            clock.tick(10)

            if android and android.check_pause():
                self.save_state()
                android.wait_for_resume()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.should_quit = True
                    self.all_dirty = True
                    return
                if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                    self.all_dirty = True
                    return
                if event.type == pygame.MOUSEBUTTONUP:
                    if link_rect.collidepoint(event.pos):
                        webbrowser.open('http://mechanicalcat.net/richard')
                    self.all_dirty = True
                    return
Esempio n. 15
0
    def input(self):
       for event in pygame.event.get():
          if android:
             if android.check_pause():
                android.wait_for_resume()

          if event.type == pygame.KEYDOWN:
             if event.key == pygame.K_ESCAPE:
                self.cancel = True
          if event.type == pygame.QUIT:
             self.next_transition = VALID_STATES['QUIT']

          if event.type == pygame.MOUSEBUTTONDOWN:
             self.user_click = True
             self.player.move()

          if event.type == pygame.MOUSEBUTTONUP:
             self.user_click = False
             self.player.stop()

          if self.user_click:
             (self.cursor_x, self.cursor_y) = pygame.mouse.get_pos()

          if event.type == pygame.USEREVENT + 1:
             self.create_huggable = True

          if event.type == pygame.USEREVENT + 2:
             self.change_angle = True

          if event.type == pygame.USEREVENT + 3:
             self.create_enemy = True
Esempio n. 16
0
    def run(self):
        pygame.init()
        self.load()
        self.gameinput = {
            "singleplayer": input.playerSplitScreen,
            "multiplayer": input.playerOnline
        }

        self.loadMenu()
        gfx.menu.draw()
        while self.running:
            if android:
                if android.check_pause():
                    android.wait_for_resume()
            input.general()
            if not self.inGame:
                input.inMenu(gfx.menu.location)
                gfx.menu.draw()
            else:
                input.inGame()
                self.gameinput[self.mode]()
                if self.settings['game']['hippie']:
                    gfx.game.ball.hippie()
                if gfx.game.playing:
                    if self.mode == "singleplayer":
                        gfx.game.ball.ballEvent()
                gfx.game.draw()

            gfx.newFrame()

        self.quit()
Esempio n. 17
0
def main():
	pygame.init()
	screen = pygame.display.set_mode()
		
	if android:	
		android.init()
		## setup the android exit button
		android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

	## Event constant.
	TIMEREVENT = pygame.USEREVENT
	FPS = 30
	pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

	while True:
	
		ev = pygame.event.wait()

		## Allows Android_OS to take control (ex. pause for phone call) 		
		if android:
			if android.check_pause():
				android.wait_for_resume()
		
		## refresh Screen
		if ev.type == TIMEREVENT:
			pygame.display.flip()
			
		## Draw a blue circle where the screen is touched
		pygame.draw.circle(screen, (0, 128, 255), pygame.mouse.get_pos(), 10)
		
		## Break the while loop to exit if android-back button pressed
		if ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
			break
Esempio n. 18
0
    def _inicia(self,game):
        self.game = game
        pygame.display.set_caption('Trains')
        if android:
            android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
            android.map_key(66, KL.K_PAGEUP)
            android.map_key(67, KL.K_PAGEDOWN)
            android.map_key(23, KL.K_HOME)
            self.text(150,50,'android: %d  escape: %d'%(
                android.KEYCODE_BACK, pygame.K_ESCAPE))
 

        while True:
            ev = pygame.event.wait()
            self._redraw()
            if android:
                if android.check_pause():
                    android.wait_for_resume()

            if ev.type == TIMEREVENT:
                pygame.display.flip()
            elif ev.type == pygame.KEYDOWN:
                if ev.key in (pygame.K_ESCAPE,'q',4):
                    self.terminate()
                    break
                else:
                    self.lidador_de_tecla(ev.key)
                    pygame.display.flip()
Esempio n. 19
0
    def update(self):
        if self.fout and self.alpha <= 0:
            self.old = self.screen.copy()
        if self.fout:
            self.blit(self.old,(0,0))
            self.alpha += self.FPS/self.speed
            self.cover.set_alpha(self.alpha)
            self.screen.blit(self.cover,(0,0))
            if self.alpha >= 255:
                self.fout = False
                self.fin  = True

        if self.fin:
            self.alpha -= self.FPS/self.speed
            self.cover.set_alpha(self.alpha)
            self.screen.blit(self.cover,(0,0))
        if self.fin and self.alpha <= 0:
            self.alpha = 0
            self.fin = False
            
        if android:
            if android.check_pause():
                android.wait_for_resume()

        if self.debug:
            if pygame.mouse.get_pressed()[0]:
                self.mouse = pygame.mouse.get_pos()
            else:
                self.mouse = (0, 0)
        else:
            self.mouse = pygame.mouse.get_pos()

        self.events.update()
        pygame.display.flip()
        self.clock.tick(self.FPS)
Esempio n. 20
0
def main():
    pygame.init()
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_r)
        android.map_key(android.KEYCODE_W, pygame.K_UP)
        android.map_key(android.KEYCODE_A, pygame.K_LEFT)
        android.map_key(android.KEYCODE_D, pygame.K_RIGHT)
        #android.mixer.pre_init(44100, 16, 2, 4096) ##i know this isnt correct
    else:
        os.environ["SDL_VIDEO_CENTERED"] = "1"
        pygame.mixer.pre_init(44100, 16, 2, 4096)
    pygame.font.init()
    clock = pygame.time.Clock()

    game = Game(["server", "client"], levelFile, tilesetFile)
    #--- Main Loop
    while game.on:
        if android:
            if android.check_pause():
                android.wait_for_resume()
        game.tick()
        clock.tick(FPS)
        pygame.display.flip()
    pygame.quit()
    sys.exit()
Esempio n. 21
0
    def run(self):
        self.play_music()
        self.total_time_passed = 0
        fps_limit = 60
        if android:
            fps_limit = 40
        while True:  #main game loop
            if android:
                if android.check_pause():
                    self.pause()
                    #self.pause_music()
                    self.save()
                    print("Block Breaker progress saved!")
                    self.stop_music()
                    android.wait_for_resume()
                    self.pause(resume=True)
                    self.play_music()
                    #self.pause_music(resume=True)
            time_passed = self.clock_getter().tick(fps_limit) / 1000.0
            # If too long has passed between two frames, lie and tell the game it's still at more than 21 FPS (0.046 seconds since last frame)
            # (either the game must have suspended for some reason, in which case we don't want it to "jump forward" suddenly -
            # or the game is running on too weak hardware (single core < 1GHz android phones for example), in which case we'd rather have the game be slow than messing up collision detection)
            if time_passed > 0.046:
                time_passed = 0.046
                #continue
            self.total_time_passed += time_passed
            input = self.process_input()

            self.update(time_passed, input, moveToPos=android)

            self.draw()
Esempio n. 22
0
def main():
    pygame.init()

    print pygame.display.list_modes()
    if not android:
        # Pick a size one smaller than our desktop to save room for WM stuff.
        modes = pygame.display.list_modes()
        if len(modes) > 1: mode = modes[1]
        else: mode = modes[0]
        screen_w, screen_h = mode
    else:
        # Fullscreen always
        _info = pygame.display.Info()
        screen_w = _info.current_w
        screen_h = _info.current_h
    global WIDTH, HEIGHT
    WIDTH = screen_w
    HEIGHT = screen_h

    #This means we must scale everything horizontally by screen_ratio
    global RATIO
    RATIO = WIDTH/HEIGHT

    # Set the screen size.
    pygame.display.set_mode((screen_w, screen_h))

    # Map the back button to the escape key.
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, int(1000 / FPS))

    # Set up our scenegraph
    setup()

    while True:

        ev = pygame.event.wait()

        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            update()
            draw()

        # When the touchscreen is pressed, change the color to green.
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            handle_click()

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
Esempio n. 23
0
def main():
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    respawn = Respawn()
    turn = Turn()
    background = pygame.Surface((DISPLAYHEIGHT, DISPLAYWIDTH))
    drawBoard(background)
    shouldUpdate = 1
    pygame.init()

    pygame.display.set_caption("Keys")

    keys = pygame.Surface((DISPLAYHEIGHT, DISPLAYWIDTH))
    drawKeysOnBoard(keys, BOARD)

    DISP.blit(background, (0, 0))
    DISP.blit(keys, (0, 0))
    while True:

        if android:
            if android.check_pause():
                android.wait_for_resume()

        for event in pygame.event.get():

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

            if event.type == MOUSEBUTTONDOWN:
                handleKeyPress(event, turn, respawn)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
                #for i in SQUARESTOHIGHLIGHT:
                # highlightSquare((i[1],i[0]),DISP,(213,23,12))
            shouldUpdate = 1
        #pygame.display.update()
        shouldUpdate = 1

        if shouldUpdate:
            DISP.blit(background, (0, 0))
            drawLockedKeysOnBoard(DISP, BOARD)
            drawKeysOnBoard(DISP, BOARD)
            for i in ROTATEPOINTS:
                highlightSquare((i[1], i[0]), DISP, (23, 223, 12))
            for i in SQUARESTOHIGHLIGHT:
                highlightSquare((i[1], i[0]), DISP, (213, 23, 12))

            for i in RESPAWNPOINTS:
                highlightSquare((i[1], i[0]), DISP, (233, 34, 223))
            if gameover:
                drawGameOverScreen(DISP, background, winner="none")
            pygame.display.update()
        fpsclock.tick(FPS)
Esempio n. 24
0
    def update(self):
        if android:
            self.controller.update()
            if android.check_pause():
                android.wait_for_resume()

        self.events.update()
        pygame.display.flip()
        self.clock.tick(self.FPS)
Esempio n. 25
0
def main():
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
    respawn = Respawn()
    turn = Turn()
    background = pygame.Surface((DISPLAYHEIGHT,DISPLAYWIDTH))
    drawBoard(background)
    shouldUpdate = 1
    pygame.init()
    
    pygame.display.set_caption("Keys")

    keys = pygame.Surface((DISPLAYHEIGHT,DISPLAYWIDTH))
    drawKeysOnBoard(keys,BOARD)
    
    DISP.blit(background,(0,0))
    DISP.blit(keys,(0,0))
    while True:

        if android:
            if android.check_pause():
                android.wait_for_resume()

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

            if event.type == MOUSEBUTTONDOWN:
                handleKeyPress(event,turn,respawn)

            if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()
                #for i in SQUARESTOHIGHLIGHT:
                   # highlightSquare((i[1],i[0]),DISP,(213,23,12))
            shouldUpdate= 1
        #pygame.display.update()
        shouldUpdate=1
        
        if shouldUpdate:
            DISP.blit(background,(0,0))
            drawLockedKeysOnBoard(DISP,BOARD)
            drawKeysOnBoard(DISP,BOARD)
            for i in ROTATEPOINTS:
                highlightSquare((i[1],i[0]),DISP,(23,223,12))
            for i in SQUARESTOHIGHLIGHT:
                highlightSquare((i[1],i[0]),DISP,(213,23,12))

            for i in RESPAWNPOINTS:
                highlightSquare((i[1],i[0]),DISP,(233,34,223))
            if gameover:
                drawGameOverScreen(DISP,background,winner="none")
            pygame.display.update()
        fpsclock.tick(FPS)
Esempio n. 26
0
def main():

    btn.add(0)
    button2.add(1)
    combo_a.add(2)
    radio_box.add(3)
    switch.add(4)

    btn.level = 1
    level = btn.level
    btn.config_set = True

    screen_color = (50,50,50)

    while True:

        if android:
            if android.check_pause():
                android.wait_for_resume()

        time = clock.tick(30)

        for event in pygame.event.get():
            sgc.event(event)
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

        level = btn.level
        if level == 2:
            if btn.config_set == False:
                screen_color = BLUE
                btn.remove(fade=False)
                radio_box.remove(fade=False)
                combo_a.remove(fade = False)
                scale.remove(fade=False)
                switch.remove(fade=False)
                print("configured 2nd screen settings")
                label.add()
# input of text not working with android soft keyboard
#                inputbox.add()
#                input_ok.add()
                btn.config_set = True
        # if inputbox.has_focus():
        #     if android:
        #         android.show_keyboard()
        # else:
        #     if android:
        #         android.hide_keyboard()

        screen.fill(screen_color)
        sgc.update(time)
        pygame.display.flip()
Esempio n. 27
0
def start_analysis(settings):
	
	"""Prepares the analysis, and runs it (saving data happens while running);
	afterwards the settings are returned
	
	arguments
	
	settings		-	app settings dict, which includes a dict on the task
					properties
	
	returns
	
	settings		-	same settings dict as was passed (updated)
	"""
	
	# get display
	disp = pygame.display.get_surface()
	disp.fill(settings[u'bgc'])
	
	# show loading message
	disp.fill(settings[u'bgc'])
	textsurf = settings[u'font'][u'large'][u'regular'].render(u"running analysis, please wait...", False, settings[u'fgc'])
	disp.blit(textsurf, (int(settings[u'dispcentre'][0]-textsurf.get_width()/2), int(settings[u'dispcentre'][1]-textsurf.get_height()/2)))
	pygame.display.flip()
	
	# prepare new Analysis
	analysis = Analysis(settings)
	
	# run analysis
	analysis.run()
	
	# show ending screen
	disp.fill(settings[u'bgc'])
	textsurf = settings[u'font'][u'large'][u'regular'].render(u"the analysis was succesfully completed", False, settings[u'fgc'])
	disp.blit(textsurf, (int(settings[u'dispcentre'][0]-textsurf.get_width()/2), int(settings[u'dispsize'][1]/3-textsurf.get_height()/2)))
	textsurf = settings[u'font'][u'large'][u'regular'].render(u"(click to return to the main menu)", False, settings[u'fgc'])
	disp.blit(textsurf, (int(settings[u'dispcentre'][0]-textsurf.get_width()/2), int(2*settings[u'dispsize'][1]/3-textsurf.get_height()/2)))
	pygame.display.flip()
	
	# wait for a click (allowing some time to unclick)
	pygame.time.wait(200)
	while check_mouseclicks()[0] == None:
		# allow an Android interrupt
		if settings[u'android']:
			if android.check_pause():
				android.wait_for_resume()	
	
	# switch back to start screen
	settings[u'currentscreen'] = u'start'
	disp.blit(settings[u'guiscreens'][settings[u'currentscreen']], (0,0))
	pygame.display.flip()
	
	# allow a bit of time to unclick
	pygame.time.wait(200)
	
	return settings
Esempio n. 28
0
    def __init__(self, size=(1280, 720), FPS=32):
        pygame.init()
        pygame.display.init()
        
        try:
            info = pygame.display.Info()        
            diag = math.hypot(info.current_w,
                              info.current_h) / android.get_dpi()
            
            width, height = (info.current_w, info.current_h)
            self.scale_width = width / float(size[0])
            self.scale_height = height / float(size[1])
            self.screen = pygame.display.set_mode((width, height))

            print(width, height, size)
            print(self.scale_width, self.scale_height)
            
        except AttributeError:
            self.screen = pygame.display.set_mode(size)
            self.scale_width = 1
            self.scale_height = 1

        if android:
            android.init()

        self.red  = pygame.color.Color('red')
        self.black  = pygame.color.Color('black')
        self.width  = self.screen.get_width()
        self.height = self.screen.get_height()
        self.clock  = pygame.time.Clock()
        self.FPS    = FPS
        self.image  = Image()
        self.audio  = Audio()
        self.events = EventHandler()
        self.controller = OuyaController()

        self.safe_percentage = 0.05
        self.vertical_safe_zone = pygame.Surface((int(self.width * self.safe_percentage), int(self.height)))
        self.vszwidth = self.vertical_safe_zone.get_width()
        self.vszheight = self.vertical_safe_zone.get_height() * self.safe_percentage
        self.horizontal_safe_zone = pygame.Surface((int(self.width - 2 * self.vszwidth), int(self.vszheight)))

        self.sz_left = (0,0)
        self.sz_right = (self.width / self.scale_width - self.vszwidth / self.scale_width, 0)
        self.sz_up = (self.vszwidth / self.scale_width, 0)
        self.sz_down = (self.vszwidth / self.scale_width,
                        self.height / self.scale_height - self.vszheight / self.scale_height)

        self.vertical_safe_zone.fill(self.red)
        self.vertical_safe_zone.set_alpha(92)
        self.horizontal_safe_zone.fill(self.red)
        self.horizontal_safe_zone.set_alpha(92)
        
        if android:
            if android.check_pause():
                android.wait_for_resume()
Esempio n. 29
0
 def show(self):
     while self.running:
         self.draw()
         display.flip()
         self.clock.tick(FPS)
         for event in pygame.event.get():
             self.handle_event(event)
         if android:
             if android.check_pause():
                 android.wait_for_resume()
Esempio n. 30
0
File: me.py Progetto: bluepeppers/me
 def show(self):
     while self.running:
         self.draw()
         display.flip()
         self.clock.tick(FPS)
         for event in pygame.event.get():
             self.handle_event(event)
         if android:
             if android.check_pause():
                 android.wait_for_resume()
Esempio n. 31
0
    def process(self):
        global on_android
        self.clock.tick(self._fps)

        # Android-specific:
        if on_android:
            if android.check_pause():
                android.wait_for_resume()

        self._dirty_rects = []

        if not self.appstate:
            raise Exception("AppState is None")

        p = self.appstate.process()
        if p:
            next_state, state_arg = p
            if next_state:
                if next_state == "GoodBye":
                    self.is_running = False
                else:
                    # appstate wants to change!
                    self.appstate = self._get_appstate(next_state)
                    self.appstate.resume(state_arg)

        events = pygame.event.get()
        for event in events:
            try:  # hack to enable fullscreen coordinates
                pos_x, pos_y = event.pos
                event.pos = tuple([pos_x - self.x, pos_y - self.y])
            except:
                #print "silly event:", event
                pass
            p = self.appstate.process_input(event)

            # ESC quits app
            if event.type == pygame.QUIT:
                self.is_running = False

        ## DRAW
        self.appstate.draw()

        # write fps
        if "font" in self.__dict__:
            fps_surf = self.font.render("FPS: %2.2f" % self.clock.get_fps(),
                False, (255, 255, 255), (0, 0, 0))
            self.dirty(self.screen.blit(fps_surf, (0, 0)))

        if self.b_fullscreen:
            self.x = self.fullscreen.get_width() / 2 - self.screen.get_width() / 2
            self.y = self.fullscreen.get_height() / 2 - self.screen.get_height() / 2
            self.fullscreen.blit(self.screen, (self.x, self.y))

        pygame.display.update(self._dirty_rects)
        pygame.event.pump()
Esempio n. 32
0
	def run(self):
		global mute_music
		if pygame.display.get_init():
			self.final_display=pygame.display.get_surface()
		elif not self.final_display: 
			pygame.init()
			pygame.display.init()
			new_size=(int(self.size[0]*self.resize_scale[0]),int(self.size[1]*self.resize_scale[1]) )
			self.final_display=pygame.display.set_mode(new_size,RESIZABLE if not self.full_screen else FULLSCREEN)
			debugLog('\t>>pygame.display.set_mode()')
		self.pre_display=pygame.Surface(self.size)
		fps_clock=pygame.time.Clock()
		pygame.display.set_caption(self.title)
		self.preEvents()
		if self.play: self.startMusic()
		while self.running and not self.stored_screen:
			if android :
				if self.music: mixer.periodic()
				if android.check_pause ():
					debugLog("pause")
					mixer.music.stop()
					debugLog("\tparou musica")
					android.wait_for_resume ()
					self.startMusic()
					debugLog("\tiniciou musica")
					debugLog("unpause")
			debugLogSuper('\t\tInicio passagem')
			if self.show_fps: pygame.display.set_caption(self.title+" - "+str(int(fps_clock.get_fps()))+":"+str(self.fps))
			for event in pygame.event.get():
				if event.type==KEYUP:
					if event.key==K_q:
						self.function(*self.args)
				if event.type==QUIT and not android:
					self.closeGame()
				if event.type==VIDEORESIZE:
					self.setNewSizeScale((event.w,event.h))
					new_size=(int(self.size[0]*self.resize_scale[0]),int(self.size[1]*self.resize_scale[1]))
					self.final_display = pygame.display.set_mode(new_size,RESIZABLE)
			
				self.eventControler(event,self.resize_scale)

			self.stored_screen=self.screenCall()
			
			self.makeBlitOn(fps_clock)
			self.screenManipulation(self)
			pygame.display.flip()
			fps_clock.tick(self.fps)
			debugLogSuper('\t\tFim passagem')
		self.posEvents()
		if self.loading_image:
			self.blitBg(self.pre_display)
			try:self.pre_display.blit(self.loading_image,self.loading_pos)
			except Exception,e:debugLog(e)
			pygame.transform.scale(self.pre_display if self.rotate==0 else pygame.transform.rotate(self.pre_display.convert(),self.rotate),(int(self.size[0]*self.resize_scale[0]),int(self.size[1]*self.resize_scale[1])),self.final_display)
			pygame.display.flip()
Esempio n. 33
0
 def gameLoop(self):
     while self.running:
         # Android-specific:
         if android:
             if android.check_pause():
                 android.wait_for_resume()
     
         if self.section:
             self.drawSelectionScreen(self.section)
         self.clock.tick(vinfo.framerate)
         self.handleEvents()
Esempio n. 34
0
   def update(self):
 
           if android:
               if android.check_pause():
                   android.wait_for_resume()
                     
           self.fps_clock.tick(60)
           mpos = pygame.mouse.get_pos()
 
             
             
           for evt in pygame.event.get():
               if evt.type == pygame.QUIT:
                   program_quit()
                     
               elif evt.type == pygame.MOUSEBUTTONDOWN:
                   if evt.button == 1:
                       self.evm.post(ev.LMBDOWN(mpos))
                     
                   if android:
                       self.evm.post(ev.MOUSEDRAG())
                         
                   if evt.button == 3:
                       self.evm.post(ev.RMBDOWN(mpos))
 
               elif evt.type == pygame.MOUSEBUTTONUP:
                   if evt.button == 1:
                       self.evm.post(ev.LMBUP(mpos))
                   elif evt.button == 3:
                       self.evm.post(ev.RMBUP(mpos))
 
               elif evt.type == pygame.MOUSEMOTION:
                   if pygame.mouse.get_pressed()[0]:
                       self.evm.post(ev.MOUSEDRAG(evt.pos))
                         
 
               elif evt.type == pygame.KEYDOWN:
                   if evt.key == pygame.K_ESCAPE:
                       program_quit()
                   elif evt.key == pygame.K_RETURN:
                       self.evm.post(ev.StartGame())
                   elif evt.key == pygame.K_SPACE:
                       self.evm.post(ev.ClearGame())
                       self.evm.post(ev.StartGame())
                         
                   if evt.key in constants.valid_hotkeys:
                       if not pygame.key.get_pressed()[pygame.K_LCTRL]:
                           self.evm.post(ev.SelectHotkey(evt.key))
                             
           #Check to set hotkeys every frame.
           if pygame.key.get_pressed()[pygame.K_LCTRL]:
               for key in constants.valid_hotkeys:
                   if pygame.key.get_pressed()[key]:
                       self.evm.post(ev.SetHotkey(mpos, key))
Esempio n. 35
0
    def play(self):
        while True:
            self.clock.tick(1000/FPS)
          
            # Android-specific:
            if android:
              if android.check_pause():
                android.wait_for_resume()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                  return False
                
                if event.type == pygame.KEYDOWN:
                        if event.key == pygame.K_LEFT:
                          pass
                        elif event.key == pygame.K_RIGHT:
                          pass
                        elif event.key == pygame.K_ESCAPE:
                          return True

            if android:
              a = android.accelerometer_reading()
              #self.debug_text = "%f" % a[0]

            ## did the ball hit a brick or paddle?
            for ball in self.balls:
                hit = pygame.sprite.spritecollide(ball, self.obstacles, False)
                if hit:
                  if hit[0].type == "paddle":
                    ball.vy = -ball.vy
                  elif hit[0].type == "brick":
                    ball.vy = -ball.vy
                    self.points = self.points + 10
                    self.obstacles.remove(hit)
                    self.splat.play()
                    self.count = self.count - 1
                    if self.count <= 0:
                        ## level complete
                        self.level = self.level + 1
                        self.init()

                ## did the ball hit the top of the screen?
                if ball.rect.y < self.border:
                  ball.vy = ball.vy * 1.5
                  ball.vy = -ball.vy

                ## did the ball hit the bottom of the screen?
                if ball.rect.y > self.screen_height:
                  self.balls = []
                  return True

            self.score_text = self.font.render("Score: " + str(self.points), 1, (255,255,255))
            self.animate()
Esempio n. 36
0
    def event(self, e):
        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        #capture special events on a top level,
        #should only be used for screen shots, forced quits,
        #magic cheat buttons, etc... debug keys and the like ...
        if e.type is QUIT:
            self.state = engine.Quit(self)
            return 1
Esempio n. 37
0
    def event(self, e):
        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # capture special events on a top level,
        # should only be used for screen shots, forced quits,
        # magic cheat buttons, etc... debug keys and the like ...
        if e.type is QUIT:
            self.state = engine.Quit(self)
            return 1
Esempio n. 38
0
    def run(self):
        if self.settings.standalone:
            self.game.start()

        while True:
            self.handler()
            self.draw()
            pygame.display.flip()
            
            if android:
                if android.check_pause():
                    android.wait_for_resume()
Esempio n. 39
0
def check_events():
    """ Check android-specific pause event. """
    if android.check_pause():
        android.hide_keyboard()
        # save emulator state
        state.console_state.screen.save_state()
        state.save()
        state.console_state.screen.clear_saved_state()
        # hibernate; we may not wake up
        android.wait_for_resume()
        return True
    return False
Esempio n. 40
0
    def run(self):
        if self.settings.standalone:
            self.game.start()

        while True:
            self.handler()
            self.draw()
            pygame.display.flip()

            if android:
                if android.check_pause():
                    android.wait_for_resume()
Esempio n. 41
0
def check_events():
    """ Check android-specific pause event. """
    if android.check_pause():
        android.hide_keyboard()
        # save emulator state
        state.console_state.screen.save_state()
        state.save()
        state.console_state.screen.clear_saved_state()
        # hibernate; we may not wake up
        android.wait_for_resume()
        return True
    return False
Esempio n. 42
0
def main():
    pygame.init()
    if android:
        android.init()

        android.mixer.music.load("click.wav")
        android.mixer.music.play(-1)

    # Set the screen size.
    screen = pygame.display.set_mode((480, 800))

    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill(color)
            pygame.display.flip()
            android.mixer.periodic()

        # When the touchscreen is pressed, change the color to green.
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.25)
                print "Open URL Version 2"
                webbrowser.open("http://www.renpy.org/")

        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
Esempio n. 43
0
def main():

    pygame.init()
    if android:
        android.init()
     
    # Set the screen size.
    screen = pygame.display.set_mode((480, 800), pygame.FULLSCREEN)

    test = pygame.image.load("test.jpg").convert()
    test.set_alpha(128)
    
    
    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    # The color of the screen.
    color = RED

    while True:

        ev = pygame.event.wait()

        # Android-specific: 
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill(color)
            screen.blit(test, (100, 100))
            pygame.display.flip()

        # When the touchscreen is pressed, change the color to green. 
        elif ev.type == pygame.MOUSEBUTTONDOWN:
            color = GREEN
            if android:
                android.vibrate(.25)
            
        # When it's released, change the color to RED.
        elif ev.type == pygame.MOUSEBUTTONUP:
            color = RED

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
Esempio n. 44
0
    def android_check_pause(*largs):
        # do nothing until android asks for it.
        if not android.check_pause():
            return

        from kivy.app import App
        from kivy.base import stopTouchApp
        from kivy.logger import Logger
        from kivy.core.window import Window
        global g_android_redraw_count, _redraw_event

        # try to get the current running application
        Logger.info('Android: Must go into sleep mode, check the app')
        app = App.get_running_app()

        # no running application, stop our loop.
        if app is None:
            Logger.info('Android: No app running, stop everything.')
            stopTouchApp()
            return

        # try to go to pause mode
        if app.dispatch('on_pause'):
            Logger.info('Android: App paused, now wait for resume.')

            # app goes in pause mode, wait.
            android.wait_for_resume()

            # is it a stop or resume ?
            if android.check_stop():
                # app must stop
                Logger.info('Android: Android wants to close our app.')
                stopTouchApp()
            else:
                # app resuming now !
                Logger.info('Android: Android has resumed, resume the app.')
                app.dispatch('on_resume')
                Window.canvas.ask_update()
                g_android_redraw_count = 25  # 5 frames/seconds for 5 seconds
                if _redraw_event is None:
                    _redraw_event = Clock.schedule_interval(
                        _android_ask_redraw, 1 / 5)
                else:
                    _redraw_event.cancel()
                    _redraw_event()
                Logger.info('Android: App resume completed.')

        # app doesn't support pause mode, just stop it.
        else:
            Logger.info('Android: App doesn\'t support pause mode, stop.')
            stopTouchApp()
Esempio n. 45
0
def init_display(experiment):
    """See openexp._canvas.legacy"""

    if experiment.resolution() != resolution:
        raise canvas_error( \
        'The droid back-end requires a resolution of %d x %d. Your display will be scaled automatically to fit devices with different resolutions.' \
        % resolution)

    # Intialize PyGame
    if not pygame.display.get_init():
        pygame.init()
    experiment.window = pygame.display.set_mode(resolution)
    experiment.surface = pygame.display.get_surface()
    # Set the time functions to use pygame
    experiment._time_func = pygame.time.get_ticks
    experiment._sleep_func = pygame.time.delay
    experiment.time = experiment._time_func
    experiment.sleep = experiment._sleep_func
    # Initialze the Android device if necessary
    if android != None:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
        dpi = android.get_dpi()
    else:
        # A dummy dpi if we are not on Android
        dpi = 96
    # Log the device characteristics
    info = pygame.display.Info()
    diag = hypot(info.current_w, info.current_h) / dpi
    if diag < 6:  # 6" is the minimum size to be considered a tablet
        is_tablet = 'yes'
    else:
        is_tablet = 'no'
    experiment.set('device_resolution_width', info.current_w)
    experiment.set('device_resolution_height', info.current_h)
    experiment.set('device_dpi', dpi)
    experiment.set('device_screen_diag', diag)
    experiment.set('device_is_tablet', is_tablet)

    # Start with a splash screen
    splash = pygame.image.load(experiment.resource('android-splash.jpg'))
    x = resolution[0] / 2 - splash.get_width() / 2
    y = resolution[1] / 2 - splash.get_height() / 2
    experiment.surface.blit(splash, (x, y))
    for i in range(10):
        pygame.display.flip()
        pygame.time.delay(100)
    if android != None and android.check_pause():
        android.wait_for_resume()
Esempio n. 46
0
def checkForQuit():
    """Sometimes we want to check the event queue for any QUIT events (or if the player has specifically pressed the Esc key to quit), but we don't care about any other events (such as mouse movements or clicks). By passing QUIT to the pygame.event.get() call, we return only QUIT events."""
    for event in pygame.event.get(QUIT):
        terminate()

    for event in pygame.event.get(KEYUP):
        if event.key == K_ESCAPE:
            terminate()
        """We'll go through the events in the event queue again, this time only looking at KEYUP events (which happen when the player lets go of a keyboard key). If the key they pressed was the Esc key, we'll quit the program."""
        pygame.event.post(event)
        """If the key was not the escape key, then we want to return the KEYUP event to the event queue by calling pygame.event.post(). This ensures that we don't take out any, say, arrow key presses and then not handle them. The code in the main() function will later pick up these keyboard events, and properly handle them."""

    # Whenever we check for quit, we also want to check for an Android pause.
    if android is not None and android.check_pause():
        android.wait_for_resume()
Esempio n. 47
0
 def event(self):
     for event in pygame.event.get():
         if event.type == QUIT:
             pygame.quit()
             sys.exit()
         if event.type == KEYDOWN:
             if event.key == K_ESCAPE:
                 pygame.quit()
                 sys.exit()
         if event.type == MOUSEBUTTONDOWN:
             self.degree = 0 # 셔틀이 더이상 회전하지 않음
             self.launchMode = True # 발사 여부를 True로 변환
             self.fuelMode = 'launch'
         if android:
             if android.check_pause():
                 android.wait_for_resume()
Esempio n. 48
0
    def show(self):
        self.spiral.prepare()
        self.start_music()
        self.logic.change_color(0)

        while self.logic.running:
            for event in pygame.event.get():
                self.logic.handle_event(event)
            self.update()

            self.draw_all()
            display.flip()
            self.clock.tick(FPS)

            if android:
                if android.check_pause():
                    android.wait_for_resume()
Esempio n. 49
0
    def get_key(self, keylist=None, timeout=None):

        if not self.persistent_virtual_keyboard and android != None:
            android.show_keyboard()
        start_time = pygame.time.get_ticks()
        time = start_time
        if keylist == None:
            keylist = self._keylist
        if timeout == None:
            timeout = self.timeout
        while True:
            time = pygame.time.get_ticks()
            for event in pygame.event.get():
                if event.type != pygame.KEYDOWN:
                    continue
                if event.key == pygame.K_ESCAPE:
                    raise osexception("The escape key was pressed.")
                # TODO The unicode mechanism that ensures compatibility between
                # keyboard layouts doesn't work for Android, so we use key
                # names. I'm not sure what effect this will have on non-QWERTY
                # virtual keyboards.
                if android != None:
                    key = pygame.key.name(event.key)
                    if len(key) == 1 and (event.mod & pygame.KMOD_LSHIFT or \
                     event.mod & pygame.KMOD_RSHIFT):
                        key = key.upper()
                else:
                    # If we're not on Android, simply use the same logic as the
                    # legacy back-end.
                    if event.unicode in invalid_unicode:
                        key = self.key_name(event.key)
                    else:
                        key = event.unicode
                if keylist == None or key in keylist:
                    if not self.persistent_virtual_keyboard and android != None:
                        android.hide_keyboard()
                    return key, time
            if timeout != None and time - start_time >= timeout:
                break
            # Allow Android interrupt
            if android != None and android.check_pause():
                android.wait_for_resume()
        if not self.persistent_virtual_keyboard and android != None:
            android.hide_keyboard()
        return None, time
Esempio n. 50
0
def main():
    pygame.init()
    if android:
        android.init()

    # Set the screen size.
    screen = pygame.display.set_mode((480, 800))

    # Map the back button to the escape key.
    if android:
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
        android.accelerometer_enable(True)

    # Use a timer to control FPS.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    font = pygame.font.Font("FreeSans.ttf", 30)

    def text(s, x, y):
        surf = font.render(s, True, (200, 200, 200, 255))
        screen.blit(surf, (x, y))

    while True:

        ev = pygame.event.wait()

        if android.check_pause():
            android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            x, y, z = android.accelerometer_reading()

            screen.fill((0, 0, 0, 255))

            text("X: %f" % x, 10, 10)
            text("Y: %f" % y, 10, 50)
            text("Z: %f" % z, 10, 90)

            pygame.display.flip()

        # When the user hits back, ESCAPE is sent. Handle it and end
        # the game.
        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
Esempio n. 51
0
	def init_display(experiment):

		if experiment.resolution() != resolution:
			raise osexception(
				(u'The droid back-end requires a resolution of %d x %d. Your '
				u'display will be scaled automatically to fit devices with '
				u'different resolutions.') % resolution
			)
		# Intialize PyGame
		if not pygame.display.get_init():
			pygame.init()
		experiment.window = pygame.display.set_mode(resolution)
		experiment.surface = pygame.display.get_surface()
		# Set the time functions to use pygame
		experiment._time_func = pygame.time.get_ticks
		experiment._sleep_func = pygame.time.delay
		experiment.time = experiment._time_func
		experiment.sleep = experiment._sleep_func
		# Initialze the Android device if necessary
		if android is not None:
			android.init()
			android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)
			dpi = android.get_dpi()
		else:
			# A dummy dpi if we are not on Android
			dpi = 96
		# Log the device characteristics
		info = pygame.display.Info()
		diag = hypot(info.current_w, info.current_h) / dpi
		experiment.var.device_resolution_width = info.current_w
		experiment.var.device_resolution_height = info.current_h
		experiment.var.device_dpi = dpi
		experiment.var.device_screen_diag = diag
		experiment.var.device_is_tablet = u'yes' if diag >= 6 else u'no'
		# Start with a splash screen
		splash = pygame.image.load(experiment.resource('android-splash.jpg'))
		x = resolution[0]/2 - splash.get_width()/2
		y = resolution[1]/2 - splash.get_height()/2
		experiment.surface.blit(splash, (x, y))
		for i in range(10):
			pygame.display.flip()
			pygame.time.delay(100)
		if android is not None and android.check_pause():
			android.wait_for_resume()
Esempio n. 52
0
    def get_click(self):

        if android is None:
            pygame.mouse.set_visible(self.visible)
        buttonlist = self.buttonlist
        timeout = self.timeout
        enable_escape = self.experiment.var.get(u'enable_escape', u'no',
                                                [u'yes', u'no']) == u'yes'
        start_time = pygame.time.get_ticks()
        time = start_time
        while True:
            time = pygame.time.get_ticks()
            # Process the input
            for event in pygame.event.get():
                if event.type == KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.experiment.pause()
                        continue
                    pygame.event.post(event)
                if event.type == MOUSEBUTTONDOWN:
                    # Check escape sequence. If the top-left and top-right
                    # corner are clicked successively within 2000ms, the
                    # experiment is aborted
                    if enable_escape and event.pos[0] < 64 and event.pos[1] \
                     < 64:
                        _time = pygame.time.get_ticks()
                        while pygame.time.get_ticks() - _time < 2000:
                            for event in pygame.event.get():
                                if event.type == MOUSEBUTTONDOWN:
                                    if event.pos[0] > \
                                     self.experiment.var.width-64 and \
                                     event.pos[1] < 64:
                                        raise osexception(
                                            u"The escape sequence was clicked/ tapped"
                                        )
                    if buttonlist is None or event.button in buttonlist:
                        return event.button, self.from_xy(event.pos), time
            if timeout is not None and time - start_time >= timeout:
                break
            # Allow Android interrupt
            if android is not None and android.check_pause():
                android.wait_for_resume()
        return None, None, time
Esempio n. 53
0
def main():
    pygame.init()

    info = pygame.display.Info()

    # Set the screen size.
    screen = pygame.display.set_mode((info.current_w, info.current_h))

    # Map the back button to the escape key.
    if android:
        android.init()
        android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE)

    # Use a timer to ensure the Android events get regularly
    # called.
    pygame.time.set_timer(TIMEREVENT, 1000 / FPS)

    im = pygame.image.load(android.assets.open("icon.png"))
    w, h = im.get_size()

    x = -w
    y = -h

    while True:

        ev = pygame.event.wait()

        # Android-specific:
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Draw the screen based on the timer.
        if ev.type == TIMEREVENT:
            screen.fill((0, 0, 0, 0))
            screen.blit(im, (x - w / 2, y - h / 2))
            pygame.display.flip()

        if ev.type == pygame.MOUSEBUTTONDOWN:
            x, y = ev.pos

        elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE:
            break
Esempio n. 54
0
def main():
    while True:
        # A PGS4A program must include these two lines
        if android.check_pause():
            android.wait_for_resume()

        time = clock.tick(30)

        for event in pygame.event.get():
            sgc.event(event)
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                # Alternate way to exit the program in Android - back button
                sys.exit()

        screen.fill((0, 0, 0))
        sgc.update(time)
        pygame.display.flip()
Esempio n. 55
0
    def android_check_pause(*largs):
        # do nothing until android ask for it.
        if not android.check_pause():
            return

        from kivy.app import App
        from kivy.base import stopTouchApp
        from kivy.logger import Logger
        from kivy.core.window import Window

        # try to get the current running application
        Logger.info('Android: Must to in sleep mode, check the app')
        app = App.get_running_app()

        # no running application, stop our loop.
        if app is None:
            Logger.info('Android: No app running, stop everything.')
            stopTouchApp()
            return

        # try to go to pause mode
        if app.dispatch('on_pause'):
            Logger.info('Android: App paused, now wait for resume.')

            # app goes in pause mode, wait.
            android.wait_for_resume()

            # is it a stop or resume ?
            if android.check_stop():
                # app must stop
                Logger.info('Android: Android want to close our app.')
                stopTouchApp()
            else:
                # app resuming now !
                Logger.info('Android: Android resumed, resume the app')
                app.dispatch('on_resume')
                Window.canvas.ask_update()
                Logger.info('Android: App resume completed.')

        # app don't support pause mode, just stop it.
        else:
            Logger.info('Android: App doesn\'t support pause mode, stop.')
            stopTouchApp()
Esempio n. 56
0
    def get_click(self, buttonlist=None, timeout=None, visible=None):
        """See openexp._mouse.legacy"""

        if android == None:
            pygame.mouse.set_visible(True)
        if buttonlist == None:
            buttonlist = self.buttonlist
        if timeout == None:
            timeout = self.timeout
        if visible == None:
            visible = self.visible
        enable_escape = self.experiment.get_check('enable_escape', 'no', \
         ['yes', 'no']) == 'yes'
        start_time = pygame.time.get_ticks()
        time = start_time
        while timeout == None or time - start_time < timeout:
            time = pygame.time.get_ticks()
            # Process the input
            for event in pygame.event.get():
                if event.type == KEYDOWN and event.key == pygame.K_ESCAPE:
                    raise openexp.exceptions.response_error( \
                     "The escape key was pressed.")
                if event.type == MOUSEBUTTONDOWN:
                    # Check escape sequence. If the top-left and top-right
                    # corner are clicked successively within 2000ms, the
                    # experiment is aborted
                    if enable_escape and event.pos[0] < 64 and event.pos[1] \
                     < 64:
                        _time = pygame.time.get_ticks()
                        while pygame.time.get_ticks() - _time < 2000:
                            for event in pygame.event.get():
                                if event.type == MOUSEBUTTONDOWN:
                                    if event.pos[0] > self.experiment.get( \
                                     'width')-64 and event.pos[1] < 64:
                                        raise openexp.exceptions.response_error( \
                                         "The escape sequence was clicked/ tapped")
                    if buttonlist == None or event.button in buttonlist:
                        return event.button, event.pos, time
            # Allow Android interrupt
            if android != None and android.check_pause():
                android.wait_for_resume()
        return None, None, time
Esempio n. 57
0
    def update(self, dt):

        if (android):
            if android.check_pause():
                if (self.musicaTema.state == "play"):
                    self.musicaTema.stop()
                android.wait_for_resume()

        if (self.soundOn is True):
            if (self.musicaTema.state == "stop"):
                self.musicaTema.play()
                self.musicaTema.volume = 0.3
        else:
            if (self.musicaTema.state == "play"):
                self.musicaTema.stop()
                self.musicaTema.volume = 0.3

        if (self.gamePause is not True):
            self.__movingPlayerAndroid()
            self.updateNivel(dt)
Esempio n. 58
0
def wait_event():
    # Wait for input, then return it when it comes.
    ev = pygame.event.wait()

    # Android-specific:
    if android:
        if android.check_pause():
            android.wait_for_resume()

    # Record if a quit event took place
    if ev.type == pygame.QUIT:
        global GOT_QUIT
        GOT_QUIT = True
    elif ev.type == TIMEREVENT:
        pygame.event.clear(TIMEREVENT)

    elif ev.type == pygame.KEYDOWN and ev.key == pygame.K_PRINT:
        screen = pygame.display.get_surface()
        pygame.image.save(screen, util.user_dir("out.png"))

    return ev
Esempio n. 59
0
    def main_loop(self):
        """Main loop for entire game. This method gets execute every frame
        by Asteria Networking's "listen()" function. Every frame we get the
        amount of time that has passed each frame, check game conditions,
        and draw the game to the screen.

        :param None:

        :rtype: None
        :returns: None

        """

        # Android-specific check for pause
        if android:
            if android.check_pause():
                android.wait_for_resume()

        # Get the amount of time that has passed since the last frame.
        time_delta = self.clock.tick(self.fps) / 1000.0
        self.time_passed_seconds = time_delta
        self.event_loop()

        # Run our event engine which will check to see if game conditions
        # are met and run an action associated with that condition.
        self.event_data = {}
        self.event_engine.check_conditions(self, time_delta)
        logger.debug("Event Data:" + str(self.event_data))

        # Draw and update our display
        self.update(time_delta)
        pg.display.update()
        if self.show_fps:
            fps = self.clock.get_fps()
            with_fps = "{} - {:.2f} FPS".format(self.caption, fps)
            pg.display.set_caption(with_fps)
        if self.exit:
            self.done = True
Esempio n. 60
0
    def update(self):
        # check for android pause event
        if android:
            if android.check_pause():
                android.wait_for_resume()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.direction = "up"
                elif event.key == pygame.K_DOWN:
                    self.direction = "down"
                elif event.key == pygame.K_LEFT:
                    self.direction = "left"
                elif event.key == pygame.K_RIGHT:
                    self.direction = "right"
                elif event.key == pygame.K_SPACE:
                    self.jump = True
            if event.type == pygame.MOUSEBUTTONDOWN:
                self.game_buttons()
        self.mouse_direction()