def eventually_fix_modifier_keys(): """update the modifier keys""" for vkey, kmod_mask in _modifiers: win = GetAsyncKeyState(vkey) sdl = get_mods() & kmod_mask if (win and not sdl) or (not win and sdl): set_mods(get_mods() ^ kmod_mask)
def process_events(self): """Handle any events that may have accumulated in pygame's event queue""" for event in pygame.event.get(): # process mouse events if event.type == MOUSEBUTTONDOWN: singleton_grid.mouse_click(event.pos) singleton_interface.mouse_press(event.pos) # process key events elif event.type == KEYDOWN: if event.key == K_F4 and (get_mods() & KMOD_ALT): sys.exit(0) elif event.key == K_ESCAPE: singleton_interface.set_mode(interface.NORMAL) elif event.key == K_2 and (get_mods() & KMOD_SHIFT): try: code = get_input("Enter some code to execute.") exec(code) except Exception as e: show_message(str(e)) # process exit signals elif event.type == QUIT: pygame.quit() sys.exit(0)
def increment(self): fastIncrementModifier = config.keys.fastIncrementModifier.get() if (fastIncrementModifier == "Shift" and key.get_mods() & KMOD_SHIFT) or (fastIncrementModifier == "Ctrl" and (key.get_mods() & KMOD_CTRL) or (key.get_mods() & KMOD_META)) or ( fastIncrementModifier == "Alt" and key.get_mods() & KMOD_ALT): return self._shift_increment return self._increment
def loop(self): ''' Basic loop tests pygame key events and reacts accordingly ''' done = False while not done: for event in self.display.loop(): if event.type == QUIT: done = True if event.type == KEYDOWN: if self.playing: if event.key == K_SPACE: self.__init__(self.layout_file, False) done = True if event.key == K_UP: self.move() if event.key == K_LEFT: self.rotate(1) if event.key == K_RIGHT: self.rotate(-1) if event.key == K_c and (get_mods() & KMOD_CTRL): done = True elif event.key == K_SPACE: self.display.clear_message() self.playing = True self.collision_detect()
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 get_modifier_keys_status(): """display-friendly status of the modifier keys""" s = "" for vkey, kmod_mask in _modifiers: win = GetAsyncKeyState(vkey) sdl = get_mods() & kmod_mask s += "*" if sdl else "." s += "*" if win else "." s += " " return s
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 on_mousebuttondown(self, button): mods = key.get_mods() ctrl = mods & KMOD_CTRL or mods & KMOD_LCTRL shift = mods & K_LSHIFT or mods & K_RSHIFT if button == 1 and self.is_selected: self.parent.deselegir_todo() self.ser_elegido() elif button == 1 and not self.is_selected: if shift: self.ser_elegido() self.parent.select_many(self) elif not ctrl: self.parent.deselegir_todo() self.ser_elegido() else: self.parent.on_mousebuttondown(button)
def register_key_down(self, key, fn, *args, **kwargs): """register_key_down(key, fn, *args, **kwargs) Register a function to execute when a given key is pressed. If the key is being pressed when this is registered, the function will be executed immediately unless the kwarg _do_immediate is set to False. key: can be either a keys[] constant (or index) from pig.keyboard or a tuple in the form (keymods[] constant/index, keys[] constant/index) fn: the function to call when the keypress occurs *args, **kwargs: arguments to fn """ # if key is already down, perform function if kwargs.pop('_do_immediate', True): try: if type(key) is tuple: if type(key[0]) is str: keymod = keymods[key[0]] else: keymod = key[0] if type(key[1]) is str: thekey = keys[key[1]] else: thekey = key[1] if type(key) is str: thekey = keys[key] keymod = 0 pressed = get_pressed()[thekey] if pressed: mods = get_mods() & ~4096 if keymod is 0: if mods: pressed = False else: if not (keymod & mods): pressed = False except: pass else: if pressed: fn(*args,**kwargs) return self._register_key( self._key_down_dict, key, fn, *args, **kwargs)
def run(self) -> None: """ Principal function, that makes the client run """ running = True self.mousex = 0 # used to store x coordinate of mouse event self.mousey = 0 # used to store y coordinate of mouse event selected = False unselected = False Selection = False self.SelectionScreen(Selection=Selection) try: # Initialize connection to server self.conn.sendto(("NEW" + str(self.game.PlayerSelected)).encode(), (self.addr, self.serverport)) # The first value represent the index of the pile in the list [PileUPAP,PileDownAP,PileUPNAP,PileDownNAP] # The second value represent the selected player. # (1,2) means that I selected the PileDownAP pile, and that I'm player 2 self.mapping_play_card = { (0, 1): 'P1_UP', (1, 1): 'P1_DOWN', (2, 1): 'P2_UP', (3, 1): 'P2_DOWN', (0, 2): 'P2_UP', (1, 2): 'P2_DOWN', (2, 2): 'P1_UP', (3, 2): 'P1_DOWN' } # setup of the piles NotSU1 = True NotSU2 = True NotSU3 = True self.SetupClientServer(NotSU1, NotSU2, NotSU3) # the game # Initialisation CardIndex = 0 StoredIndex = -1 while running: # select on specified file descriptors readable, _, _ = (select.select(self.read_list, self.write_list, [], 0)) for f in readable: if f is self.conn: message, _ = f.recvfrom(65536) message = message.decode() if len(message) >= 3: command = message[0:3] message = message[3:] self.RunCommand(command, message, CardIndex) # re-initialisation of dynamic variables mouseClicked = False unselected = False self.game.DISPLAYSURF.blit(self.game.Images["BGsurface"], (0, 0)) self.game.DisplayActivePlayer() FrontEndHand, Piles, Decks = self.game.DrawBoard() for event in pygame.event.get(): # event handling loop mod = key.get_mods() if event.type == pygame.VIDEORESIZE: # resize self.game.DISPLAYSURF = pygame.display.set_mode( (event.w, event.h), pygame.RESIZABLE) self.game.DefineSizes() self.game.DefineImages() if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() elif event.type == MOUSEMOTION: self.mousex, self.mousey = event.pos for index, cardFrontHand in enumerate(FrontEndHand): cardZone = cardFrontHand[0] if event.type == MOUSEBUTTONDOWN and event.button == 1 and cardZone.collidepoint( self.mousex, self.mousey): self.mousex, self.mousey = event.pos mouseClicked = True selected = True CardIndex = index if event.type == MOUSEBUTTONUP and event.button == 1 and selected: selected = False unselected = True self.mousex, self.mousey = event.pos elif event.type == MOUSEBUTTONDOWN and event.button == 1: self.mousex, self.mousey = event.pos mouseClicked = True elif event.type == KEYDOWN and mod and KMOD_CTRL: # event.type == KEYDOWN and event.unicode == 'a': if event.type == KEYDOWN and event.key == K_z: # we want the azerty for z: event.unicode == 'a' a in if self.game.PlayedThisTurn[ 'P' + str(self.game.PlayerSelected)] != []: self.conn.sendto(("UND").encode(), (self.addr, self.serverport)) # Highlight the card we're on for cardFrontHand in FrontEndHand: cardZone = cardFrontHand[0] if cardZone.collidepoint(self.mousex, self.mousey): LeftTopx, LeftTopy = cardFrontHand[1] pygame.draw.rect( self.game.DISPLAYSURF, self.game.HIGHLIGHTCOLOR, (LeftTopx, LeftTopy, self.game.WIDTHCARD, self.game.HEIGHTCARD), 4) # TODO put buttons here ? boxRectEOT = self.game.DISPLAYSURF.blit( self.game.Images["EndOfTurn"], (int(0.8 * self.game.WINDOWWIDTH), int(0.45 * self.game.WINDOWHEIGHT))) boxRectQUIT = self.game.DISPLAYSURF.blit( self.game.Images["Quit"], (int(0.8 * self.game.WINDOWWIDTH), 0)) # Shows the "Won or lost" indicator in the upper left corner of the screen if self.game.GameOver['P' + str(self.game.PlayerSelected)]: self.game.DISPLAYSURF.blit( self.game.Images["YouLost" + self.game.color[ 'P' + str(self.game.PlayerSelected)]], (0, 0)) # shows the number of cards of the players for index, deck in enumerate(Decks): # index == 0 : SelectedPlayer deck, index == 1 : Non SelectedPlayer deck if deck.collidepoint(self.mousex, self.mousey): LeftTopx = int( (self.game.WINDOWWIDTH + (7.8 * index - 4.4) * self.game.WIDTHCARD) / 2) LeftTopy = int( (-2 * index + 4.5) * self.game.HEIGHTCARD) label = self.game.myfont.render( str(len(self.game.Decks['P' + str(index + 1)])), 1, self.game.ColorsCodes[self.game.color['P' + str(index + 1)]]) self.game.DISPLAYSURF.blit(label, (LeftTopx, LeftTopy)) # we move the image selected if selected: self.game.MoveACard(self.mousex, self.mousey, CardIndex) # we play the card on the pile or we sort the hand if unselected: play_tmp = False if self.game.PlayerSelected == self.game.ActivePlayer: for index, pile in enumerate(Piles): if pile.collidepoint(self.mousex, self.mousey): CardToPlay = self.game.Moving[0] message_to_encode = 'PLC' + self.mapping_play_card[ (index, self.game.PlayerSelected)] + ';' message_to_encode += self.Encode([ CardToPlay ]) + ';' + str(self.game.PlayerSelected) self.conn.sendto(message_to_encode.encode(), (self.addr, self.serverport)) play_tmp = True for index, cardFrontHand in enumerate(FrontEndHand): cardZone = cardFrontHand[0] if cardZone.collidepoint(self.mousex, self.mousey) and not play_tmp: message_to_encode = 'SRT' + self.Encode( self.game.Moving) + ';' + str( index) + ';' + str( self.game.PlayerSelected) self.conn.sendto(message_to_encode.encode(), (self.addr, self.serverport)) if self.game.Moving != [] and not play_tmp: self.game.HandsFrontEnd[ 'P' + str(self.game.PlayerSelected)].insert( CardIndex, self.game.Moving[0]) self.game.Moving = [] # into a pile if StoredIndex > -1: self.ShowPilesScreen(StoredIndex) StoredIndex = -1 # Pile, EOT or concede block if mouseClicked: for index, pile in enumerate(Piles): if pile.collidepoint(self.mousex, self.mousey): StoredIndex = index if boxRectQUIT.collidepoint(self.mousex, self.mousey): #self.game.Concede() #print('concede') break elif boxRectEOT.collidepoint(self.mousex, self.mousey): if self.game.HasTheRightToEndTurn() == 1: self.conn.sendto("EOT".encode(), (self.addr, self.serverport)) elif self.game.ActivePlayer == self.game.PlayerSelected and self.game.HasTheRightToEndTurn( ) == 0: # TODO if you don't have the right to end the turn the popup must be cleaner and not distorded GraySurf = pygame.Surface( (self.game.WINDOWWIDTH, self.game.WINDOWHEIGHT), pygame.SRCALPHA) # per-pixel alpha GraySurf.fill((150, 150, 150, 150)) NotClickedOutEOTScreen = True x0 = int(0.1 * self.game.WINDOWWIDTH) y0 = int(self.game.WINDOWHEIGHT / 4) self.game.DISPLAYSURF.blit(GraySurf, (0, 0)) self.game.DISPLAYSURF.blit( self.game.Images["NoRightEOT"], (x0, y0)) while NotClickedOutEOTScreen: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: NotClickedOutEOTScreen = False pygame.display.update() self.game.clock.tick(self.game.FPS) pygame.display.update() self.game.clock.tick(self.game.FPS) # One player has lost the game if self.game.GameOver['P1']: # TODO improve the handle of the win in the backend and therfore in the front end if self.game.PlayerSelected == 1: # display you lost GraySurf = pygame.Surface( (self.game.WINDOWWIDTH, self.game.WINDOWHEIGHT), pygame.SRCALPHA) # per-pixel alpha GraySurf.fill((150, 150, 150, 150)) NotClickedOutYouLostGoldScreen = True x0 = int( (self.game.WINDOWWIDTH - 0.1 * self.game.WINDOWWIDTH) / 2) y0 = int((self.game.WINDOWHEIGHT - 0.06 * self.game.WINDOWHEIGHT) / 2) self.game.DISPLAYSURF.blit(GraySurf, (0, 0)) self.game.DISPLAYSURF.blit(self.game.Images["YouLostGold"], (x0, y0)) while NotClickedOutYouLostGoldScreen: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: NotClickedOutYouLostGoldScreen = False pygame.display.update() self.game.clock.tick(self.game.FPS) if self.game.PlayerSelected == 2: # display you won GraySurf = pygame.Surface( (self.game.WINDOWWIDTH, self.game.WINDOWHEIGHT), pygame.SRCALPHA) # per-pixel alpha GraySurf.fill((150, 150, 150, 150)) NotClickedOutYouWonSilverScreen = True x0 = int( (self.game.WINDOWWIDTH - 0.1 * self.game.WINDOWWIDTH) / 2) y0 = int((self.game.WINDOWHEIGHT - 0.06 * self.game.WINDOWHEIGHT) / 2) self.game.DISPLAYSURF.blit(GraySurf, (0, 0)) self.game.DISPLAYSURF.blit( self.game.Images["YouWonSilver"], (x0, y0)) while NotClickedOutYouWonSilverScreen: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: NotClickedOutYouWonSilverScreen = False pygame.display.update() self.game.clock.tick(self.game.FPS) elif self.game.GameOver['P2']: if self.game.PlayerSelected == 1: # display you won GraySurf = pygame.Surface( (self.game.WINDOWWIDTH, self.game.WINDOWHEIGHT), pygame.SRCALPHA) # per-pixel alpha GraySurf.fill((150, 150, 150, 150)) NotClickedOutYouWonGoldScreen = True x0 = int( (self.game.WINDOWWIDTH - 0.1 * self.game.WINDOWWIDTH) / 2) y0 = int((self.game.WINDOWHEIGHT - 0.06 * self.game.WINDOWHEIGHT) / 2) self.game.DISPLAYSURF.blit(GraySurf, (0, 0)) self.game.DISPLAYSURF.blit(self.game.Images["YouWonGold"], (x0, y0)) while NotClickedOutYouWonGoldScreen: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: NotClickedOutYouWonGoldScreen = False pygame.display.update() self.game.clock.tick(self.game.FPS) if self.game.PlayerSelected == 2: # display you lost GraySurf = pygame.Surface( (self.game.WINDOWWIDTH, self.game.WINDOWHEIGHT), pygame.SRCALPHA) # per-pixel alpha GraySurf.fill((150, 150, 150, 150)) NotClickedOutYouLostSilverScreen = True x0 = int( (self.game.WINDOWWIDTH - 0.1 * self.game.WINDOWWIDTH) / 2) y0 = int((self.game.WINDOWHEIGHT - 0.06 * self.game.WINDOWHEIGHT) / 2) self.game.DISPLAYSURF.blit(GraySurf, (0, 0)) self.game.DISPLAYSURF.blit( self.game.Images["YouLostSilver"], (x0, y0)) while NotClickedOutYouLostSilverScreen: for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN and event.button == 1: NotClickedOutYouLostSilverScreen = False pygame.display.update() self.game.clock.tick(self.game.FPS) finally: print("Quit") self.conn.sendto("QUI".encode(), (self.addr, self.serverport))
def handle_events(self): """events""" for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() write_timings(self.timings, self.timeOffset) exit() # sys.exit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if not self.isStart: self.start() elif self.isPause: self.resume() else: self.pause() if event.key == pygame.K_r: self.stop() if key.get_mods() & pygame.KMOD_CTRL: # & for mask working if self.skip >= len(self.timings): # current return if event.key == pygame.K_RIGHT: self.timings[self.skip] -= 50 elif event.key == pygame.K_LEFT: self.timings[self.skip] += 50 elif event.key == pygame.K_DOWN: self.start_dt -= datetime.timedelta(milliseconds=50) elif event.key == pygame.K_UP: self.start_dt += datetime.timedelta(milliseconds=50) elif key.get_mods() & pygame.KMOD_SHIFT: if event.key == pygame.K_RIGHT: self.start_dt -= datetime.timedelta(milliseconds=50) self.timeOffset -= 50 elif event.key == pygame.K_LEFT: self.start_dt += datetime.timedelta(milliseconds=50) self.timeOffset += 50 else: # prev if self.skip <= 0: return if event.key == pygame.K_RIGHT: self.timings[self.skip-1] -= 50 elif event.key == pygame.K_LEFT: self.timings[self.skip-1] += 50 elif event.key == pygame.K_y: self.timings.pop(self.skip) if not key.get_mods() & pygame.KMOD_CTRL: keys = key.get_pressed() if keys[pygame.K_DOWN]: self.start_dt -= datetime.timedelta(milliseconds=3) elif keys[pygame.K_UP]: self.start_dt += datetime.timedelta(milliseconds=2) for i in range(self.skip-1, -1, -1): # -1 not incl temp = self.timings[i] - \ self.tempTime.total_seconds()*1000.0 if temp > self.hidePos and temp < self.showTime: self.skip -= 1 else: break
def key_down(self, event): self.get_root().notMove = True if not event.cmd or (event.alt and event.unicode): k = event.key if k == K_LEFT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(-1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_end is None and self.insertion_point != 0: self.selection_start = self.insertion_point self.selection_end = self.insertion_point - 1 self.insertion_point = None elif self.selection_end is not None and self.selection_end != 0: self.selection_end -= 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_RIGHT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_start is None and self.insertion_point < len( self.text): self.selection_start = self.insertion_point self.selection_end = self.insertion_point + 1 self.insertion_point = None elif self.selection_start is not None and self.selection_end < len( self.text): self.selection_end += 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_TAB: self.attention_lost() self.tab_to_next() return if k == K_DOWN: self.move_insertion_line(1) return if k == K_UP: self.move_insertion_line(-1) return if k == K_HOME: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = 0 self.sync_line_and_step() elif self.insertion_point != 0: if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = 0 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return if k == K_END: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = len(self.text) self.sync_line_and_step() elif self.insertion_point != len(self.text): if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = len(self.text) if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return try: c = event.unicode except ValueError: print 'value error' c = "" if self.insert_char(c, k) != 'pass': return if event.cmd and event.unicode: if event.key == K_c or event.key == K_x: try: #pygame.scrap.put(SCRAP_TEXT, self.text) text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = self.text elif i is None and self.selection_start is not None and self.selection_end is not None: text = text[( min(self.selection_start, self.selection_end) ):max(self.selection_start, self.selection_end)] else: return pyperclip.copy(text) except: print "scrap not available" finally: if event.key == K_x and i is None: self.insert_char(event.unicode, K_BACKSPACE) elif event.key == K_v: try: #t = pygame.scrap.get(SCRAP_TEXT).replace('\0', '') t = pyperclip.paste().replace("\n", " ") if t is not None: if self.insertion_point is not None: self.text = self.text[:self. insertion_point] + t + self.text[ self.insertion_point:] self.insertion_point += len(t) elif self.insertion_point is None and ( self.selection_start is None or self.selection_end is None): self.text = t self.insertion_point = len(t) elif self.insertion_point is None and self.selection_start is not None and self.selection_end is not None: self.selection_point = min( self.selection_start, self.selection_end) + len(t) self.text = self.text[:( min(self.selection_start, self.selection_end) )] + t + self.text[(max(self.selection_start, self. selection_end)):] self.selection_start = None self.selection_end = None else: return self.change_text(self.text) self.sync_line_and_step() except: print "scrap not available" #print repr(t) else: self.attention_lost()
def main(): # initialize the pygame module pygame.init() # load and set the logo logo = pygame.image.load(sys.path[0] + "/logo32x32.png") pygame.display.set_icon(logo) sysfont = font.SysFont(None, 24) screen = pygame.display.set_mode((700,700), constants.RESIZABLE) interactables = [] filename = sys.argv[1] if len(sys.argv) > 1 else 'smlogicsim.json' try: jsonContent = "" with open(filename, 'r') as file: jsonContent = file.read() interactables = deserialize(jsonContent) except IOError: None pygame.display.set_caption("Scrap Mechanic Logic Gate Simulator - " + filename) # define a variable to control the main loop closing = False running = False selected = None isMoving = False isLinking = False posAtStart = (0,0) tick = 0 lastTickTime = time.time() # main loop while not closing: # event handling, gets all event from the event queue for event in pygame.event.get(): if event.type == constants.MOUSEBUTTONDOWN: if event.button == 1: selectedNow = findItem(interactables, event.pos) if selected is not None: selected.selected = False if selectedNow is None: selected = None else: selectedNow.selected = True selected = selectedNow posAtStart = event.pos elif event.type == constants.MOUSEBUTTONUP: if isLinking: target = findItem(interactables, event.pos) if target is not None and target is not selected and target.maxInputCount != 0: if selected in target.inputs: # the connection is already there - undo it target.inputs.remove(selected) else: # If the connection already goes the other way, reverse it. if target in selected.inputs: selected.inputs.remove(target) selected.inputsChanged() if target.maxInputCount == 1: target.inputs.clear() target.inputs.append(selected) target.inputsChanged() target.paint() selected.paint() isLinking = False isMoving = False elif event.type == constants.MOUSEMOTION: if event.buttons[0] == 1: # the >5 thing is to prevent random jiggles while clicking from instigating moves. if selected is not None \ and not isMoving \ and not isLinking \ and (abs(event.pos[0] - posAtStart[0]) > 5 or abs(event.pos[1] - posAtStart[1]) > 5): keyboardModifiers = key.get_mods() isMoving = keyboardModifiers in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT) isLinking = keyboardModifiers == 0 if isMoving: selected.move(event.rel) elif event.type == constants.KEYDOWN: if event.key == constants.K_DELETE and selected is not None: interactables.remove(selected) for i in interactables: if selected in i.inputs: i.inputs.remove(selected) i.inputsChanged() selected = None elif event.key == constants.K_LEFT and selected is not None: selected.swapGate(-1) elif event.key == constants.K_RIGHT and selected is not None: selected.swapGate(1) elif event.key == constants.K_UP and selected is not None: selected.alternate() elif event.key == constants.K_DOWN and selected is not None: selected.alternate() elif event.key == constants.K_F10 and not running: singleStep(interactables) tick += 1 elif event.key == constants.K_F4: tick = 0 running = False if event.mod in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT): putOnLift(interactables) else: reload(interactables) elif event.key == constants.K_F5: running = True elif event.key == constants.K_F6: running = False elif event.key == constants.K_s: with open(filename, 'w') as file: file.write(serialize(interactables)) elif event.key == constants.K_p: if event.mod in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT): for i in interactables: i.paint() elif selected is not None: selected.paint() elif event.key in Interactable.hotkeyToTypeMap.keys(): if selected is not None: selected.selected = False selected = Interactable.hotkeyToTypeMap[event.key](mouse.get_pos()) selected.selected = True interactables.append(selected) elif event.type == constants.QUIT: closing = True if running: timenow = time.time() if (timenow - lastTickTime > .25): singleStep(interactables) tick += 1 lastTickTime = timenow screen.fill(BLACK) tickImage = sysfont.render(str(tick), True, RED) tickRect = tickImage.get_rect() screenRect = screen.get_rect() tickRect.move_ip(screenRect.width - 10 - tickRect.width, 10) screen.blit(tickImage, tickRect) for box in interactables: for input in box.inputs: drawLineWithArrows(screen, input.rect.center, box.rect.center, LIGHTBLUE if input.prevState else BLUE) for box in interactables: box.draw(screen) if isLinking: mousePos = mouse.get_pos() target = findItem(interactables, mousePos) if target is None: draw.line(screen, GRAY, selected.rect.center, mouse.get_pos(), 1) else: draw.line(screen, GREEN, selected.rect.center, target.rect.center, 1) display.flip() # display.update() # Always just save on exit savedState = serialize(interactables) with open(filename, 'w') as file: file.write(savedState)
def update(cls): events = event.get([ KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION, QUIT ]) event.clear() # esto es para que se pueda reemplazar un locutor sin tener que reseleccionarlo. cls.selected.add([ i for i in cls.widgets.widgets() if i.is_selected and (i not in cls.selected) ]) for e in events: mods = key.get_mods() ctrl = mods & KMOD_CTRL shift = mods & KMOD_SHIFT if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): salir() elif e.type == KEYDOWN: widgets = cls.selected.widgets() if System.type_mode: if e.key == K_F3: System.toggle_typemode('MainTB') else: EventHandler.trigger('Key', cls.name, { 'key': e.key, 'mod': e.mod }) elif e.key == K_c: if len(widgets) == 2 and all( [o.numerable for o in widgets]): widgets.sort( key=lambda o: o.idx) # lower idx's go first if not shift: widgets[0].connect(widgets[1]) else: widgets[0].disconnect(widgets[1]) elif e.key == K_a and len(widgets) == 2: base, other = widgets EventHandler.trigger('AddMidPoint', 'System', { 'base': base, 'other': other }) elif e.key == K_RETURN: EventHandler.trigger('CreateDialog', cls.name, {'nodes': cls.numerable}) elif e.key == K_F3: if any([o.order == 'b' for o in widgets]): System.toggle_typemode('MainTB') else: for widget in widgets: widget.on_keydown(e) elif e.key == K_s: x, y = mouse.get_pos() color, text = None, None if any([o.order == 'a' for o in widgets]): color = [i for i in widgets if i.order == 'a'][0].color text = [i for i in widgets if i.order == 'a'][0].text if System.area_nodos.collidepoint(x, y) and text is not None: EventHandler.trigger('AddNode', cls.name, { 'text': text, 'pos': [x, y], 'color': color }) elif e.key == K_d and any([o.order == 'a' for o in widgets]): widgets.sort(key=lambda o: o.order) color_namer = widgets.pop(0) for other in widgets: other.colorize(color_namer) elif len(cls.selected): for widget in cls.selected.widgets(): widget.on_keydown(e) elif e.type == KEYUP: if len(cls.selected): for widget in cls.selected.widgets(): widget.on_keyup(e) elif e.type == MOUSEBUTTONDOWN: # pos, button widgets = [ w for w in cls.widgets.widgets() if w.selectable and w.rect.collidepoint(e.pos) ] if not len( widgets ) and e.button == 1 and cls.active_area.collidepoint(e.pos): if not shift and not System.type_mode: cls.selected.empty() if not ctrl: EventHandler.trigger('AddSelection', cls.name, { "pos": e.pos, 'value': True }) elif len(widgets) and not len(cls.selected): cls.selected.sumar([w for w in widgets if w.selectable]) elif not cls.selected.has(widgets) and e.button == 1 and len( widgets): order_c = [i for i in widgets if i.order == 'c'] if not ctrl and not System.type_mode and not len(order_c): cls.selected.empty() cls.selected.sumar(widgets) if len(widgets): for widget in cls.selected.widgets(): if widget is not cls.selection: widget.on_mousedown(e) elif e.button != 1: widgets = [w for w in cls.widgets.widgets() if w.numerable] if ctrl and not shift: dx, dy = 1, 0 elif shift and not ctrl: dx, dy = 0, 5 elif ctrl and shift: dx, dy = 5, 0 else: dx, dy = 0, 1 for widget in widgets: if e.button == 4: dx *= -1 dy *= -1 elif e.button == 5: dx *= 1 dy *= 1 widget.rect.move_ip(dx, dy) elif e.type == MOUSEBUTTONUP: # pos, button if cls.on_selection and e.button == 1: cls.selection.on_mouseup(e) selected = [ i for i in cls.widgets if cls.selection.rect.contains(i.rect) ] cls.selected.sumar(selected) elif e.type == MOUSEMOTION: # pos, rel, buttons if e.buttons[0] and len( cls.selected) and not shift and not System.type_mode: for widget in [ i for i in cls.selected.widgets() if i.draggable is True ]: widget.on_mousemotion(e) elif cls.on_selection and e.buttons[0]: cls.selection.on_mousemotion(e) elif ctrl and e.buttons[0]: widgets = [ w for w in cls.widgets.widgets() if w.selectable and w.draggable ] for widget in widgets: widget.on_mousemotion(e) cls.widgets.update()
def increment(self): if key.get_mods() & KMOD_SHIFT: return self._shift_increment return self._increment
def _click(self, position): """S._click (...) -> None Deals with mouse clicks. """ # Get the item and toggle the selection. item = self.child.get_item_at_pos(position) mods = key.get_mods() if not item: return if self.selectionmode != SELECTION_MULTIPLE: self._last_direction = None selection = self.get_selected() allowed = self.selectionmode != SELECTION_NONE if mods & KMOD_CTRL: if selection and item in selection: selection.remove(item) self.__deselect(*selection) self.set_cursor(item, not item.selected and allowed) else: self.__deselect(*selection) self.set_cursor(item, allowed) return if item.selected: if mods & KMOD_CTRL: self.set_cursor(item, False) elif mods & KMOD_SHIFT: # The item usually should be somewhere in that selection. # Get its index and crop the selection according to that # index. selection = self.get_selected() if len(selection) > 1: start = self.items.index(selection[0]) end = self.items.index(selection[-1]) index = selection.index(item) if self._last_direction == K_UP: if index > 0: self.__deselect(*selection[0:index]) elif self._last_direction == K_DOWN: if index > 0: self.__deselect(*selection[index:end + 1]) self.set_cursor(item, True) else: self.set_cursor(selection[0], True) else: self._last_direction = None self.__deselect(*self.get_selected()) self.set_cursor(item, True) else: if mods & KMOD_CTRL: self.set_cursor(item, True) elif mods & KMOD_SHIFT: # No click on an existing selection. Expand the current. selection = self.get_selected() start = self.items.index(self.cursor) index = self.items.index(item) if len(selection) != 0: if self._last_direction == K_DOWN: start = self.items.index(selection[0]) end = self.items.index(selection[-1]) if index < start: self._last_direction = K_UP self.__deselect(*selection) self.__select(*self.items[index:start]) elif index > end: self.__select(*self.items[end:index]) elif self._last_direction == K_UP: start = self.items.index(selection[0]) end = self.items.index(selection[-1]) if index > end: self._last_direction = K_DOWN self.__deselect(*selection) self.__select(*self.items[end + 1:index]) elif index < start: self.__select(*self.items[index:start]) else: start = self.items.index(selection[0]) if index > start: self.__select(*self.items[start:index]) self._last_direction = K_DOWN else: self.__select(*self.items[index:start]) self._last_direction = K_UP self.set_cursor(item, True) else: self._last_direction = None self.__deselect(*self.get_selected()) self.set_cursor(item, True)
def _click (self, position): """S._click (...) -> None Deals with mouse clicks. """ # Get the item and toggle the selection. item = self.child.get_item_at_pos (position) mods = key.get_mods () if not item: return if self.selectionmode != SELECTION_MULTIPLE: self._last_direction = None selection = self.get_selected () allowed = self.selectionmode != SELECTION_NONE if mods & KMOD_CTRL: if selection and item in selection: selection.remove (item) self.__deselect (*selection) self.set_cursor (item, not item.selected and allowed) else: self.__deselect (*selection) self.set_cursor (item, allowed) return if item.selected: if mods & KMOD_CTRL: self.set_cursor (item, False) elif mods & KMOD_SHIFT: # The item usually should be somewhere in that selection. # Get its index and crop the selection according to that # index. selection = self.get_selected () if len (selection) > 1: start = self.items.index (selection[0]) end = self.items.index (selection[-1]) index = selection.index (item) if self._last_direction == K_UP: if index > 0: self.__deselect (*selection[0:index]) elif self._last_direction == K_DOWN: if index > 0: self.__deselect (*selection[index:end + 1]) self.set_cursor (item, True) else: self.set_cursor (selection[0], True) else: self._last_direction = None self.__deselect (*self.get_selected ()) self.set_cursor (item, True) else: if mods & KMOD_CTRL: self.set_cursor (item, True) elif mods & KMOD_SHIFT: # No click on an existing selection. Expand the current. selection = self.get_selected () start = self.items.index (self.cursor) index = self.items.index (item) if len (selection) != 0: if self._last_direction == K_DOWN: start = self.items.index (selection[0]) end = self.items.index (selection[-1]) if index < start: self._last_direction = K_UP self.__deselect (*selection) self.__select (*self.items[index:start]) elif index > end: self.__select (*self.items[end:index]) elif self._last_direction == K_UP: start = self.items.index (selection[0]) end = self.items.index (selection[-1]) if index > end: self._last_direction = K_DOWN self.__deselect (*selection) self.__select (*self.items[end + 1:index]) elif index < start: self.__select (*self.items[index:start]) else: start = self.items.index (selection[0]) if index > start: self.__select (*self.items[start:index]) self._last_direction = K_DOWN else: self.__select (*self.items[index:start]) self._last_direction = K_UP self.set_cursor (item, True) else: self._last_direction = None self.__deselect (*self.get_selected ()) self.set_cursor (item, True)
def key_down(self, event): self.get_root().notMove = True if not event.cmd or (event.alt and event.unicode): k = event.key if k == K_LEFT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(-1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_end is None and self.insertion_point != 0: self.selection_start = self.insertion_point self.selection_end = self.insertion_point - 1 self.insertion_point = None elif self.selection_end is not None and self.selection_end != 0: self.selection_end -= 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_RIGHT: if not (key.get_mods() & KMOD_SHIFT): self.move_insertion_point(1) else: if self.selection_end is None and self.selection_start is None and self.insertion_point is None: return if self.selection_start is None and self.insertion_point < len(self.text): self.selection_start = self.insertion_point self.selection_end = self.insertion_point + 1 self.insertion_point = None elif self.selection_start is not None and self.selection_end < len(self.text): self.selection_end += 1 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None return if k == K_TAB: self.attention_lost() self.tab_to_next() return if k == K_DOWN: self.move_insertion_line(1) return if k == K_UP: self.move_insertion_line(-1) return if k == K_HOME: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = 0 self.sync_line_and_step() elif self.insertion_point != 0: if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = 0 if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return if k == K_END: if not (key.get_mods() & KMOD_SHIFT): self.selection_start = None self.selection_end = None self.insertion_point = len(self.text) self.sync_line_and_step() elif self.insertion_point != len(self.text): if self.insertion_point is not None: self.selection_start = self.insertion_point self.insertion_point = None self.selection_end = len(self.text) if self.selection_end == self.selection_start: self.insertion_point = self.selection_end self.selection_end = None self.selection_start = None self.sync_line_and_step() return try: c = event.unicode except ValueError: print 'value error' c = "" if self.insert_char(c, k) != 'pass': return if event.cmd and event.unicode: if event.key == K_c or event.key == K_x: try: #pygame.scrap.put(SCRAP_TEXT, self.text) text, i = self.get_text_and_insertion_point() if i is None and (self.selection_start is None or self.selection_end is None): text = self.text elif i is None and self.selection_start is not None and self.selection_end is not None: text = text[(min(self.selection_start, self.selection_end)):max(self.selection_start, self.selection_end)] else: return pyperclip.copy(text) except: print "scrap not available" finally: if event.key == K_x and i is None: self.insert_char(event.unicode, K_BACKSPACE) elif event.key == K_v: try: #t = pygame.scrap.get(SCRAP_TEXT).replace('\0', '') t = pyperclip.paste().replace("\n", " ") if t is not None: allow = True for char in t: if not self.allow_char(char): allow = False if not allow: return if self.insertion_point is not None: self.text = self.text[:self.insertion_point] + t + self.text[self.insertion_point:] self.insertion_point += len(t) elif self.insertion_point is None and ( self.selection_start is None or self.selection_end is None): self.text = t self.insertion_point = len(t) elif self.insertion_point is None and self.selection_start is not None and self.selection_end is not None: self.selection_point = min(self.selection_start, self.selection_end) + len(t) self.text = self.text[:(min(self.selection_start, self.selection_end))] + t + self.text[( max(self.selection_start, self.selection_end)):] self.selection_start = None self.selection_end = None else: return self.change_text(self.text) self.sync_line_and_step() except: print "scrap not available" #print repr(t) else: self.attention_lost()
def increment(self): fastIncrementModifier = config.keys.fastIncrementModifier.get() if (fastIncrementModifier == "Shift" and key.get_mods() & KMOD_SHIFT) or (fastIncrementModifier == "Ctrl" and (key.get_mods() & KMOD_CTRL) or (key.get_mods() & KMOD_META)) or (fastIncrementModifier == "Alt" and key.get_mods() & KMOD_ALT): return self._shift_increment return self._increment