def user_answer(self, block, trial): reverse = block.get_factor('reverse') correct_answer = trial.get_factor('sequence') seq_length = trial.get_factor('sequence_length') input_method = self.exp.config.get('ANDROID', 'input_method') if android and input_method == 'keyboard': android.show_keyboard() self.exp.keyboard.clear() if not android or input_method == 'keyboard' or input_method == 'none': user_input = io.TextInput(_('remember_sequence_reverse') if reverse else _('remember_sequence'), length=seq_length, position=self.input_offset, user_text_size=self.input_text_size ).get().strip() android.hide_keyboard() if android else None else: pass answer = user_input[::-1] if reverse else user_input format = {'sequence': correct_answer, 'sequence_length': seq_length, 'sequence_reverse': correct_answer[::-1]} if answer.strip() == correct_answer: self.exp._show_message('', 'correct_trial', format=format) else: self.exp._show_message('', 'incorrect_trial_reverse' if reverse else 'incorrect_trial', format=format) return(answer == correct_answer, user_input)
def _key_handler(a, key, b, c, d): global container if key == 1001: android.hide_keyboard() if container.shown: try: container.popup.dismiss() except: sys.exit(0) else: global taptime t = time.time() if t - taptime <= 1: # Double tap sys.exit(0) else: label = Label(text="Press Back again to exit", halign="center", size_hint=(1, None), height=20) self.root.add_widget(label, 1) container.label = label def rmlabel(*args, **kwargs): global container self.root.remove_widget(container.label) del container.label Clock.schedule_once(rmlabel, 1) taptime = t elif key == 1000: if not container.shown: self.show_help() else: container.popup.dismiss()
def hide_kbd_or_exit(self, *args): if platform == "android" and not self.exitnext: android.hide_keyboard() self.exitnext = True Clock.schedule_once(lambda *args: setattr(self, "exitnext", False), 2) self.toast(("Press Back again to exit"), 0) else: self.stop()
def toggle_keyboard(): """ Togle soft keyboard visibility. """ global keyboard_visible if keyboard_visible: android.hide_keyboard() else: android.show_keyboard() keyboard_visible = not keyboard_visible
def show_virtual_keyboard(self, visible=True): if android == None: return self.persistent_virtual_keyboard = visible if visible: android.show_keyboard() else: android.hide_keyboard()
def hide_vkbd(self, *args): """Hide the virtual keyboard. Arguments: - `self`: """ Logger.debug("DiceWidget: hiding keyboard") if IS_ANDROID: android.hide_keyboard()
def sf(self,v): self._focused = v if android: if isinstance(v,editbox): if not self._keyboard: self._keyboard = True android.show_keyboard() else: if self._keyboard: self._keyboard = False android.hide_keyboard()
def show_virtual_keyboard(self, visible=True): """See openexp._keyboard.legacy""" if android == None: return self.persistent_virtual_keyboard = visible if visible: android.show_keyboard() else: android.hide_keyboard()
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 handle_android_back(self): if platform() == "android": import android res = android.hide_keyboard() print "HANDLING android back..." self.go_back()
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 get_key(self, keylist=None, timeout=None): """See openexp._keyboard.legacy""" 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) else: # If we're not on Android, simply use the same logic as the # legacy back-end. if event.unicode in invalid_unicode or \ event.unicode not in printable: 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 process_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.quit() elif event.key == pygame.K_SPACE: self.release_a_ball() elif event.key == pygame.K_a: if DEBUGGING: self.load_level(self.level + 1) elif event.key == pygame.K_f: if DEBUGGING: self.create_powerup((480, 0)) elif event.key == pygame.K_y and self.game_over: if android: android.hide_keyboard() self.restart() elif event.key == pygame.K_n and self.game_over: if android: android.hide_keyboard() self.force_quit() elif event.type == pygame.MOUSEBUTTONDOWN: self.touching = True if not android: self.release_a_ball() elif event.type == pygame.MOUSEBUTTONUP: if android: self.release_a_ball() self.touching = False elif event.type == self.WAIT_NEW_LEVEL: self.waiting_for_level = False self.powerups.empty() self.load_level(self.level + 1) pygame.time.set_timer(self.WAIT_NEW_LEVEL, 0) elif event.type == self.TIME_DISTORTION_FIELD: self.disable_time_distortion_field() if android: if self.touching: return pygame.mouse.get_pos()[0] else: return 0 return pygame.mouse.get_rel()[0]
def process_input(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.quit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: self.quit() elif event.key == pygame.K_SPACE: self.release_a_ball() elif event.key == pygame.K_a: if DEBUGGING: self.load_level(self.level+1) elif event.key == pygame.K_f: if DEBUGGING: self.create_powerup((480,0)) elif event.key == pygame.K_y and self.game_over: if android: android.hide_keyboard() self.restart() elif event.key == pygame.K_n and self.game_over: if android: android.hide_keyboard() self.force_quit() elif event.type == pygame.MOUSEBUTTONDOWN: self.touching = True if not android: self.release_a_ball() elif event.type == pygame.MOUSEBUTTONUP: if android: self.release_a_ball() self.touching = False elif event.type == self.WAIT_NEW_LEVEL: self.waiting_for_level = False self.powerups.empty() self.load_level(self.level+1) pygame.time.set_timer(self.WAIT_NEW_LEVEL, 0) elif event.type == self.TIME_DISTORTION_FIELD: self.disable_time_distortion_field() if android: if self.touching: return pygame.mouse.get_pos()[0] else: return 0 return pygame.mouse.get_rel()[0]
def getBall(self): if android: android.hide_keyboard() return ( self.gender, self.faith, self.faithLevel, self.str, self.itl, self.dex, 1, 1, # hunger, thirst const.blocksize, # img dimensions const.blocksize, self.HP, self.HP, # max, current self.MP, self.MP, 0, 10, # score, keys 3, 0, 50, # level, current XP, XP for next lev [], None, # weapons, eq. weapons [], [ None, None, None, #armor, eq. armor (helmet, plate, shield, None, None, None, #ring, ring, amulet, None, None, None ], #cloak, boots, ?) range(100), # items [], # spells 100, [False, False, False], 0, #gold, stats, slain self.name)
def get_key(self): if not self.persistent_virtual_keyboard and android is not None: android.show_keyboard() start_time = pygame.time.get_ticks() time = start_time keylist = self.keylist 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: self.experiment.pause() # 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 is not 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 is None or key in keylist: if not self.persistent_virtual_keyboard and android is not None: android.hide_keyboard() return key, 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() if not self.persistent_virtual_keyboard and android is not None: android.hide_keyboard() return None, time
def loadSavedGame(titleScreen): if android: android.hide_keyboard() try: FX.displayLoadingMessage(titleScreen, 'Loading game file...') savFile = gzip.GzipFile('ransack0.sav', 'rb', 1) FX.displayLoadingMessage(titleScreen, 'Loading saved game...') ball = cPickle.load(savFile) savFile.close() Game = game.game(images, screen, clock, iFace, FX, iH, titleScreen, SFX, myWorldBall, ball[0], ball[1], ball[2], ball[3]) FX.fadeOut(0) iFace.state = 'game' if Game.mainLoop(): endScreen(Game, "You Win!") else: endScreen(Game, "Game Over.") FX.fadeOut(0) except IOError as err: print('loadSavedGame error: {}'.format(err))
def getBall(self): if android: android.hide_keyboard() return (self.gender, self.faith, self.faithLevel, self.str, self.itl, self.dex, 1, 1, # hunger, thirst const.blocksize, # img dimensions const.blocksize, self.HP, self.HP, # max, current self.MP, self.MP, 0, 10, # score, keys 3, 0, 50, # level, current XP, XP for next lev [], None, # weapons, eq. weapons [], [None, None, None, #armor, eq. armor (helmet, plate, shield, None, None, None, #ring, ring, amulet, None, None, None], #cloak, boots, ?) range(100), # items [], # spells 100, [False, False, False], 0, #gold, stats, slain self.name )
def demandeUtilisateur(screen, question, answer=None): "ask(screen, question) -> answer" if android: android.init() android.show_keyboard() entryAnswer = False pygame.font.init() current_string = [] if not answer == None: for i in answer: current_string.append(i) question = question + " : " afficherDialog(screen, question + string.join(current_string, "")) while entryAnswer == False: event = pygame.event.wait() if event.type == pygame.KEYDOWN: inkey = event.key if inkey == pygame.K_BACKSPACE: current_string = current_string[0:-1] elif inkey == pygame.K_RETURN: entryAnswer = True elif inkey == pygame.K_MINUS: current_string.append("_") elif inkey <= 127: current_string.append(chr(inkey)) afficherDialog(screen, question + " " + string.join(current_string, "")) if android: android.hide_keyboard() return string.join(current_string, "")
def connect(self, nameInput, teamInput, serverInput, original, tetrifast): # Připojuje k serveru, kontrola vstupů if (len(nameInput.text) > 0) and (len(serverInput.text) > 0): self.root.nickname = nameInput.text.strip() self.root.team = teamInput.text.strip() self.root.server = serverInput.text.strip() self.root.tetrifast = tetrifast.active if self.root.onAndroid(): android.hide_keyboard() self.root.vibrate(0.05) self.root.Cfg[1] = self.root.nickname self.root.Cfg[2] = self.root.team if self.bookmark.active: self.root.addBookmark = True self.root.refreshCfg() self.root.connect_to_server() self.root.overlay.setSize() self.root.sm.current = 'GameScreen' self.root.sm.transition = SlideTransition(direction="left") else: Toast(text='Name or server missing', timeout=2).open()
def loadSavedGame(titleScreen): if android: android.hide_keyboard() try: FX.displayLoadingMessage(titleScreen, 'Loading game file...') savFile = gzip.GzipFile('ransack0.sav', 'rb', 1) FX.displayLoadingMessage(titleScreen, 'Loading saved game...') ball = cPickle.load(savFile) savFile.close() Game = game.game(images, screen, clock, iFace, FX, iH, titleScreen, SFX, myWorldBall, ball[0], ball[1], ball[2], ball[3]) FX.fadeOut(0) iFace.state = 'game' if Game.mainLoop(): endScreen(Game, "You Win!") else: endScreen(Game, "Game Over.") FX.fadeOut(0) except IOError as err: print ('loadSavedGame error: {}'.format(err))
def get_key(self, keylist=None, timeout=None): """See openexp._keyboard.legacy""" if 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 openexp.exceptions.response_error( \ "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. key = pygame.key.name(event.key) if keylist == None or key in keylist: if 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 android != None: android.hide_keyboard() return None, time
def release_keyboard(self, *largs): super(WindowPygame, self).release_keyboard(*largs) if android: android.hide_keyboard() return True
def close(): """ Android-specific cleanup. """ android.hide_keyboard()
def question_screen(screen, color, text_color, texto, max_length): # printamos pantalla fondo = Window("", "", WHITE, "DroidSans-Bold.ttf", 1, "sound0.wav", 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, color, WHITE, WHITE, WHITE) fondo.plot(screen) fuente = load_text_font("DroidSans-Bold.ttf", FNT_DIR, 26) size = fuente.size(texto) mensaje = fuente.render(texto, 1, text_color) screen.blit(mensaje, ((SCREEN_WIDTH / 2) - (size[0] / 2), (SCREEN_HEIGHT / 2) - ((size[1] / 2) * 3) )) # Inicializamos variables y = (SCREEN_HEIGHT / 2) + (size[1]) x = (SCREEN_WIDTH / 2) - (size[1] * (max_length-1) / 2) contador = 0 text = [0, 0, 0, 0] salir = True pygame.gfxdraw.rectangle(screen, (x - 5, y - 5, size[1] * (max_length - 1), 10 + size[1]), WHITE) pygame.display.flip() # Printamos if android: android.show_keyboard() while salir: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_0: if contador < max_length: text[contador] = 0 contador = contador + 1 elif event.key == pygame.K_1: if contador < max_length: text[contador] = 1 contador = contador + 1 elif event.key == pygame.K_2: if contador < max_length: text[contador] = 2 contador = contador + 1 elif event.key == pygame.K_3: if contador < max_length: text[contador] = 3 contador = contador + 1 elif event.key == pygame.K_4: if contador < max_length: text[contador] = 4 contador = contador + 1 elif event.key == pygame.K_5: if contador < max_length: text[contador] = 5 contador = contador + 1 elif event.key == pygame.K_6: if contador < max_length: text[contador] = 6 contador = contador + 1 elif event.key == pygame.K_7: if contador < max_length: text[contador] = 7 contador = contador + 1 elif event.key == pygame.K_8: if contador < max_length: text[contador] = 8 contador = contador + 1 elif event.key == pygame.K_9: if contador < max_length: text[contador] = 9 contador = contador + 1 elif event.key == pygame.K_BACKSPACE: if contador > 0: contador = contador - 1 elif event.key == pygame.K_RETURN: salir = False pygame.gfxdraw.box(screen, (x, y, size[0] * 0.6, size[1]), color) if (contador == 1): mensaje_text = fuente.render("{0}".format(text[0]), 1, WHITE) if (contador == 2): mensaje_text = fuente.render("{0} {1}".format(text[0], text[1]), 1, WHITE) if (contador == 3): mensaje_text = fuente.render("{0} {1} {2}".format(text[0], text[1], text[2]), 1, WHITE) if (contador == 4): mensaje_text = fuente.render("{0} {1} {2} {3}".format(text[0], text[1], text[2], text[3]), 1, WHITE) if (contador > 0): screen.blit(mensaje_text, (x, y)) pygame.display.flip() # Printamos if android: android.hide_keyboard() return text
def handle_android_back(self): if platform() == 'android': import android res = android.hide_keyboard() print 'HANDLING android back...' self.go_back()
def get_player(self): name = "" ai = False invert = False shift = False while True: pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYUP: shift = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_RETURN: self.add_player_to_list(name,ai,invert) name = "" pygame.display.update(self.name_box) elif event.key == pygame.K_LSHIFT or event.key == pygame.K_RSHIFT: shift = True elif event.key == pygame.K_DELETE or event.key == pygame.K_BACKSPACE: name = name[:-1] self.name.surface = fonts.h1.render(name,1,(0,0,0),(255,255,255)) pygame.draw.rect(self.screen,(255,255,255),self.name_box) self.screen.blit(self.name.surface,self.name.rect) pygame.display.update(self.name_box) elif event.key in [32]+range(48,58)+range(97,123): if len(name)<=16: if shift and event.key in range(97,123): name += chr(event.key).capitalize() else: name += chr(event.key) self.name.surface = fonts.h1.render(name,1,(0,0,0),(255,255,255)) self.screen.blit(self.name.surface,self.name_box,(0,0,self.name_box.width,self.name_box.height)) pygame.display.update(self.name_box) else: print event.key elif event.type == pygame.MOUSEBUTTONUP: if self.add_player.rect.collidepoint(event.pos): self.add_player_to_list(name,ai,invert) name = "" elif self.del_player.rect.collidepoint(event.pos): if len(self.players): self.players.pop() self.draw_player_list() elif self.done.rect.collidepoint(event.pos): if android: android.hide_keyboard() return self.players elif self.ai_off.rect.collidepoint(event.pos): ai = not ai if ai: self.screen.blit(self.ai_on.surface,self.ai_on.rect) else: self.screen.blit(self.ai_off.surface,self.ai_off.rect) pygame.display.update(self.ai_off.rect) elif self.invert_off.rect.collidepoint(event.pos): invert = not invert if invert: self.screen.blit(self.invert_on.surface,self.invert_on.rect) else: self.screen.blit(self.invert_off.surface,self.invert_off.rect) pygame.display.update(self.invert_off.rect) elif self.name_box.collidepoint(event.pos): if android: android.show_keyboard() else: if android: android.hide_keyboard()
def main(): # Check if sound and font are supported if not pygame.font: print "Warning, fonts disabled" # Constants FPS = 35 SCREEN_WIDTH, SCREEN_HEIGHT = 480, 800 SCREENRECT = Rect(0, 0, 480, 800) SPEED = 5 BACKGROUND_COLOR = (0, 0, 0) # font = pygame.font.Font(None, 30) score = 0 levelNum = 0 # Initialize Pygame, the clock (for FPS), and a simple counter pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 0) pygame.display.set_caption('Sky High') clock = pygame.time.Clock() # Game loop while True: time_passed = clock.tick(FPS) if levelNum == 0: levelNum = title(screen) # Returns 99 if "Play Game" is clicked, 100 if "View Highscores" is clicked elif levelNum == 100: levelNum = scores(screen) # Returns 0 when player exits highscore screen levelNum = 0 else: # levelNum == 99: t = game(screen) score = score + int(t) if android: filename = "highscores.txt" else: filename = "highscores.txt" highscore = [("",0), ("",0), ("",0), ("",0), ("",0), ("",0), ("",0), ("",0)] try: # If there is already a highscores file, try opening it f = open(filename, "r+") except IOError: # If there is no highscores file, create one and add 0's to it f = open(filename, "w+") cPickle.dump(highscore, f) f.seek(0) try: highscore = cPickle.load(f) except EOFError: pass # Just don't load anything username = "******" if android: ## android.show_keyboard() ## ## #KEY MAPPING ## android.map_key(android.KEYCODE_BACK, pygame.K_BACKSPACE) ## android.map_key(android.KEYCODE_ENTER, pygame.K_RETURN) ## android.map_key(android.KEYCODE_SPACE, pygame.K_SPACE) ## android.map_key(android.KEYCODE_A, pygame.K_a) ## android.map_key(android.KEYCODE_B, pygame.K_b) ## android.map_key(android.KEYCODE_C, pygame.K_c) ## android.map_key(android.KEYCODE_D, pygame.K_d) ## android.map_key(android.KEYCODE_E, pygame.K_e) ## android.map_key(android.KEYCODE_F, pygame.K_f) ## android.map_key(android.KEYCODE_G, pygame.K_g) ## android.map_key(android.KEYCODE_H, pygame.K_h) ## android.map_key(android.KEYCODE_I, pygame.K_i) ## android.map_key(android.KEYCODE_J, pygame.K_j) ## android.map_key(android.KEYCODE_K, pygame.K_k) ## android.map_key(android.KEYCODE_L, pygame.K_l) ## android.map_key(android.KEYCODE_M, pygame.K_m) ## android.map_key(android.KEYCODE_N, pygame.K_n) ## android.map_key(android.KEYCODE_O, pygame.K_o) ## android.map_key(android.KEYCODE_P, pygame.K_p) ## android.map_key(android.KEYCODE_Q, pygame.K_q) ## android.map_key(android.KEYCODE_R, pygame.K_r) ## android.map_key(android.KEYCODE_S, pygame.K_s) ## android.map_key(android.KEYCODE_T, pygame.K_t) ## android.map_key(android.KEYCODE_U, pygame.K_u) ## android.map_key(android.KEYCODE_V, pygame.K_v) ## android.map_key(android.KEYCODE_W, pygame.K_w) ## android.map_key(android.KEYCODE_X, pygame.K_x) ## android.map_key(android.KEYCODE_Y, pygame.K_y) ## android.map_key(android.KEYCODE_Z, pygame.K_z) ## android.map_key(android.KEYCODE_0, pygame.K_0) ## android.map_key(android.KEYCODE_1, pygame.K_1) ## android.map_key(android.KEYCODE_2, pygame.K_2) ## android.map_key(android.KEYCODE_3, pygame.K_3) ## android.map_key(android.KEYCODE_4, pygame.K_4) ## android.map_key(android.KEYCODE_5, pygame.K_5) ## android.map_key(android.KEYCODE_6, pygame.K_6) ## android.map_key(android.KEYCODE_7, pygame.K_7) ## android.map_key(android.KEYCODE_8, pygame.K_8) ## android.map_key(android.KEYCODE_9, pygame.K_9) ## # android.map_key(android.ACTION_DOWN, pygame.KEYDOWN) ## ## for event in pygame.event.get(): ## ## if event.type == pygame.KEYDOWN: ## username = "" ## if event.key == pygame.K_t: ## username += "t" ## ## #username = raw_input("Enter name: ") android.hide_keyboard() # Add the new highscore if it is high enough newscore = (username, score) highscore.append(newscore) highscore = sorted(highscore, key=itemgetter(1), reverse = True) del highscore[-1] # Clear file's contents f.close() f = open(filename, "w+") # Write the new high score table cPickle.dump(highscore, f) f.close() levelNum = 0 score2 = score score = 0 username = "******" endgame(screen, score2) # Flip the display pygame.display.flip()
def wait(self, keys=None, duration=None, wait_for_keyup=False, check_for_control_keys=True): """Wait for keypress(es) (optionally for a certain amount of time). This function will wait for a keypress and returns the found key as well as the reaction time. (This function clears the event queue!) Parameters ---------- keys : int or list, optional a specific key or list of keys to wait for duration : int, optional maximal time to wait in ms wait_for_keyup : bool, optional if True it waits for key-up check_for_control_keys : bool, optional checks if control key has been pressed (default=True) """ if android is not None: android.show_keyboard() start = Clock._cpu_time() rt = None found_key = None self.clear() if keys is None: keys = self.default_keys if keys is not None and type(keys) is not list: keys = [keys] if wait_for_keyup: target_event = pygame.KEYUP else: target_event = pygame.KEYDOWN pygame.event.pump() done = False while not done: expyriment._active_exp._execute_wait_callback() for event in pygame.event.get(): if check_for_control_keys and Keyboard.process_control_keys(event): done = True elif event.type == target_event: if keys is not None: if event.key in keys: rt = int((Clock._cpu_time() - start) * 1000) found_key = event.key done = True else: rt = int((Clock._cpu_time() - start) * 1000) found_key = event.key done = True if duration and not done: done = int((Clock._cpu_time() - start) * 1000) >= duration time.sleep(0.0005) if self._logging: expyriment._active_exp._event_file_log("Keyboard,received,{0},wait"\ .format(found_key)) if android is not None: android.hide_keyboard() return found_key, rt
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 handle_android_back(self): if platform() == 'android': import android res = android.hide_keyboard() self.current = 'home'
def hide_keyboard(*args, **kwargs): android.hide_keyboard()