def input_string(self, prompt, x, y): # Draw a prompt string in the window using the current font # and colors. Check keys pressed by the user until an enter # key is pressed and return the sequence of key presses as a # str object. # - self is the Window # - prompt is the str to display # - x is the int x coord of the upper left corner of the # string in the window # - y is the int y coord of the upper left corner of the # string in the window key = K_SPACE answer = '' while key != K_RETURN: self.draw_string(prompt + answer + ' ', x, y) if not self.__auto_update__: update() key = self._get_key() key_state = get_pressed() if (K_SPACE <= key <= K_z): if key == K_SPACE: letter = ' ' else: letter = name(key) if key_state[K_LSHIFT] or key_state[K_RSHIFT] or key_state[ K_CAPSLOCK]: letter = letter.upper() answer = answer + letter if key == K_BACKSPACE: answer = answer[0:len(answer) - 1] return answer
def onKeyUp(self, event): from pygame import key if(self.focused): if(key.name(event.key) == "return"): self.setText(self.clean) self.releaseEvent() if(self.action): self.action(self.clean) self.focused = False return if(key.name(event.key) == "backspace"): self.clean = self.clean[:-1] elif key.name(event.key) == "space": self.clean += " " else: self.clean += key.name(event.key) self.setText(self.clean + "|")
def key_down(self, evt): keyname = key.name(evt.key) if keyname == config.config.get("Keys", "Up"): self.nudge(Vector(0, 1, 0)) if keyname == config.config.get("Keys", "Down"): self.nudge(Vector(0, -1, 0)) Z = self.get_root( ).mcedit.editor.mainViewport.cameraVector # xxx mouthful absZ = map(abs, Z) if absZ[0] < absZ[2]: forward = (0, 0, (-1 if Z[2] < 0 else 1)) else: forward = ((-1 if Z[0] < 0 else 1), 0, 0) back = map(int.__neg__, forward) left = forward[2], forward[1], -forward[0] right = map(int.__neg__, left) if keyname == config.config.get("Keys", "Forward"): self.nudge(Vector(*forward)) if keyname == config.config.get("Keys", "Back"): self.nudge(Vector(*back)) if keyname == config.config.get("Keys", "Left"): self.nudge(Vector(*left)) if keyname == config.config.get("Keys", "Right"): self.nudge(Vector(*right))
def handle_am_input(self, e): ship_back = None if e.type == KEYDOWN: ship_back = self.main_action_menu.input_master.process_input( key.name(e.key)) if ship_back: return ship_back
def key_down(self, evt): keyname = key.name(evt.key) if keyname == config.config.get("Keys", "Up"): self.nudge((0, 1, 0)) if keyname == config.config.get("Keys", "Down"): self.nudge((0, -1, 0)) Z = self.get_root().mcedit.editor.mainViewport.cameraVector #xxx mouthful absZ = map(abs, Z) if absZ[0] < absZ[2]: forward = (0, 0, (-1 if Z[2] < 0 else 1)) else: forward = ((-1 if Z[0] < 0 else 1), 0, 0) back = map(int.__neg__, forward) left = forward[2], forward[1], -forward[0] right = map(int.__neg__, left) if keyname == config.config.get("Keys", "Forward"): self.nudge(forward) if keyname == config.config.get("Keys", "Back"): self.nudge(back) if keyname == config.config.get("Keys", "Left"): self.nudge(left) if keyname == config.config.get("Keys", "Right"): self.nudge(right)
def getKey(self, evt, movement=False): keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: keyname = keyname[5:] elif 'right' in keyname and len(keyname) > 6: keyname = keyname[6:] try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) finally: if keyname == 'Meta': keyname = 'Ctrl' newKeyname = "" if evt.shift and keyname != "Shift" and not movement: newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl" and not movement: newKeyname += "Ctrl-" if evt.alt and keyname != "Alt" and not movement: newKeyname += "Alt-" keyname = newKeyname + keyname if keyname == 'Enter': keyname = 'Return' return keyname
def handle_inventory_input(self, e): ship_back = None if e.type == KEYDOWN: ship_back = self.inventory_menu.input_master.process_input( key.name(e.key)) if ship_back: return ship_back
def getKey(evt, i=0): keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: keyname = keyname[5:] elif 'right' in keyname and len(keyname) > 6: keyname = keyname[6:] try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) finally: if keyname == 'Meta': keyname = 'Ctrl' newKeyname = "" if evt.shift == True and keyname != "Shift" and i != 1: newKeyname += "Shift-" if (evt.ctrl == True or evt.cmd == True) and keyname != "Ctrl" and i != 1: newKeyname += "Ctrl-" if evt.alt == True and keyname != "Alt" and i != 1: newKeyname += "Alt-" keyname = newKeyname + keyname if keyname == 'Enter': keyname = 'Return' return keyname
def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) keyname = keyname.replace("right ", "").replace("left ", "").replace("Meta", "Ctrl").replace("Enter", "Return").replace("Delete", "Del") try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) except: pass if movement: return keyname newKeyname = "" if evt.shift and keyname != "Shift": newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl": newKeyname += "Ctrl-" if evt.alt and keyname != "Alt": newKeyname += "Alt-" keyname = newKeyname + keyname if newKeyname: return keyname if sys.platform == 'linux2': test_key = getattr(evt, 'scancode', None) tool_keys = [10, 11, 12, 13, 14, 15, 16, 17, 18] else: test_key = keyname tool_keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if test_key in tool_keys: keyname = str(tool_keys.index(test_key) + 1) elif test_key == 19: keyname = '0' return keyname
def typed(self, event): tecla = event.data['key'] mods = event.data['mod'] shift = mods & KMOD_SHIFT or mods & KMOD_CAPS raw = key.name(tecla).strip('[]') name = None if raw == 'space': name = ' ' elif raw == 'backspace': self.del_character('backward') elif raw == 'delete': self.del_character('forward') elif raw in ['enter', 'return']: name = '\n' elif raw.isdecimal(): if tecla == K_0: name = '=' if shift else raw elif tecla == K_1: name = '!' if shift else raw elif tecla == K_2: name = '"' if shift else raw elif tecla == K_3: name = '#' if shift else raw elif tecla == K_4: name = '$' if shift else raw elif tecla == K_5: name = '%' if shift else raw elif tecla == K_6: name = '&' if shift else raw elif tecla == K_7: name = '•' if shift else raw elif tecla == K_8: name = '(' if shift else raw elif tecla == K_9: name = ')' if shift else raw elif raw.isalpha and len(raw) == 1: if raw == '.': name = ':' if shift else raw elif raw == ',': name = ';' if shift else raw elif raw == "´": self.acento = True elif raw == "'": name = "?" if shift else "'" elif raw == '¡': name = '¿' if shift else '¡' else: name = raw.upper() if shift else raw if self.acento: vowels = 'aeiou' accented_v = 'áéíóú' if raw in vowels: name = accented_v[vowels.index(raw)] name = name.upper() if shift else name if name is not None: self.acento = False self.input_character(name)
def check(self): """Respond to user input or internal game events..""" for e in event.get(): t = e.type if t in (KEYDOWN, KEYUP): key_name = key.name(e.key) if t == KEYDOWN: self.on_key_down(key_name) elif t == KEYUP: self.on_key_up(key_name)
def check_events(self): """Input checking.""" cursor_keys = ("move_up", "move_down", "move_left", "move_right") screen_keys = ("quit", "new_game") for e in event.get(): k = "" if e.type == JOYAXISMOTION: if e.axis == 1: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "up" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "down" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action if e.axis == 0: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "left" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "right" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action elif e.type in (KEYDOWN, KEYUP): k = key.name(e.key) if e.type == KEYDOWN: _type = "keydown" elif e.type == KEYUP: _type = "keyup" if k in State.controls: if self._last_joystick_action: sprite = State.joystick if _type == "keyup": self._last_joystick_action = None else: sprite = State.cursor control = getattr(actions, State.controls[k]) if _type == "keydown": State.pressed.append(control) ctrl = State.controls[k] if ctrl in cursor_keys: control (sprite) else: control(State.screen) elif _type == "keyup": if control in State.pressed: del State.pressed[State.pressed.index(control)] actions.move_stop(sprite) if State.pressed: State.pressed[-1](sprite)
def on_keydown(self, tecla): mods = key.get_mods() shift = mods & KMOD_SHIFT or mods & KMOD_CAPS raw = key.name(tecla).strip('[]') name = None if raw == 'space': self.input_character(' ') elif raw == 'backspace': self.del_character() elif raw in ['enter', 'return']: self.button_trigger() elif raw.isdecimal(): if tecla == K_0: name = '=' if shift else raw elif tecla == K_2: name = '"' if shift else raw elif tecla == K_3: name = '#' if shift else raw elif tecla == K_4: name = '$' if shift else raw elif tecla == K_5: name = '%' if shift else raw elif tecla == K_6: name = '&' if shift else raw elif tecla == K_7: name = '•' if shift else raw elif tecla == K_8: name = '(' if shift else raw elif tecla == K_9: name = ')' if shift else raw else: name = raw elif raw.isalpha and len(raw) == 1: if raw == '.': name = ':' if shift else raw elif raw == ',': name = ';' if shift else raw elif raw == "´": self.acento = True elif raw == "'": name = "?" if shift else "'" elif raw == '¡': name = '¿' if shift else '¡' else: name = raw.upper() if shift else raw if self.acento: vowels = 'aeiou' accented_v = 'áéíóú' if raw in vowels: name = accented_v[vowels.index(raw)] name = name.upper() if shift else name if name is not None: self.acento = False self.input_character(name)
def useKeys(i): keyName = self.getKey(movement=True, keyname=key.name(i)) if keyName == self.editor.sprintKey: self.sprint = True if allKeys[K_LCTRL] or allKeys[K_RCTRL] or allKeys[K_RMETA] or allKeys[K_LMETA]: return if keyName in self.editor.movements: self.changeMovementKeys(self.editor.movements.index(keyName), keyName) if keyName in self.editor.cameraPan: self.changeCameraKeys(self.editor.cameraPan.index(keyName))
def create_anims_txt(self, anims): txt_list = [] ix = 0 for anim in anims: key_name = key.name(ANIM_KEYS[ix]) txt_list.append( Txt(FONT, 8, '({0}): {1}'.format(key_name, anim), WHITE, 600, ix * 8 + 10, self)) ix += 1 # cur_ix = self.anims.index(self.target.anim) txt_list[cur_ix].color = GREEN return txt_list
def run_trial(trial_pars, subj_info, data_file): ''' Run a single trial. trial_pars -- a list specifying trial parameters, [cue_pos, tar_pos, isi, cueing, cor_key] subj_info -- info about the subject [id, name, age] data_file -- an open file to save the trial data.''' # Show the fixation then wait for 1000 ms draw_frame('fix', trial_pars) time.wait(1000) # Show the cue for 100 ms draw_frame('cue', trial_pars) time.wait(100) # Inter-stimulus interval (ISI) draw_frame('fix', trial_pars) time.wait(trial_pars[2]) # Show the target and register a keypress response draw_frame('target', trial_pars) tar_onset = time.get_ticks() tar_resp = -32768 # response time resp_key = -32768 # key pressed # Check for key presses time_out = False got_key = False event.clear() # clear bufferred events while not (time_out or got_key): # Cehck for time out (1500 ms) if time.get_ticks() - tar_onset > 1500: time_out = True # Check if any key has been pressed for ev in event.get(): if ev.type == KEYDOWN: if ev.key in [K_z, K_SLASH]: tar_resp = time.get_ticks() resp_key = key.name(ev.key) got_key = True # write data to file trial_data = subj_info + trial_pars + [tar_onset, tar_resp, resp_key] trial_data = map(str, trial_data) data_file.write(','.join(trial_data) + '\n') # ITI (inter-trial_interval) draw_frame('fix', trial_pars) time.wait(1500)
def on_keydown(self, tecla): mods = key.get_mods() shift = mods & K_LSHIFT or mods & K_RSHIFT or mods & KMOD_CAPS name = key.name(tecla).strip('[]') if name == 'space': self.input_character(' ') elif name == 'backspace': self.del_character() elif name == 'enter' or name == 'return': self.button_trigger() elif name.isalnum(): if shift: name = name.upper() self.input_character(name)
def set_key_state(event): ''' キーの状態を保持する ''' # キーの番号から名前に変換する name = key.name(event.key) # イベントの種類で 1 か 0 をセットする # キーが離されたイベント if event.type == pygame.KEYUP: keymap[name] = 0 # キーが押されたイベント elif event.type == pygame.KEYDOWN: keymap[name] = 1
def event(self, event): if event.type == PG.KEYDOWN and event.key == PG.K_ESCAPE: G.Globals.STATE = Menu.Menu() elif event.type == PG.KEYDOWN and ((event.key >= PG.K_a and event.key <= PG.K_z) or len(self.initials) is 3): if len(self.initials) is 3: self.send_data() elif self.first_key_pressed: self.first_key_pressed = False self.surf = GameOver.FONT.render("".join(self.initials), True, self.color) else: self.initials.append(PK.name(event.key)) self.surf = GameOver.FONT.render("".join(self.initials), True, self.color) if len(self.initials) == 4: self.send_data()
def event(self, event): if event.type == PG.KEYDOWN and event.key == PG.K_ESCAPE: G.Globals.STATE = Menu.Menu() elif event.type == PG.KEYDOWN and ( (event.key >= PG.K_a and event.key <= PG.K_z) or len(self.initials) is 3): if len(self.initials) is 3: self.send_data() elif self.first_key_pressed: self.first_key_pressed = False self.surf = GameOver.FONT.render("".join(self.initials), True, self.color) else: self.initials.append(PK.name(event.key)) self.surf = GameOver.FONT.render("".join(self.initials), True, self.color) if len(self.initials) == 4: self.send_data()
def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: keyname = keyname[5:] elif 'right' in keyname and len(keyname) > 6: keyname = keyname[6:] try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) finally: if keyname == 'Meta': keyname = 'Ctrl' if not movement: newKeyname = "" if evt.shift and keyname != "Shift": newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl": newKeyname += "Ctrl-" if evt.alt and keyname != "Alt": newKeyname += "Alt-" keyname = newKeyname + keyname if not newKeyname: if sys.platform == 'linux2': test_key = getattr(evt, 'scancode', None) tool_keys = [10, 11, 12, 13, 14, 15, 16, 17, 18] else: test_key = keyname tool_keys = [ '1', '2', '3', '4', '5', '6', '7', '8', '9' ] if test_key in tool_keys: keyname = str(tool_keys.index(test_key) + 1) elif test_key == 19: keyname = '0' if keyname == 'Enter': keyname = 'Return' elif keyname == 'Delete': keyname = 'Del' return keyname
def draw(self, surface, offsetX: int, offsetY: int): self.creature.draw(surface, offsetX, offsetY) key_trigger_times = self.get_key_trigger_times() for i, v in enumerate(self.keyStates): muscle_cycle_time = self.triggerClock % self.keybinds[v].cycle_time keyColor = colour.KEY_RED if self.keyStates[v] else colour.KEY_BLUE newMuscleState = colour.RED if muscle_cycle_time < self.keybinds[v].change_time else colour.BLUE key_combo_height = surface.get_height()//2 + 150 draw.rect(surface, keyColor, (i*76+15, key_combo_height, 50, 10)) draw.rect(surface, newMuscleState, (i*76+5, key_combo_height + key_trigger_times[v][0] * 3-10, 70, 20)) key_font_render = KEY_FONT.render(key.name(v).upper(), True, colour.LIGHT_GREY, keyColor) surface.blit(key_font_render, (i*76 + 5 + 35 - key_font_render.get_width()//2, key_combo_height - key_font_render.get_height()))
def getKey(evt=None, movement=False, keyname=None): if keyname is None: keyname = key.name(evt.key) if 'left' in keyname and len(keyname) > 5: keyname = keyname[5:] elif 'right' in keyname and len(keyname) > 6: keyname = keyname[6:] try: keyname = keyname.replace(keyname[0], keyname[0].upper(), 1) finally: if keyname == 'Meta': keyname = 'Ctrl' if not movement: newKeyname = "" if evt.shift and keyname != "Shift": newKeyname += "Shift-" if (evt.ctrl or evt.cmd) and keyname != "Ctrl": newKeyname += "Ctrl-" if evt.alt and keyname != "Alt": newKeyname += "Alt-" keyname = newKeyname + keyname if not newKeyname: if sys.platform == 'linux2': test_key = getattr(evt, 'scancode', None) tool_keys = [10, 11, 12, 13, 14, 15, 16, 17, 18] else: test_key = keyname tool_keys = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] if test_key in tool_keys: keyname = str(tool_keys.index(test_key) + 1) elif test_key == 19: keyname = '0' if keyname == 'Enter': keyname = 'Return' elif keyname == 'Delete': keyname = 'Del' return keyname
def check_events(self): """Input checking.""" cursor_keys = ("move_up", "move_down", "move_left", "move_right") screen_keys = ("quit", "new_game") for e in event.get(): if e.type in (KEYDOWN, KEYUP): k = key.name(e.key) if k in State.controls: control = getattr(actions, State.controls[k]) if e.type == KEYDOWN: State.pressed.append(control) ctrl = State.controls[k] if ctrl in cursor_keys: control(State.cursor) else: control(State.screen) if e.type == KEYUP: if control in State.pressed: del State.pressed[State.pressed.index(control)] actions.move_stop(State.cursor) if State.pressed: State.pressed[-1](State.cursor)
def update(cls): cls.clock.tick(60) events = event.get( [KEYDOWN, MOUSEBUTTONDOWN, MOUSEBUTTONUP, QUIT, MOUSEMOTION]) event.clear() for e in events: if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): EventHandler.trigger('salir', 'engine', {'mensaje': 'normal'}) elif e.type == KEYDOWN and not cls.locked: if e.key in (K_KP_ENTER, K_KP_EQUALS): EventHandler.trigger('Fin', cls.origin) elif e.key == K_BACKSPACE: EventHandler.trigger('BackSpace', cls.origin) elif e.key == K_UP: EventHandler.trigger('Arrow', cls.origin, { 'word': 'arriba', 'delta': -1 }) elif e.key == K_DOWN: EventHandler.trigger('Arrow', cls.origin, { 'word': 'abajo', 'delta': +1 }) else: name = key.name(e.key).strip('[]') if len( name ) == 1: # single character, excludes "space" and things like that. if name == '.': # bc there's not other way to identifying it. EventHandler.trigger('Key', cls.origin, {'value': '.'}) elif name.isdigit(): EventHandler.trigger('Key', cls.origin, {'value': name}) elif name.isalpha(): if e.mod & KMOD_LSHIFT or e.mod & KMOD_RSHIFT: name = name.capitalize() EventHandler.trigger('Typed', cls.origin, {'value': name}) elif name == 'space': EventHandler.trigger('Typed', cls.origin, {'value': ' '}) elif e.type == MOUSEBUTTONDOWN: widgets = [ i for i in cls.contents.sprites() if i.rect.collidepoint(e.pos) ] widgets.sort(key=lambda o: o.layer, reverse=True) if not cls.locked or widgets[0] is cls.the_one: cls.origin = widgets[0].on_mousebuttondown(e) else: cls.the_one.blink() elif e.type == MOUSEBUTTONUP: widgets = [ i for i in cls.contents.sprites() if i.rect.collidepoint(e.pos) ] widgets.sort(key=lambda o: o.layer, reverse=True) widgets[0].on_mousebuttonup(e) elif e.type == MOUSEMOTION: x, y = e.pos for widget in cls.contents.sprites(): if widget.rect.collidepoint((x, y)): widget.on_mousemotion(e.rel) x, y = mouse.get_pos() for widget in cls.contents.sprites(): if widget.rect.collidepoint( (x, y)) and (not cls.locked or widget is cls.the_one): widget.on_mouseover() cls.contents.update()
def setKey(self, inkey): from pygame import key self.lastKey = inkey self.setText("Key: " + key.name(self.lastKey)) self.releaseEvent()
def run_modal(self, modal_widget): if self.editor is None: self.editor = self.mcedit.editor self.selectTool = self.editor.toolbar.tools[0] old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self #from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = False self.bonus_draw_time = False while modal_widget.modal_result is None: try: if not self.mcedit.version_checked: if not self.mcedit.version_lock.locked(): self.mcedit.version_checked = True self.mcedit.check_for_version() self.hover_widget = self.find_widget(pygame.mouse.get_pos()) if not self.bonus_draw_time: self.bonus_draw_time = True if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) pygame.display.flip() self.frames += 1 events = pygame.event.get() if not events: self.call_idle_handlers() for event in events: type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.bonus_draw_time = False t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.bonus_draw_time = False add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse('mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.bonus_draw_time = False mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse('mouse_up', event) elif type == KEYDOWN: key_down = event.key set_modifier(key_down, True) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.takeAScreenshot.get(): self.take_screenshot() self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key_up = event.key set_modifier(key_up, False) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.showBlockInfo.get() and self.editor.toolbar.tools[0].infoKey == 1: self.editor.toolbar.tools[0].infoKey = 0 self.editor.mainViewport.showCommands() if self.nudgeDirection is not None: keyname = self.getKey(movement=True, keyname=key.name(key_up)) for i, move_key in enumerate(self.editor.movements): if keyname == move_key and i == self.nudgeDirection: self.nudgeDirection = None self.testTime = None self.testTimeBack = 0.4 self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: if self.redraw_every_frame: self.bonus_draw_time = False else: self.bonus_draw_time = True if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor(event) self.begin_frame() elif type == VIDEORESIZE: self.bonus_draw_time = False self.size = (event.w, event.h) elif type == VIDEOEXPOSE: if self.mcedit.displayContext.win and self.mcedit.displayContext.win.get_state() == 1: x, y = config.settings.windowX.get(), config.settings.windowY.get() pos = self.mcedit.displayContext.win.get_position() if pos[0] != x: config.settings.windowX.set(pos[0]) if pos[1] != y: config.settings.windowY.set(pos[1]) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) if not self.sessionStolen: try: if self.editor.level is not None and hasattr(self.editor.level, "checkSessionLock"): self.editor.level.checkSessionLock() except Exception as e: log.warn(u"Error reading chunk (?): %s", e) traceback.print_exc() if not config.session.override.get(): self.sessionStolen = True else: self.editor.level.acquireSessionLock() if self.editor.level is not None: self.editor.cameraInputs = [0., 0., 0., 0., 0., 0.] self.editor.cameraPanKeys = [0., 0., 0., 0.] def useKeys(i): keyName = self.getKey(movement=True, keyname=key.name(i)) if keyName == self.editor.sprintKey: self.sprint = True if allKeys[K_LCTRL] or allKeys[K_RCTRL] or allKeys[K_RMETA] or allKeys[K_LMETA]: return if keyName in self.editor.movements: self.changeMovementKeys(self.editor.movements.index(keyName), keyName) if keyName in self.editor.cameraPan: self.changeCameraKeys(self.editor.cameraPan.index(keyName)) allKeys = key.get_pressed() for x in enumerate(allKeys): if x[1]: useKeys(x[0]) for edit in self.filesToChange: newTime = os.path.getmtime(edit.filename) if newTime > edit.timeChanged: edit.timeChanged = newTime edit.makeChanges() except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None
def run_modal(self, modal_widget): if self.editor is None: self.editor = self.mcedit.editor self.selectTool = self.editor.toolbar.tools[0] old_captured_widget = None if self.captured_widget: old_captured_widget = self.captured_widget self.capture_mouse(None) global last_mouse_event, last_mouse_event_handler global top_widget, clicked_widget is_modal = modal_widget is not None modal_widget = modal_widget or self #from OpenGL import GL try: old_top_widget = top_widget top_widget = modal_widget was_modal = modal_widget.is_modal modal_widget.is_modal = True modal_widget.modal_result = None if not modal_widget.focus_switch: modal_widget.tab_to_first() if clicked_widget: clicked_widget = modal_widget num_clicks = 0 last_click_time = start_time last_click_button = False self.bonus_draw_time = False while modal_widget.modal_result is None: try: if not self.mcedit.version_checked: if not self.mcedit.version_lock.locked(): self.mcedit.version_checked = True self.mcedit.check_for_version() self.hover_widget = self.find_widget( pygame.mouse.get_pos()) if not self.bonus_draw_time: self.bonus_draw_time = True if self.is_gl: self.gl_clear() self.gl_draw_all(self, (0, 0)) GL.glFlush() else: self.draw_all(self.surface) pygame.display.flip() self.frames += 1 events = pygame.event.get() if not events: self.call_idle_handlers() for event in events: type = event.type if type == QUIT: self.quit() elif type == MOUSEBUTTONDOWN: self.bonus_draw_time = False t = datetime.now() if t - last_click_time <= double_click_time and event.button == last_click_button: num_clicks += 1 else: num_clicks = 1 last_click_button = event.button last_click_time = t event.dict['num_clicks'] = num_clicks add_modifiers(event) mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget clicked_widget = mouse_widget last_mouse_event_handler = mouse_widget last_mouse_event = event mouse_widget.notify_attention_loss() mouse_widget.handle_mouse('mouse_down', event) elif type == MOUSEMOTION: self.bonus_draw_time = False add_modifiers(event) modal_widget.dispatch_key('mouse_delta', event) last_mouse_event = event mouse_widget = self.update_tooltip(event.pos) if clicked_widget: last_mouse_event_handler = clicked_widget clicked_widget.handle_mouse( 'mouse_drag', event) else: if not mouse_widget.is_inside(modal_widget): mouse_widget = modal_widget last_mouse_event_handler = mouse_widget mouse_widget.handle_mouse('mouse_move', event) elif type == MOUSEBUTTONUP: add_modifiers(event) self.bonus_draw_time = False mouse_widget = self.find_widget(event.pos) if self.captured_widget: mouse_widget = self.captured_widget if clicked_widget: last_mouse_event_handler = clicked_widget event.dict['clicked_widget'] = clicked_widget else: last_mouse_event_handler = mouse_widget event.dict['clicked_widget'] = None last_mouse_event = event clicked_widget = None last_mouse_event_handler.handle_mouse( 'mouse_up', event) elif type == KEYDOWN: key_down = event.key set_modifier(key_down, True) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.takeAScreenshot.get(): self.take_screenshot() self.send_key(modal_widget, 'key_down', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == KEYUP: key_up = event.key set_modifier(key_up, False) add_modifiers(event) self.bonus_draw_time = False keyname = self.getKey(event) if keyname == config.keys.showBlockInfo.get( ) and self.editor.toolbar.tools[0].infoKey == 1: self.editor.toolbar.tools[0].infoKey = 0 self.editor.mainViewport.showCommands() if self.nudgeDirection is not None: keyname = self.getKey(movement=True, keyname=key.name(key_up)) for i, move_key in enumerate( self.editor.movements): if keyname == move_key and i == self.nudgeDirection: self.nudgeDirection = None self.testTime = None self.testTimeBack = 0.4 self.send_key(modal_widget, 'key_up', event) if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict['local'] = last_mouse_event.local last_mouse_event_handler.setup_cursor(event) elif type == MUSIC_END_EVENT: self.music_end() elif type == USEREVENT: make_scheduled_calls() if not is_modal: if self.redraw_every_frame: self.bonus_draw_time = False else: self.bonus_draw_time = True if last_mouse_event_handler: event.dict['pos'] = last_mouse_event.pos event.dict[ 'local'] = last_mouse_event.local add_modifiers(event) last_mouse_event_handler.setup_cursor( event) self.begin_frame() elif type == VIDEORESIZE: self.bonus_draw_time = False self.size = (event.w, event.h) elif type == VIDEOEXPOSE: if self.mcedit.displayContext.win and self.mcedit.displayContext.win.get_state( ) == 1: x, y = config.settings.windowX.get( ), config.settings.windowY.get() pos = self.mcedit.displayContext.win.get_position( ) if pos[0] != x: config.settings.windowX.set(pos[0]) if pos[1] != y: config.settings.windowY.set(pos[1]) elif type == ACTIVEEVENT: add_modifiers(event) self.dispatch_key('activeevent', event) if not self.sessionStolen: try: if self.editor.level is not None and hasattr( self.editor.level, "checkSessionLock"): self.editor.level.checkSessionLock() except Exception as e: log.warn(u"Error reading chunk (?): %s", e) if not config.session.override.get(): self.sessionStolen = True else: self.editor.level.acquireSessionLock() if self.editor.level is not None: self.editor.cameraInputs = [0., 0., 0., 0., 0., 0.] self.editor.cameraPanKeys = [0., 0., 0., 0.] def useKeys(i): keyName = self.getKey(movement=True, keyname=key.name(i)) if keyName == self.editor.sprintKey: self.sprint = True if allKeys[K_LCTRL] or allKeys[K_RCTRL] or allKeys[ K_RMETA] or allKeys[K_LMETA]: return if keyName in self.editor.movements: self.changeMovementKeys( self.editor.movements.index(keyName), keyName) if keyName in self.editor.cameraPan: self.changeCameraKeys( self.editor.cameraPan.index(keyName)) allKeys = key.get_pressed() for x in enumerate(allKeys): if x[1]: useKeys(x[0]) for edit in self.filesToChange: newTime = os.path.getmtime(edit.filename) if newTime > edit.timeChanged: edit.timeChanged = newTime edit.makeChanges() except Cancel: pass finally: modal_widget.is_modal = was_modal top_widget = old_top_widget if old_captured_widget: self.capture_mouse(old_captured_widget) clicked_widget = None
def on_key_press(self,key_code): if key_code == pygame.K_ESCAPE: self.shutdown_gate() elif not self.gate_active: self.input_symbol(key.name(key_code))
def check_events(self): """Input checking.""" cursor_keys = ("move_up", "move_down", "move_left", "move_right") screen_keys = ("quit", "new_game") for e in event.get(): k = "" if e.type == JOYAXISMOTION: if e.axis == 1: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "up" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "down" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action if e.axis == 0: if -1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "left" if 1 == round(e.value): _type = "keydown" self._last_joystick_action = k = "right" if 0 == round(e.value): _type = "keyup" k = self._last_joystick_action elif e.type in (KEYDOWN, KEYUP): k = key.name(e.key) if e.type == KEYDOWN: _type = "keydown" elif e.type == KEYUP: _type = "keyup" if k in State.controls: if self._last_joystick_action: sprite = State.joystick if _type == "keyup": self._last_joystick_action = None else: sprite = State.cursor control = getattr(actions, State.controls[k]) if _type == "keydown": State.pressed.append(control) ctrl = State.controls[k] if ctrl in cursor_keys: control (sprite) else: control(State.screen) if _type == "keyup": if control in State.pressed: del State.pressed[State.pressed.index(control)] actions.move_stop(sprite) if State.pressed: State.pressed[-1](sprite) def update(self): """Called whenever the game clock determines that game mechanics are ready to be updated.""" self.check_events() def draw(self): """Called whenever the game clock determines that a frame is ready to be drawn.""" State.screen.draw() def run(self, screen): """Main game loop.""" State.running = True State.restore(screen) while State.running: State.clock.tick() if State.clock.update_ready(): self.update() if State.clock.frame_ready(): self.draw()
def key_down(self, evt): if key.name(evt.key) == 'escape': self.dismiss() else: self.editor.key_down(evt)
def _get_key(event): return key.name(event.key)