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()
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()
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()
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())
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)
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
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
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
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()
def opening_scene(screen): pygame.display.flip() opening_widget = OpeningWidget() version_widget = VersionWidget() rockwell_widget = RockwellWidget() clock = pygame.time.Clock() running = True while running: if android: if android.check_pause(): print "@@@@ pausing" running = False quit_game = True for event in pygame.event.get(): if event.type == pygame.QUIT: running = False quit_game = True elif ( event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.KEYDOWN ): running = False quit_game = False ms_elapsed = clock.tick(TICK) pygame.event.pump() opening_widget.draw(screen) version_widget.draw(screen) rockwell_widget.draw(screen) pygame.display.flip() return quit_game
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
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
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
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
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()
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
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
def is_paused(): if is_android: if features.get("app.disable_android_pause"): return False else: return android.check_pause() else: return sig_state == PAUSED
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)
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)
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()
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()
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
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()
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()
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()
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()
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))
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()
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
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()
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 # 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 Clock.unschedule(_android_ask_redraw) Clock.schedule_interval(_android_ask_redraw, 1 / 5) 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()
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) # 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() # 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
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()
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
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
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()
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
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
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()
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()
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
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)
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
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 my_state.is_key_for_action(ev, "next_widget"): my_state.active_widget_hilight = True my_state.activate_next_widget(ev.mod & pygame.KMOD_SHIFT) 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 my_state.widget_responded = False if my_state.widgets_active: for w in my_state.widgets: w.respond_event(ev) # If the view has a check_event method, call that. if my_state.view and hasattr(my_state.view, "check_event"): my_state.view.check_event(ev) return ev
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
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()
def main(self): # start us off with a blank slate self.screen.fill((230, 230, 230)) for name in SHAPES: IMAGES[name] = pygame.image.load(DATADIR + '%s-%s.png' % (name, self.icon_size)) self.cross = pygame.image.load(DATADIR + 'cross-%s.png' % self.icon_size) for name in ACTIONS: IMAGES[name] = pygame.image.load(DATADIR + '%s/%s.png' % (self.density, name)) clock = pygame.time.Clock() # add 8dp on either side of the action icon/text action_icon_pad = int(8 * self.dp) action_line_height = self.action_icon_size + action_icon_pad * 2 # figure the height of the remaining area to work with - balance the # bottom action line with another spacing of the same height at the top remain = self.screen_height - action_line_height * 2 play_height = self.icon_size * 8 score_height = action_line_height # this remaining area holds the play area and score (an # action_line_height); determine padding to space the two evenly pad = remain - play_height - score_height pad //= 3 # determine the play area size and thus the positioning of it self.play_y_offset = action_line_height + pad score_y = self.play_y_offset + self.icon_size * 8 + pad self.play_x_offset = self.screen_width // 2 - (self.icon_size * 8) // 2 for n in range(8): # force using dirty for update 'cos the other method is busted g = ColumnGroup(_use_update=True) g.set_timing_treshold(1000.) g.x = self.play_x_offset + n * self.icon_size g.set_clip(self.screen.get_clip()) self.columns.append(g) self.load_state() # generate the background image background = pygame.surface.Surface( (self.screen_width, self.screen_height - 2 * action_line_height)) background.fill((230, 230, 230)) # check we've not loaded a game over game if self.grid_complete_and_settled and self.is_game_over(): self.game_over = True if not self.splash_shown: self.splash_shown = True self.do_about() # group for collecting effects being drawn self.effects_group = pygame.sprite.Group() bad_swap_text = self.small_font.render('Must swap to make a group', True, (255, 68, 68)) not_adjacent_text = self.small_font.render('Must swap adjacent shapes', True, (255, 68, 68)) reset_clickable = None while not self.should_quit: if android and android.check_pause(): self.save_state() android.wait_for_resume() # update, but limit the step just in case we were paused or # something dt = min(.1, clock.tick(30) / 1000.) self.update(dt) for event in pygame.event.get(): if event.type == pygame.QUIT: self.should_quit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.should_quit = True if __debug__: if event.mod & pygame.KMOD_CTRL and event.key == pygame.K_s: pygame.image.save(self.screen, 'screenshot.png') if event.mod & pygame.KMOD_CTRL and event.key == pygame.K_g: self.game_over = True if event.type == pygame.MOUSEBUTTONUP: for sprite in self.action_bar.sprites(): if sprite.rect.collidepoint(event.pos): sprite.action() if self.game_over: if reset_clickable is not None and \ reset_clickable.collidepoint(event.pos): self.reset() else: self.mouse_up(event.pos) if self.game_over: continue if event.type == pygame.MOUSEBUTTONDOWN: self.mouse_down(event.pos) if event.type == pygame.MOUSEMOTION: self.mouse_motion(event.pos) if self.all_dirty: self.screen.fill((230, 230, 230)) for column in self.columns: for sprite in column._spritelist: sprite.dirty = 1 # action bar background action_bar_top = self.screen_height - action_line_height self.screen.fill((200, 200, 200), ((0, action_bar_top), (self.screen_width, action_line_height))) # add the action icons self.action_bar = pygame.sprite.Group() # right-align w = IMAGES['2_action_about'].get_size()[0] x = self.screen_width - action_icon_pad - w y = action_bar_top + action_icon_pad ActionSprite((x, y), IMAGES['2_action_about'], self.do_about, self.action_bar) self.action_bar.draw(self.screen) for column in self.columns: column.draw(self.screen, background) self.effects_group.draw(self.screen) # update score if self.all_dirty or self.score_changed: # render the text and determine its dimensions text = thousands(self.score) text = self.font.render('Score: ' + text, True, (50, 50, 50)) tw, th = text.get_size() # draw the background to clear previous text r = pygame.rect.Rect((0, score_y), (self.screen_width, pad)) self.screen.fill((230, 230, 230), r) # center the text in the middle of that rect self.screen.blit(text, (self.screen_width // 2 - tw // 2, score_y + score_height // 2 - th // 2)) if self.score == self.high_score: text = self.small_font.render('HIGH SCORE', True, (150, 150, 150)) tw, th = text.get_size() y = score_y + score_height // 2 + th // 2 self.screen.blit( text, (self.screen_width // 2 - tw // 2, y + th)) self.score_changed = False if self.bad_swap_text_life > 0: btw, bth = bad_swap_text.get_size() r = pygame.rect.Rect( (self.screen_width // 2 - btw // 2, pad // 2 - bth // 2), (btw, bth)) self.screen.fill((230, 230, 230), r) # clear block text from display if game over if self.game_over: self.bad_swap_text_life = 0 else: # retain text for 4 seconds self.bad_swap_text_life -= dt if self.bad_swap_text_life > 0: self.screen.blit(bad_swap_text, r.topleft) if self.not_adjacent_text_life > 0: btw, bth = not_adjacent_text.get_size() r = pygame.rect.Rect((self.screen_width // 2 - btw // 2, pad // 2 - bth // 2 + bth), (btw, bth)) self.screen.fill((230, 230, 230), r) # clear block text from display if game over if self.game_over: self.not_adjacent_text_life = 0 else: # retain text for 4 seconds self.not_adjacent_text_life -= dt if self.not_adjacent_text_life > 0: self.screen.blit(not_adjacent_text, r.topleft) if self.game_over: self.screen.fill((230, 230, 230), pygame.rect.Rect((0, 0), (self.screen_width, pad))) # render text, get dimensions game_over_text = self.bold_font.render('Game Over', True, (50, 50, 50)) tw, th = text.get_size() # icon dimensions rw, rh = IMAGES['1_navigation_refresh'].get_size() # add in a spacer to get width space = int(16 * self.dp) w = tw + rw + space # determine starting X coord which gives clickable rect box x = self.screen_width // 2 - w // 2 reset_clickable = pygame.rect.Rect((x, 0), (w, pad)) # blit text self.screen.blit(game_over_text, (x, pad // 2 - th // 2)) # blit icon x += tw + space + rw // 2 self.screen.blit(IMAGES['1_navigation_refresh'], (x, pad // 2 - rh // 2)) pygame.display.flip() self.all_dirty = False self.save_state()
def game_loop(): clock=pygame.time.Clock() recording=False terrain=make_terrain() terrain_d=TERRAIN_DIRTY() objects=[] map_layer = pyscroll.BufferedRenderer(MyData(terrain), (screen_w,screen_h)) group = pyscroll.PyscrollGroup(map_layer=map_layer) macro=[] mobs=[] dwarves=[] dw_index=0 position=TILE*2500,TILE*50 a_dwarf=Dwarf(2500*16,40*16,terrain,terrain_d,group,objects) another_dwarf=Dwarf(2502*16,40*16,terrain,terrain_d,group,objects) yet_another_dwarf=Dwarf(2505*16,40*16,terrain,terrain_d,group,objects) fourth_dwarf=Dwarf(2507*16,40*16,terrain,terrain_d,group,objects) dwarves.append(a_dwarf) group.add(a_dwarf) dwarves.append(another_dwarf) group.add(another_dwarf) dwarves.append(yet_another_dwarf) group.add(yet_another_dwarf) dwarves.append(fourth_dwarf) group.add(fourth_dwarf) a_hammer=Hammer() a_pick=PickAxe() a_sickle=Sickle() a_ladder=Ladder() group.add(a_hammer) group.add(a_pick) group.add(a_sickle) group.add(a_ladder) the_dwarf=dwarves[dw_index] a_dwarf.inventory=a_pick another_dwarf.inventory=a_ladder yet_another_dwarf.inventory=a_sickle fourth_dwarf.inventory=a_hammer while True: if android: OuyaController.startOfFrame() delta=clock.tick(30) if android: if android.check_pause(): android.wait_for_resume() events = pygame.event.get() keys = pygame.key.get_pressed() mouse = pygame.mouse.get_pressed() for e in events: if e.type==pygame.QUIT: return if e.type==pygame.KEYDOWN and e.key==pygame.K_q: return if e.type==pygame.KEYDOWN and e.key==pygame.K_k: if not recording: dw_index=(dw_index+1)%len(dwarves) if e.type==pygame.KEYDOWN and e.key==pygame.K_j: if not recording: dw_index=(dw_index-1)%len(dwarves) if e.type==pygame.KEYDOWN and e.key==pygame.K_r: if not recording: macro=["LOOP"] else: program=the_dwarf.commands_behave(macro) the_dwarf.behaviour=program macro=[] recording=not recording the_dwarf=dwarves[dw_index] the_dwarf.command=None the_dwarf.parameter=None if keys[pygame.K_c] and keys[pygame.K_RIGHT]: if the_dwarf.inventory is not None: the_dwarf.command="USE-RIGHT" elif keys[pygame.K_c] and keys[pygame.K_LEFT]: if the_dwarf.inventory is not None: the_dwarf.command="USE-LEFT" elif keys[pygame.K_c] and keys[pygame.K_DOWN]: if the_dwarf.inventory is not None: the_dwarf.command="USE-DOWN" elif keys[pygame.K_c] and keys[pygame.K_UP]: if the_dwarf.inventory is not None: the_dwarf.command="USE-UP" elif keys[pygame.K_c]: if the_dwarf.inventory is not None: the_dwarf.command="USE" elif keys[pygame.K_UP]: the_dwarf.command="UP" elif keys[pygame.K_LEFT]: the_dwarf.command="LEFT" elif keys[pygame.K_RIGHT]: the_dwarf.command="RIGHT" elif keys[pygame.K_DOWN]: the_dwarf.command="DOWN" elif keys[pygame.K_s]: if the_dwarf.inventory is not None: the_dwarf.command="PUT" elif keys[pygame.K_x]: if the_dwarf.inventory is None: the_dwarf.command="TAKE" if recording and the_dwarf.command: macro.append(the_dwarf.command) if terrain_d.get(): map_layer.redraw() group.update(delta) group.center(the_dwarf.rect.center) group.draw(screen) if len(sys.argv)==2 and sys.argv[1]=="--big": screen.blit(the_font.render("arrows-move, j/k-switch gnome",1,[255,255,255]),[5,23]) screen.blit(the_font.render("x/s-take/drop, c-use tool",1,[255,255,255]),[5,38]) off=53 else: screen.blit(the_font.render("arrows-move, j/k-switch gnome, x/s-take/drop, c-use tool",1,[255,255,255]),[5,23]) off=38 for i,dwarf in enumerate(dwarves): if dwarf.inventory is not None: screen.blit(the_font.render(dwarf.inventory.name +" "+str(dwarf.inventory.durability) +" "+str(dwarf.food/50) ,1,(255,255,255)),(5,off+i*15)) else: screen.blit(the_font.render("NOTHING" +" "+str(dwarf.food/50) ,1,(255,255,255)),(5,off+i*15)) if recording: screen.blit(rec,(0,0)) if len(sys.argv)==2 and sys.argv[1]=="--big": pygame.transform.scale(screen,(800,600),screen_real) pygame.display.flip()
def run(self): global mute_music if pygame.display.get_init(): self.final_display=pygame.display.get_surface() elif not self.final_display: 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()') pre_display=pygame.Surface(self.size) fps_clock=pygame.time.Clock() pygame.display.set_caption(self.title) self.preEvents() '''### if android: cgps_hardware = autoclass("com.lab.labnavia.Hardware") gps_hardware = cgps_hardware() locationManager = gps_hardware.startLocationManager() gps_hardware.startLocationUpdater(locationManager,10000,1) '''### 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.blitOn(pre_display) ''' self.blitOn(self.render_list) self.render_list.reorderList() self.render_list.blitOn(pre_display) ''' debugLogScreen(pre_display,str(int(fps_clock.get_fps()))+":"+str(self.fps),(0,0),(255,55,55)) ''' if android: debugLogScreen(pre_display,str(gps_hardware.location.latitude),(0,50),(0,0,0)) debugLogScreen(pre_display,str(gps_hardware.location.longitude),(0,100),(0,0,0)) #location=gps_hardware.getLocation(locationManager) #debugLogScreen(pre_display,str(location.getLatitude()),(120,30),(0,0,255)) #debugLogScreen(pre_display,str(location.getLongitude()),(120,30),(0,0,255)) ''' pygame.transform.scale(pre_display if self.rotate==0 else pygame.transform.rotate(pre_display.convert(),self.rotate),(int(self.size[0]*self.resize_scale[0]),int(self.size[1]*self.resize_scale[1])),self.final_display) self.screenManipulation(self) '''self.render_list.setZero()''' pygame.display.flip() fps_clock.tick(self.fps) debugLogSuper('\t\tFim passagem') self.posEvents() if self.loading_image: self.blitBg(pre_display) try:pre_display.blit(self.loading_image,self.loading_image.get_rect(center=(self.size[0]//2,self.size[1]//2)).topleft) except Exception,e:print e pygame.transform.scale(pre_display if self.rotate==0 else pygame.transform.rotate(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()
def main(): global MAINCLOCK, MAINSURF, FONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, SOLVE_SURF, SOLVE_RECT """The main() function is where our program begins. (See the last two lines of code to see why.) Because we define MAINCLOCK and MAINSURF inside this function, these are local variables to the main() function and the names MAINCLOCK and MAINSURF won't exist outside of this function. By using a global statement, we can tell Python that we want these variables to be global variables. More information about global and local variables is at http://inventwithpython.com/chapter6.html#VariableScope """ pygame.init() if android: android.init() MAINCLOCK = pygame.time.Clock() MAINSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Slide Puzzle') """pygame.init() needs to be called before any of the other Pygame functions. pygame.time.Clock() returns a pygame.Clock object. We will use this object's tick() method to ensure that the program runs at no faster than 30 frames per second (or whatever integer value we have in the FPS constant.) pygame.display.set_mode() creates the window on the screen and returns a pygame.Surface object. Any drawing done on this Surface object with the pygame.draw.* functions will be displayed on the screen when we call pygame.display.update(). More information about pygame.display.set_mode() is at http://inventwithpython.com/chapter17.html#ThepygamedisplaysetmodeandpygamedisplaysetcaptionFunctions""" FONT = pygame.font.Font('freesansbold.ttf', FONTSIZE) """This line loads a font to use for drawing text. Since our game only uses one font (and at one size, 16 points) we only have to make one call to the pygame.font.Font() constructor function. We will store this font in the global variable FONT.""" # Store the option buttons and their rectangles in OPTIONS. RESET_SURF, RESET_RECT = makeText('Reset', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 240, WINDOWHEIGHT - 180) NEW_SURF, NEW_RECT = makeText('New Game', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 240, WINDOWHEIGHT - 120) SOLVE_SURF, SOLVE_RECT = makeText('Solve', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 240, WINDOWHEIGHT - 60) """Our program needs three buttons for reset the game, starting a new game, and solving the current puzzle. The data for these buttons will be made by our makeText() function, which is described later. makeText() will return two objects, a surface object that contains the text and a rectangle object that contains the position and size data of the button. Here we are just creating the objects for the button. We will display them on the screen in the drawBoard() function.""" mainBoard, solutionSeq = generateNewPuzzle(80) """generateNewPuzzle() will create a new puzzle by creating a new data structure for our board and then randomly sliding the puzzle around 100 times. It will remember the sequence of slides it made and return that along with the board data structure. The structure of the board data structure is described in detail in generateNewPuzzle(), but basically it's a list of list of integers, where the integers correspond to the number on the tile and the 0 integer stands for the blank space. Since we keep a record of the slides that were made, we could always do the reverse of those slides to get the board back to its original state. This is how we "solve" the board when the player pushes on the Solve button.""" solvedBoard = getStartingBoard( ) # a solved board is the same as the board in a start state. """We're going to make a board that is in the ordered, starting state around so we can compare it to the board that is displayed on the screen (that is, mainBoard). If these two boards are equal, we know that the player has solved the board.""" seq = [] """We are also going to keep a record of the player's slides, so we can revert back to the start of the puzzle if the player wants. (We also need to know this if we want to automatically solve the puzzle.""" while True: # The main game loop. sliding = None msg = '' if mainBoard == solvedBoard: msg = 'Solved!' """This is the main game loop, which constantly loops while the program is playing. In this loop, we display the board on the screen and also handle any input events from the player. The sliding variable will keep track of which direction we should slide the tiles. We have a separate variable for this so that we can treat input from the mouse and the keyboard the same way. We also want to display a text message at the top left corner of the window for various reasons. We will use the msg variable to store this string. If the board happens to be in the solved state, then we want the text message to be Solved!""" drawBoard(mainBoard, message=msg) """On each iteration we want to draw the current state of the board on the screen (along with any text message). Since the game loop runs 30 times a seconds (unless the computer is too slow or yo have changed the value in the FPS variable), we are constantly drawing the latest board to the screen.""" if android is not None and android.check_pause(): android.wait_for_resume() # Handle any events. for event in pygame.event.get(): print event if event.type == QUIT: terminate() if event.type == KEYDOWN and event.key == K_PAGEUP: terminate() if event.type == MOUSEBUTTONUP: spotClicked = getSpotClicked(mainBoard, event.pos[0], event.pos[1]) """When the MOUSEBUTTONUP is created, we check if the mouse is currently over one of the tiles (otherwise we can ignore it.) The bulk of this is implemented inside our getSpotClicked() function. This function returns None if the mouse wasn't over a button, or it returns the color value of the button.""" if spotClicked is not None: spotx, spoty = spotClicked """If getSpotClicked() did not return None, then this means the place on the window the player clicked was a spot (as opposed to somewhere in the margins).""" blankx, blanky = getBlankPosition(mainBoard) """We also need to find out where the blank spot currently is on the board. We'll get the xy coordinates of this spot from getBlankPosition().""" if spotx == blankx + 1 and spoty == blanky: sliding = LEFT if spotx == blankx - 1 and spoty == blanky: sliding = RIGHT if spotx == blankx and spoty == blanky + 1: sliding = UP if spotx == blankx and spoty == blanky - 1: sliding = DOWN """Now we find out if the spot that the player clicked on is located next to the blank spot. We should slide a tile to the left if the blank spot is on its left, and slide the tile up if the blank space is above it, and so on.""" else: # check if the user clicked on one of the option buttons if RESET_RECT.collidepoint(event.pos[0], event.pos[1]): resetAnimation(mainBoard, seq) seq = [] """Here we use the pygame.Rect object's collidepoint() method to find out if the x and y coordinates of the mouse click (which are in event.pos[0] and event.pos[1], respectively) are inside the rectangular area that the "reset" button occupies. If so, then we want to reset all the tiles back to their original configuration. We do this by passing resetAnimation() the sequence of moves made by the player so far (which is in the seq list). Of course, afterwards we'll want to set the seq list back to a blank list, since now the board is as though the player never made any moves at all.""" if NEW_RECT.collidepoint(event.pos[0], event.pos[1]): mainBoard, solutionSeq = generateNewPuzzle(80) seq = [] """This code handles what happens when the user's mouse click was inside the "new game" button. Here we are going to start a brand new game, so we replace the board data structure stored in mainBoard and the sequence of moves to solve it in the solutionSeq list. We also want to reset the seq list since the player is starting a new game.""" if SOLVE_RECT.collidepoint(event.pos[0], event.pos[1]): resetAnimation(mainBoard, solutionSeq + seq) seq = [] """Here we check if the player has clicked on the "solve" button, in which case we do almost the same code as the "reset" button case. Except for this, instead of just reseting the sequence of steps the player has made (that is, the seq list) we reset the steps of the solution including the steps the player has made (solutionSeq + seq). This will reset the board back to the ordered starting board. If the player wants a new puzzle, they will have to click the "new game" button to generate a new random puzzle.""" if event.type == KEYUP: """The previous code checked what happens in the event that the user clicked the mouse (MOUSEBUTTONUP), while this code will handle what happens when the user presses a keyboard key. The key value that you can compare event.key to is stored in Pygame's own set of constants that have the format K_*, where the * is the letter of the key. In the case of the Esc key, it is K_ESCAPE. We need to call isValidMove() to make sure that the board is in a state where this move is allowed. Otherwise we would start sliding tiles off the board and cause bugs.""" if (event.key == K_LEFT or event.key == K_a) and isValidMove( mainBoard, LEFT): sliding = LEFT if (event.key == K_RIGHT or event.key == K_d) and isValidMove( mainBoard, RIGHT): sliding = RIGHT if (event.key == K_UP or event.key == K_w) and isValidMove( mainBoard, UP): sliding = UP if (event.key == K_DOWN or event.key == K_s) and isValidMove( mainBoard, DOWN): sliding = DOWN if event.key == K_ESCAPE: terminate() if event.key == K_r: resetAnimation(board, moves) if sliding: slideAnimation(mainBoard, sliding) makeMove(mainBoard, sliding) seq.append(sliding) """The sliding variable will not be None if the player specified (either through the keyboard or with the mouse) that we should slide the tiles. First we play the animation of the tile moving over, then we update the board data structure, and then we add this recent move to the list of moves the player has made in the seq list.""" pygame.display.update() MAINCLOCK.tick(FPS)
def run(self): # start of this Thread if android is None: pygame.init() self.db = classes.dbconn.DBConnection(self.config.file_db, self) self.scheme = None # classes.colors.BYScheme() #BW, WB, BY self.scheme_code = None self.user_name = None self.display_info = pygame.display.Info() # Used to manage how fast the screen updates self.clock = pygame.time.Clock() while self.done4good is False: if self.window_state == "LOG IN": self.done = False self.set_init_vals() """ if self.config.platform != "windows" and android is None: os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ( self.config.window_pos[0], self.config.window_pos[1]) """ os.environ['SDL_VIDEO_CENTERED'] = '1' if android is None: if not self.logged_out: self.size = [800, 570] else: self.size = self.wn_size else: self.size = self.android_login_size self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption(self.config.window_caption) self.loginscreen = classes.loginscreen.LoginScreen(self, self.screen, self.size) wait = False while self.done is False and self.userid < 0: if android is not None: if android.check_pause(): wait = True android.wait_for_resume() else: wait = False if not wait: for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): self.done = True # mark to finish the loop and the game self.done4good = True else: self.loginscreen.handle(event) if self.redraw_needed[0] and self.loginscreen.update_me: self.loginscreen.update() self.flip_needed = True if self.flip_needed: # update the screen with what we've drawn. pygame.display.flip() self.flip_needed = False self.clock.tick(30) if self.window_state == "GAME": self.set_up_user() self.done = False self.game_const = None self.set_init_vals() """ if android is None: os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (self.config.window_pos[0], self.config.window_pos[1]) """ os.environ['SDL_VIDEO_CENTERED'] = '1' self.config.fs_width = self.display_info.current_w self.config.fs_height = self.display_info.current_h # check if there's a size available from previous session, but not on MacOS if self.config.platform != "macos" and \ self.config.settings["screenw"] >= self.config.size_limits[0] and \ self.config.settings["screenh"] >= self.config.size_limits[1] and \ self.config.settings["screenw"] <= self.config.size_limits[2] and \ self.config.settings["screenh"] <= self.config.size_limits[3]: self.wn_size = [self.config.settings["screenw"], self.config.settings["screenh"]] else: self.wn_size = [min(self.config.fs_width - self.config.os_panels_w, self.config.size_limits[2]), min(self.config.fs_height - self.config.os_panels_h, self.config.size_limits[3])] self.config.settings["screenw"] = self.wn_size[0] self.config.settings["screenh"] = self.wn_size[1] self.fs_size = [self.config.fs_width, self.config.fs_height] if self.config.fullscreen == True: self.size = self.fs_size[:] flag = pygame.FULLSCREEN else: self.size = self.wn_size[:] flag = pygame.RESIZABLE # restarting the display to solve a bug causing some of the game area unresponsive after resizing (this bug affected the game only when it was set to start in fullscreen) if android is None: pygame.display.quit() pygame.display.init() self.screen = pygame.display.set_mode(self.size, flag) else: self.wn_size = self.android_screen_size self.fs_size = self.android_screen_size self.size = self.android_screen_size self.screen = pygame.display.set_mode(self.android_screen_size) # Set title of the window pygame.display.set_caption(self.config.window_caption) self.sizer = classes.sizer.Sizer(self, self.size[0], self.size[1]) self.sb = classes.score_bar.ScoreBar(self) self.create_subsurfaces() # display splash screen during loading self.screen.fill((255, 255, 255)) loading_image = pygame.image.load(os.path.join('res', 'images', 'schemes', 'white', 'home_logo.png')) self.screen.blit(loading_image, ((self.size[0] - 750) // 2, (self.size[1] - 180) // 2)) pygame.display.flip() # create a list of one sprite holding game image or logo self.sprites_list = pygame.sprite.RenderPlain() # create a dummy self.game_board variable to be deleted and recreated at the beginning of the main loop self.game_board = None # kind of a dirty workaround to avoid issues with anti-aliasing on devices not supporting aa compatible bit depths - hopefully it works (not tested - haven't got such device) if pygame.display.get_surface().get_bitsize() not in [32, 24]: pygame.draw.aalines = pygame.draw.lines pygame.draw.aaline = pygame.draw.line # create game menu / game manager self.xml_conn = classes.xml_conn.XMLConn(self) m = classes.menu.Menu(self) self.m = m # create info panel integrated with level control - holds current level/game and some buttons to change levels, etc. info = classes.info_bar.InfoBar(self) self.info = info self.dialog = classes.dialogwnd.DialogWnd(self) # -------- Main Program Loop ----------- # wait = False while self.done is False: if android is not None: if android.check_pause(): wait = True android.wait_for_resume() else: if wait: self.redraw_needed = [True, True, True] wait = False if not wait: if m.active_game_id != m.game_started_id: # if game id changed since last frame or selected activity is the Language changing panel if self.game_board is not None: # if this is not the first start of a game - the self.game_board has been already 'created' at least once self.game_board.board.clean() # empty sprite groups, delete lists del (self.game_board) # delete all previous game objects self.game_board = None exec("import game_boards.%s" % m.game_constructor[0:7]) self.game_const = eval("game_boards.%s" % m.game_constructor) self.game_board = self.game_const(self, self.speaker, self.config, self.size[0], self.size[1]) m.game_started_id = m.active_game_id self.layout = self.game_board.layout self.recreate_game_screen() info.new_game(self.game_board, self.info_bar) self.set_up_scheme() gc.collect() # force garbage collection to remove remaining variables to free memory elif self.game_board.level.lvl != self.game_board.level.prev_lvl: # if game id is the same but the level changed load new level self.layout = self.game_board.layout self.sizer.update_sizer(self.size[0], self.size[1]) self.recreate_game_screen() info.new_game(self.game_board, self.info_bar) self.game_board.level.prev_lvl = self.game_board.level.lvl self.redraw_needed[0] = True gc.collect() if not self.show_dialogwnd: if self.game_board.show_msg == True: # if dialog after completing the game is shown then hide it and load next game if time.time() - self.game_board.level.completed_time > 1.25: self.game_board.show_msg = False self.game_board.level.next_board_load() # Process or delegate events for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): self.dialog.show_dialog(0, self.lang.d["Do you want to exit the game?"]) elif event.type == pygame.VIDEORESIZE: if self.config.fullscreen == False: self.on_resize(list(event.size), info) elif event.type == pygame.KEYDOWN and event.key == pygame.K_f and ( event.mod & pygame.KMOD_LCTRL): self.fullscreen_toggle(info) elif event.type == pygame.KEYDOWN and event.key == pygame.K_F5: # refresh - reload level self.game_board.level.load_level() elif event.type == pygame.KEYDOWN and event.key == pygame.K_F8: # auto resize window to prep for screenshots and video self.on_resize([1280, 720], self.info) elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEMOTION: pos = event.pos if self.show_dialogwnd: self.dialog.handle(event) else: if pos[0] > 0 and self.sizer.score_bar_h > pos[1]: if self.mouse_over[0] is not None and self.mouse_over[0] != self.sb: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = self.sb self.sb.handle(event) elif pos[0] > 0 and self.sizer.top_margin > pos[1]: if self.mouse_over[0] is not None and self.mouse_over[0] != info: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = info info.handle(event, self.game_board.layout, self) elif pos[0] > 0 and self.sizer.top_margin < \ pos[1] < self.game_board.layout.game_h + self.sizer.top_margin: # clicked on game board if event.type == pygame.MOUSEBUTTONDOWN and self.game_board.show_msg is True: # if dialog after completing the game is shown then hide it and load next game self.game_board.show_msg = False self.game_board.level.next_board_load() else: self.game_board.handle(event) else: # clicked on info panel if self.mouse_over[0] is not None and self.mouse_over[0] != self.game_board: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = self.game_board if event.type == pygame.MOUSEBUTTONDOWN and self.game_board.show_msg is True: # if dialog after completing the game is shown then hide it and load next game self.game_board.show_msg = False self.game_board.level.next_board_load() elif event.type == pygame.MOUSEBUTTONUP: pos = event.pos if self.show_dialogwnd: self.dialog.handle(event) else: gbh = False if pos[0] > 0 and self.sizer.top_margin < \ pos[1] < self.game_board.layout.game_h + self.sizer.top_margin: self.game_board.handle(event) gbh = True elif pos[0] > 0 and pos[1] < self.sizer.score_bar_h: self.sb.handle(event) elif pos[0] > 0 and pos[1] < self.sizer.top_margin: # make the game finish drag, etc. self.game_board.handle(event) # handle info button clicks info.handle(event, self.game_board.layout, self) if not gbh: self.game_board.handle(event) if android is None: pygame.mouse.set_cursor(*pygame.cursors.arrow) else: if self.show_dialogwnd: self.dialog.handle(event) else: # let the game handle other events self.game_board.handle(event) # checking if any of the subsurfaces need updating and updating them if needed if self.redraw_needed[1]: info.draw(self.info_bar) self.redraw_needed[1] = False self.flip_needed = True if self.redraw_needed[0]: self.game_board.update(self.game) self.redraw_needed[0] = False self.flip_needed = True if self.sb.update_me: self.sb.draw(self.score_bar) self.flip_needed = True self.sb.update_me = False if self.flip_needed: # update the screen with what we've drawn. if self.show_dialogwnd: self.sb.draw(self.score_bar) self.dialog.update() pygame.display.flip() self.flip_needed = False # Limit to 30 frames per second but most redraws are made when needed - less often # 30 frames per second used mainly for event handling self.game_board.process_ai() self.clock.tick(30) # close eSpeak process, quit pygame, collect garbage and exit the game. if self.config.settings_changed: self.config.save_settings(self.db) self.clock.tick(300) self.db.close() if self.speaker.process is not None: self.speaker.stop_server() pygame.quit() gc.collect() if android is None: os.sys.exit()
def textfield(rect, font, settings, onlynums=False, loadtext=True): """Starts interaction with a text field, handling keyboard input and updating part of the display on that input; returns when Enter is pressed arguments rect - a (x,y,w,h) tuple indicating where the textfield is font - a pygame.font.Font instance fgc - a (r,g,b) tuple indicating the text colour bgc - a (r,g,b) tuple indicating the background colour of the textfield settings - the app settings dict keyword arguments onlynums - Boolean indicating whether only numerical values should be allowed loadtext - Boolean indicating if the current text should be loaded (assuming the function is called via the currently active button!); alternatively all text is deleted when this function is called returns input - string of what was typed in """ # get the display surface disp = pygame.display.get_surface() # clip the display surface, to prevent text from spilling over disp.set_clip(rect) # rect centre textcentre = (rect[0]+rect[2]/2, rect[1]+rect[3]/2) # allowed characters if onlynums: allowed = u'0123456789' else: allowed = keymodsdict.keys() # load the current text if loadtext: text = settings[u'guibuttons'][settings[u'currentscreen']][settings[u'currentbutton']][u'text'] else: text = u"" # if this is Android, show the keyboard if settings[u'android']: android.show_keyboard() # run until Enter is pressed enter = False while not enter: # check if there is any event for event in pygame.event.get(): # check if the event is a keypress if event.type == pygame.KEYDOWN: # convert the keyname into something readable key = pygame.key.name(event.key) # check if the key is Enter if key == u'return': enter = True # remove the last index of the text if the key was backspace elif key == u'backspace' and len(text) > 0: text = text[:-1] # add the input to the text if the key was an allowed key elif key in allowed: # check if the Shift key is pressed (not when using nums) if (event.mod & pygame.KMOD_SHIFT) and not onlynums: # change key value accordingly key = keymodsdict[key] # append key to the text text += key # render the text textsurf = font.render(text, False, settings[u'fgc']) # text position textpos = (int(textcentre[0] - textsurf.get_width()/2), int(textcentre[1]-textsurf.get_height()/2)) # reset text if enter: colour = settings[u'tfbgc'] else: colour = settings[u'tfhbgc'] disp.fill(colour, rect) # blit text to display disp.blit(textsurf, textpos) pygame.display.flip() # allow an Android interrupt if settings[u'android']: if android.check_pause(): android.wait_for_resume() # hide keyboard on Android if settings[u'android']: android.hide_keyboard() # unclip display disp.set_clip(None) return text
def colourpicker(settings): """Allows a user to choose a colour, using three sliders (one for red, one for green, and one for blue); the interactive window will be full screen (taking over the display), and will restore the display to its state when calling colourpicker before returning arguments settings - the app settings dict returns input - list of the chosen colour, e.g. [255,100,0] """ # DISPLAY # get current display disp = pygame.display.get_surface() ds = disp.get_size() # copy display as it is now dispcopy = disp.copy() # PROPERTIES # current button button = settings[u'guibuttons'][settings[u'currentscreen']][settings[u'currentbutton']] # current colour exec(u"rgb = list(%s)" % button[u'text']) # colour rect crect = [int(ds[0]/4), int(ds[1]/5), int(ds[0]/2), int(2*ds[1]/5)] # text position (centre) textrect = [int(ds[0]/4), int(3*ds[1]/5), int(3*ds[0]/8), int(ds[1]/10)] textpos = (int(7*ds[0]/16), int(13*ds[1]/20)) # save button savetext = settings[u'font'][u'medium'][u'bold'].render(u"save", False, settings[u'fgc']) saverect = [int(5*ds[0]/8), int(12.5*ds[1]/20), int(ds[0]/8), int(ds[1]/20)] savepos = (int(saverect[0]+saverect[2]/2)-savetext.get_width()/2, int(saverect[1]+saverect[3]/2)-savetext.get_height()/2) # sliders bw = 1 sly = [14*ds[1]/20, 16*ds[1]/20, 18*ds[1]/20] slrect = [] for y in sly: slrect.append([int(ds[0]/4), int(y), int(ds[0]/2), int(ds[1]/20)]) # slider button buttsize = (slrect[0][3]-2*bw, slrect[0][3]-2*bw) minx = slrect[0][0]+bw maxfill = (slrect[0][2]-2*bw) - buttsize[0] # DRAWING # fill the display with the background colour disp.fill(settings[u'bgc']) # draw colour rect disp.fill(rgb, crect) # RGB value rgbtext = settings[u'font'][u'medium'][u'bold'].render(unicode(rgb), False, settings[u'fgc']) disp.blit(rgbtext, (textpos[0]-rgbtext.get_width()/2, textpos[1]-rgbtext.get_height()/2)) # save button disp.fill(settings[u'colours'][u'chameleon'][2], saverect) disp.blit(savetext, (savepos)) # sliders for i in range(len(slrect)): r = slrect[i] # draw rect background pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][4], r, 0) # draw border pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][0], r, bw) # draw button x = minx + (rgb[i] / 255.0) * maxfill pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][0], [x, r[1]+bw, buttsize[0], buttsize[1]], 0) # update display pygame.display.flip() # INTERACTION saved = False while not saved: # check for clicks b, pos = check_mouseclicks() # handle input if b != None: # save button if check_click(pos, saverect): saved = True # any rect for i in range(len(slrect)): r = slrect[i] if check_click(pos, r) and (minx < pos[0] <= minx+maxfill): # reset button pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][4], r, 0) pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][0], r, bw) # draw new button pygame.draw.rect(disp, settings[u'colours'][u'aluminium'][0], [pos[0], r[1]+bw, buttsize[0], buttsize[1]], 0) # set corresponding RGB value rgb[i] = int(((pos[0]-minx) / float(maxfill)) * 255) # redraw rect disp.fill(rgb, crect) # reset and redraw text disp.fill(settings[u'bgc'], textrect) rgbtext = settings[u'font'][u'medium'][u'bold'].render(unicode(rgb), False, settings[u'fgc']) disp.blit(rgbtext, (textpos[0]-rgbtext.get_width()/2, textpos[1]-rgbtext.get_height()/2)) # update display pygame.display.flip() # allow an Android interrupt if settings[u'android']: if android.check_pause(): android.wait_for_resume() # DISPLAY # reset display disp.blit(dispcopy,(0,0)) pygame.display.flip() return rgb
def main(): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" # Initialize Everything width = 800 height = 600 pygame.init() screen = pygame.display.set_mode((width, height)) pygame.display.set_caption('break0ut') pygame.mouse.set_visible(0) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((0, 0, 0)) # Map the back button to the escape key. if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) # Display The Background # screen.blit(background, (0, 0)) # pygame.display.flip() # Prepare Game Objects clock = pygame.time.Clock() # create the bar and set the y position of the bar gameBar = Bar(screen.get_height() - 50) playBall = Ball() playBall.resetSelf(gameBar.rect) moveableSprites = pygame.sprite.RenderPlain((gameBar, playBall)) # sample Block aBlock = Block((10, 10)) #create a pit bottom for the ball, which is used to reset the ball pitBottom = Rect(0, height - 10, width, 10) #block area should occupy 80% of the width and 50% of height blockAreaWidth = int(width * 0.8) blockAreaHeight = int(height * 0.5) maxBlockInX = int(blockAreaWidth / aBlock.rect.width) #update the block area width to the correct size blockAreaWidth = (maxBlockInX * aBlock.rect.width) # get start position for x blockStartX = int((width - (blockAreaWidth)) / 2) blockStartY = int(blockStartX) # same difference above as on the sides # create the blocks start at the x value and go until the max width has reached # there should be no space between the current and the next block gameAreaSprites = pygame.sprite.RenderPlain() for blockPosX in xrange(blockStartX, (width - blockStartX), aBlock.rect.w): for blockPosY in xrange(blockStartY, (blockAreaHeight + blockStartY), aBlock.rect.h): gameAreaSprites.add(Block((blockPosX, blockPosY))) # draw background screen.blit(background, (0, 0)) pygame.display.flip() # main game loop while 1: clock.tick(60) # Android-specific: if android: if android.check_pause(): android.wait_for_resume() # Handle Input Events for event in pygame.event.get(): # quit the game if escape is pressed if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return # move the handles according to the object elif event.type == MOUSEMOTION: gameBar.handleEvent(event) playBall.handleEvent(event) elif event.type == MOUSEBUTTONDOWN: playBall.handleEvent(event) # check if a block has hit a ball, if so remove the block # the ball is reversed in the checkhit method hit = playBall.checkHit(gameAreaSprites) if hit: if hit.decreaseHP() == 0: gameAreaSprites.remove(hit) gameBar.checkBarHit(playBall) if pitBottom.colliderect(playBall.rect): playBall.resetSelf(gameBar.rect) # update and draw Everything gameAreaSprites.update() moveableSprites.update() screen.blit(background, (0, 0)) moveableSprites.draw(screen) gameAreaSprites.draw(screen) pygame.display.flip()
def start_task(settings): """Prepares the task, and runs it (saving data happens while running); afterwards the settings are returned, with adjusted analysis properties so that the data that has just been collected can be analyzed arguments settings - app settings dict, which includes a dict on the task properties returns settings - same settings dict as was passed, with updated analysis settings """ # get display disp = pygame.display.get_surface() # set display to fullscreen mode flags = disp.get_flags() if not flags & pygame.FULLSCREEN: flags = pygame.FULLSCREEN disp = pygame.display.set_mode(settings[u'dispsize'], flags) # inputrect inputrect = [ int(settings[u'dispcentre'][0] - settings[u'dispsize'][0] / 4), int(settings[u'dispcentre'][1] - settings[u'dispsize'][1] / 12), int(settings[u'dispsize'][0] / 2), int(settings[u'dispsize'][0] / 6) ] # draw text input screen disp.fill(settings[u'bgc']) textsurf = settings[u'font'][u'large'][u'regular'].render( u"please provide a filename", False, settings[u'fgc']) disp.blit(textsurf, (int(settings[u'dispcentre'][0] - textsurf.get_width() / 2), int(settings[u'dispsize'][1] / 4 - textsurf.get_height() / 2))) disp.fill(settings[u'tfbgc'], inputrect) pygame.display.flip() # ask for the participant name settings[u'ppname'] = textfield(inputrect, settings[u'font'][u'large'][u'regular'], settings, loadtext=False) # show loading message disp.fill(settings[u'bgc']) textsurf = settings[u'font'][u'large'][u'regular'].render( u"starting task, 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() # initialize new Task task = Task(settings) # prepare task task.prepare() # run task task.run() # show ending screen disp.fill(settings[u'bgc']) textsurf = settings[u'font'][u'large'][u'regular'].render( u"thank you for participating", 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
def run(self): # start of this Thread if android is None: pygame.init() self.db = classes.dbconn.DBConnection(self.config.file_db, self) self.scheme = None # classes.colors.BYScheme() #BW, WB, BY self.scheme_code = None self.user_name = None self.display_info = pygame.display.Info() # Used to manage how fast the screen updates clock = pygame.time.Clock() self.clock = clock while self.done4good is False: if self.window_state == "LOG IN": self.done = False self.set_init_vals() if self.config.platform != "windows" and android is None: os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ( self.config.window_pos[0], self.config.window_pos[1]) if android is None: if not self.logged_out: self.size = [800, 570] else: self.size = self.wn_size else: self.size = self.android_login_size self.screen = pygame.display.set_mode(self.size) pygame.display.set_caption(self.config.window_caption) self.loginscreen = classes.loginscreen.LoginScreen( self, self.screen, self.size) wait = False while self.done is False and self.userid < 0: if android is not None: if android.check_pause(): wait = True android.wait_for_resume() else: wait = False if not wait: for event in pygame.event.get(): if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): self.done = True # mark to finish the loop and the game self.done4good = True else: self.loginscreen.handle(event) if (self.redraw_needed[0] and self.game_redraw_tick[0] < 3) and self.loginscreen.update_me: self.loginscreen.update() self.game_redraw_tick[0] += 1 if self.game_redraw_tick[0] == 2: self.redraw_needed[0] = False self.game_redraw_tick[0] = 0 self.flip_needed = True if self.flip_needed: # update the screen with what we've drawn. pygame.display.flip() self.flip_needed = False clock.tick(30) if self.window_state == "GAME": self.set_up_user() self.done = False self.set_init_vals() if android is None: os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % ( self.config.window_pos[0], self.config.window_pos[1]) self.config.fs_width = self.display_info.current_w self.config.fs_height = self.display_info.current_h # check if there's a size available from previous session, but not on MacOS if self.config.platform != "macos" and \ self.config.settings["screenw"] >= self.config.size_limits[0] and \ self.config.settings["screenh"] >= self.config.size_limits[1] and \ self.config.settings["screenw"] <= self.config.size_limits[2] and \ self.config.settings["screenh"] <= self.config.size_limits[3]: self.wn_size = [ self.config.settings["screenw"], self.config.settings["screenh"] ] else: self.wn_size = [ min(self.config.fs_width - self.config.os_panels_w, self.config.size_limits[2]), min(self.config.fs_height - self.config.os_panels_h, self.config.size_limits[3]) ] self.config.settings["screenw"] = self.wn_size[0] self.config.settings["screenh"] = self.wn_size[1] self.fs_size = [self.config.fs_width, self.config.fs_height] if self.config.fullscreen == True: self.size = self.fs_size[:] flag = pygame.FULLSCREEN else: self.size = self.wn_size[:] flag = pygame.RESIZABLE # restarting the display to solve a bug causing some of the game area unresponsive after resizing (this bug affected the game only when it was set to start in fullscreen) if android is None: pygame.display.quit() pygame.display.init() self.screen = pygame.display.set_mode(self.size, flag) else: self.wn_size = self.android_screen_size self.fs_size = self.android_screen_size self.size = self.android_screen_size self.screen = pygame.display.set_mode( self.android_screen_size) # Set title of the window pygame.display.set_caption(self.config.window_caption) # create a list of one sprite holding game image or logo self.sprites_list = pygame.sprite.RenderPlain() # create a dummy self.game_board variable to be deleted and recreated at the beginning of the main loop self.game_board = None # kind of a dirty workaround to avoid issues with anti-aliasing on devices not supporting aa compatible bit depths - hopefully it works (not tested - haven't got such device) if pygame.display.get_surface().get_bitsize() not in [32, 24]: pygame.draw.aalines = pygame.draw.lines pygame.draw.aaline = pygame.draw.line # create game menu / game manager self.xml_conn = classes.xml_conn.XMLConn(self) m = classes.menu.Menu(self) self.m = m self.sb = classes.score_bar.ScoreBar(self) # create info panel integrated with level control - holds current level/game and some buttons to change levels, etc. info = classes.info_bar.InfoBar(self) self.info = info self.dialog = classes.dialogwnd.DialogWnd(self) # create the logo object and add it to the list to render on update self.front_img = classes.logoimg.LogoImg(self) self.sprites_list.add(self.front_img) # -------- Main Program Loop ----------- # wait = False while self.done is False: if android is not None: if android.check_pause(): wait = True android.wait_for_resume() else: if wait: self.redraw_needed = [True, True, True] wait = False if not wait: if m.active_game_id != m.game_started_id: # or m.active_game_id == 0: #if game id changed since last frame or selected activity is the Language changing panel if self.game_board is not None: # if this is not the first start of a game - the self.game_board has been already 'created' at least once self.game_board.board.clean( ) # empty sprite groups, delete lists del (self.game_board ) # delete all previous game objects self.game_board = None # recreate a new game and subsurfaces exec("import game_boards.%s" % m.game_constructor[0:7]) game_const = eval("game_boards.%s" % m.game_constructor) self.game_board = game_const( self, self.speaker, self.config, self.size[0], self.size[1]) m.game_started_id = m.active_game_id m.l = self.game_board.layout self.create_subsurfaces(self.game_board) info.new_game(self.game_board, self.info_bar) self.set_up_scheme() gc.collect( ) # force garbage collection to remove remaining variables to free memory elif self.game_board.level.lvl != self.game_board.level.prev_lvl or self.game_board.update_layout_on_start: # if game id is the same but the level changed load new level self.create_subsurfaces(self.game_board) info.new_game(self.game_board, self.info_bar) self.game_board.level.prev_lvl = self.game_board.level.lvl self.game_board.update_layout_on_start = False gc.collect() if not self.show_dialogwnd: if self.game_board.show_msg == True: # if dialog after completing the game is shown then hide it and load next game if time.time( ) - self.game_board.level.completed_time > 1.25: self.game_board.show_msg = False self.game_board.level.next_board_load() # Process or delegate events for event in pygame.event.get( ): # pygame.event.get(): # User did something if event.type == pygame.QUIT or ( event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): self.dialog.show_dialog( 0, self.lang. d["Do you want to exit the game?"]) elif event.type == pygame.VIDEORESIZE: if self.config.fullscreen == False: self.on_resize(list(event.size), info) elif event.type == pygame.KEYDOWN and event.key == pygame.K_f and ( event.mod & pygame.KMOD_LCTRL): self.fullscreen_toggle(info) elif event.type == pygame.KEYDOWN and event.key == pygame.K_F5: # refresh - reload level self.game_board.level.load_level() elif event.type == pygame.MOUSEBUTTONDOWN or event.type == pygame.MOUSEMOTION: pos = event.pos if self.show_dialogwnd: self.dialog.handle(event) else: if pos[0] > self.game_board.layout.menu_a_w and self.game_board.layout.score_bar_h > \ pos[1]: if self.mouse_over[ 0] is not None and self.mouse_over[ 0] != self.sb: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = self.sb self.sb.handle(event) elif pos[ 0] > self.game_board.layout.menu_a_w and self.game_board.layout.top_margin > \ pos[1]: if self.mouse_over[ 0] is not None and self.mouse_over[ 0] != info: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = info info.handle(event, self.game_board.layout, self) elif pos[ 0] > self.game_board.layout.menu_a_w and self.game_board.layout.top_margin < \ pos[1] < self.game_board.layout.game_h + self.game_board.layout.top_margin: # clicked on game board if event.type == pygame.MOUSEBUTTONDOWN and self.game_board.show_msg is True: # if dialog after completing the game is shown then hide it and load next game self.game_board.show_msg = False self.game_board.level.next_board_load( ) else: self.game_board.handle(event) elif pos[0] < self.game_board.layout.menu_a_w and pos[1] < \ self.game_board.layout.misio_pos[3]: self.front_img.handle(event) if self.mouse_over[ 0] is not None and self.mouse_over[ 0] != self.front_img: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = self.front_img elif pos[0] < self.game_board.layout.menu_a_w and pos[1] > \ self.game_board.layout.misio_pos[3]: # clicked on menu panel if self.mouse_over[ 0] is not None and self.mouse_over[ 0] != m: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = m if pos[0] < self.game_board.layout.menu_l_w: # clicked on category menu m.handle_menu_l(event) else: # clicked on game selection menu m.handle_menu_r( event, self.game_board.layout. menu_l_w) else: # clicked on info panel if self.mouse_over[ 0] is not None and self.mouse_over[ 0] != self.game_board: self.mouse_over[0].on_mouse_out() self.mouse_over[0] = self.game_board if event.type == pygame.MOUSEBUTTONDOWN and self.game_board.show_msg is True: # if dialog after completing the game is shown then hide it and load next game self.game_board.show_msg = False self.game_board.level.next_board_load( ) elif event.type == pygame.MOUSEBUTTONUP: pos = event.pos if self.show_dialogwnd: self.dialog.handle(event) else: gbh = False if pos[0] < self.game_board.layout.menu_a_w and pos[1] > \ self.game_board.layout.misio_pos[3]: # clicked on menu panel if pos[0] < self.game_board.layout.menu_l_w: # clicked on category menu m.handle_menu_l(event) else: # clicked on game selection menu m.handle_menu_r( event, self.game_board.layout. menu_l_w) elif pos[0] < self.game_board.layout.menu_a_w and pos[1] < \ self.game_board.layout.misio_pos[3]: self.front_img.handle(event) elif pos[ 0] > self.game_board.layout.menu_a_w and self.game_board.layout.top_margin < \ pos[1] < self.game_board.layout.game_h + self.game_board.layout.top_margin: self.game_board.handle(event) gbh = True elif pos[0] > self.game_board.layout.menu_a_w and pos[1] < \ self.game_board.layout.score_bar_h: self.sb.handle(event) elif pos[0] > self.game_board.layout.menu_a_w and pos[1] < \ self.game_board.layout.top_margin: # make the game finish drag, etc. self.game_board.handle(event) # handle info button clicks info.handle(event, self.game_board.layout, self) if not gbh: self.game_board.handle(event) if android is None: pygame.mouse.set_cursor( *pygame.cursors.arrow) m.swipe_reset() else: if self.show_dialogwnd: self.dialog.handle(event) else: # let the game handle other events self.game_board.handle(event) # trying to save the CPU - only update a subsurface entirely, (can't be bothered to play with dirty sprites) # if anything has changed on the subsurface or it's size has changed # creating list of drawing functions and arguments for each subsurface self.draw_func = [ self.game_board.update, info.draw, m.draw_menu ] self.draw_func_args = [[self.game], [self.info_bar], [ self.menu, self.menu_l, self.menu_r, self.game_board.layout ]] if self.m.scroll_direction != 0: if self.menu_speed == self.menu_tick: self.m.scroll_menu() self.menu_tick = 0 else: self.menu_tick += 1 # checking if any of the subsurfaces need updating and updating them if needed # in reverse order so the menu is being drawn first for i in range(2, -1, -1): if self.redraw_needed[i]: self.draw_func[i](*self.draw_func_args[i]) if i > 0: self.redraw_needed[i] = False self.flip_needed = True else: if self.game_redraw_tick[i] == 2: self.redraw_needed[i] = False self.flip_needed = True self.game_redraw_tick[i] = 0 else: self.game_redraw_tick[i] += 1 # draw the logo over menu - top left corner self.front_img.update() self.sprites_list.draw(self.misio) if self.sb.update_me: self.sb.draw(self.score_bar) self.flip_needed = True self.sb.update_me = False if self.flip_needed: # update the screen with what we've drawn. if self.show_dialogwnd: self.sb.draw(self.score_bar) self.dialog.update() pygame.display.flip() self.flip_needed = False # Limit to 30 frames per second but most redraws are made when needed - less often # 30 frames per second used mainly for event handling self.game_board.process_ai() clock.tick(30) # close eSpeak process, quit pygame, collect garbage and exit the game. if self.config.settings_changed: self.config.save_settings(self.db) clock.tick(300) self.db.close() if self.speaker.process is not None: self.speaker.stop_server() # self.speaker.stop_server_en() pygame.quit() gc.collect() if android is None: os.sys.exit()
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
WHITE = ((255, 255, 255)) BLACK = ((0, 0, 0)) BLUE = ((85, 191, 223)) speed = 4 speed_2 = 6 x = 770 y = 360 windowSurface = pygame.display.set_mode((1280, 770)) player_circle = pygame.image.load("img/final_circle.png") control_circle = pygame.draw.circle(windowSurface, WHITE, (1080, 550), 100, 4) while True: if android: if android.check_pause(): android.wait_for_resume() velocity_reading = android.accelerometer_reading() 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() mouse_pos = pygame.mouse.get_pos() ### x-axis acceleration
def androidpause(): if android: if android.check_pause(): assets.save_game("android_pause",True) android.wait_for_resume()