def update(cls): cls.fps.tick(60) events = event.get([QUIT, KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION]) event.clear() for e in events: if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): quit() exit() elif e.type == MOUSEBUTTONDOWN: widgets = cls.widgets.get_widgets_at(e.pos) for widget in widgets: cls.selected = widget.onmousebuttondown(e.button) elif e.type == MOUSEBUTTONUP: widgets = cls.widgets.get_widgets_at(e.pos) for widget in widgets: widget.onmousebuttonup(e.button) elif e.type == MOUSEMOTION: pass elif e.type == KEYDOWN: pass elif e.type == KEYUP: pass pos = mouse.get_pos() for widget in cls.widgets.widgets(): if widget.rect.collidepoint(pos): widget.onmouseover() cls.widgets.update()
def exchangeInput(self): """Exchange a round of inputs in a network-safe manner. """ inputs = [] for player in self.playerList: inp = self.getPlayerInput(player) debug("Player " + str(player.name) +\ " input: " + inp + "\n") if self.record and inp != NOOP: self.playerInputFileList[int(player.name)].write( \ str(self.totalGameLoops) +\ ',' + inp + '\n') # Check players input if len(inp) != len(UP): print "Bad input from player",player.getHandle() inp = DISCONNECT # Can quit the game from end splash screen if inp == QUITCOMMAND: sys.exit() inputs.append((player.name,inp)) for netplayer in self.playerList: netplayer.sendCommand(player.getBroadcastable()) self.totalGameLoops += 1 # Clear all useless events eventsWeWant = events.get([KEYDOWN, KEYUP, JOYBUTTONDOWN,\ JOYAXISMOTION]) events.clear() for event in eventsWeWant: events.post(event) return inputs
def exchangeInput(self): """Exchange a round of inputs in a network-safe manner. """ inputs = [] for player in self.playerList: inp = self.getPlayerInput(player) debug("Player " + str(player.name) +\ " input: " + inp + "\n") if self.record and inp != NOOP: self.playerInputFileList[int(player.name)].write( \ str(self.totalGameLoops) +\ ',' + inp + '\n') # Check players input if len(inp) != len(UP): print "Bad input from player", player.getHandle() inp = DISCONNECT # Can quit the game from end splash screen if inp == QUITCOMMAND: sys.exit() inputs.append((player.name, inp)) for netplayer in self.playerList: netplayer.sendCommand(player.getBroadcastable()) self.totalGameLoops += 1 # Clear all useless events eventsWeWant = events.get([KEYDOWN, KEYUP, JOYBUTTONDOWN,\ JOYAXISMOTION]) events.clear() for event in eventsWeWant: events.post(event) return inputs
def update(self, field): from pygame.constants import KEYDOWN, MOUSEBUTTONUP, K_EQUALS, K_MINUS, K_ESCAPE from pygame.event import poll, clear field.camera.set_lead(self.mob.leads[self.mob.current_lead]) new_event = poll() if new_event.type == KEYDOWN: if new_event.key == K_EQUALS: self.mob.current_lead += 1 self.mob.current_lead %= len(self.mob.leads) elif new_event.key == K_MINUS: self.mob.current_lead -= 1 self.mob.current_lead %= len(self.mob.leads) elif new_event.key == K_ESCAPE: from bin.Interaction import pause_menu return pause_menu(field.screen, field) elif new_event.type == MOUSEBUTTONUP: if new_event.button == 1: from bin.Logic import pixel_to_hex, coord_get_offset, coord_available position = new_event.pos[0] + field.camera.border_pixel[ 0], new_event.pos[1] + field.camera.border_pixel[1] hexagon = pixel_to_hex(position, field.camera.size, field) coord = coord_get_offset(hexagon, field) if coord_available(hexagon, field) and field.map[coord[0]][coord[1]][1].exploration and \ field.map[coord[0]][coord[1]][1].passability: self.hexagon = hexagon clear() return True
def update(self, field): from pygame.constants import KEYDOWN, MOUSEBUTTONUP, K_EQUALS, K_MINUS, K_ESCAPE from pygame.event import poll, clear field.camera.set_lead(self.mob.leads[self.mob.current_lead]) new_event = poll() if new_event.type == KEYDOWN: if new_event.key == K_EQUALS: self.mob.current_lead += 1 self.mob.current_lead %= len(self.mob.leads) elif new_event.key == K_MINUS: self.mob.current_lead -= 1 self.mob.current_lead %= len(self.mob.leads) elif new_event.key == K_ESCAPE: from bin.Interaction import pause_menu return pause_menu(field.screen, field) elif new_event.type == MOUSEBUTTONUP: if new_event.button == 1: from bin.Logic import pixel_to_hex, coord_get_offset, coord_available position = new_event.pos[0] + field.camera.border_pixel[0], new_event.pos[1] + field.camera.border_pixel[1] hexagon = pixel_to_hex(position, field.camera.size, field) coord = coord_get_offset(hexagon, field) if coord_available(hexagon, field) and field.map[coord[0]][coord[1]][1].exploration and \ field.map[coord[0]][coord[1]][1].passability: self.hexagon = hexagon clear() return True
def test_post__clear(self): """Ensure posted events can be cleared.""" for _ in range(10): fastevent.post(event.Event(pygame.USEREVENT)) event.clear() self.assertListEqual(fastevent.get(), []) self.assertListEqual(event.get(), [])
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 show(self, text): self.box(text) while 1: if self.cb and self.cbargs: self.cb(*self.cbargs) sleep(0.01) events = event.get((KEYDOWN, MOUSEBUTTONDOWN, QUIT)) if not events: event.clear() continue if QUIT in [e.type for e in events]: return e else: sleep(0.1) return
def update(cls): cls.clock.tick(30) events = event.get([KEYDOWN, MOUSEBUTTONDOWN, QUIT]) 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: if cls.active is not None: cls.active.on_keydown(e.key) elif e.type == KEYUP: if cls.active is not None: cls.active.on_keyup(e.key) elif e.type == MOUSEBUTTONDOWN: for wig in cls.contents: wig.active = False widgets = [ i for i in cls.contents.sprites() if i.rect.collidepoint(e.pos) ] for w in widgets: w.on_mousebuttondown(e.button) cls.active = w elif e.type == MOUSEBUTTONUP: pass elif e.tyoe == MOUSEMOTION: pass x, y = mouse.get_pos() for widget in cls.contents.sprites(): if widget.rect.collidepoint((x, y)): widget.on_mouseover() cls.contents.update()
def reset(cls): display.set_icon( image.load(os.path.join(os.getcwd(), 'data', 'favicon.png'))) display.set_caption("WorldBuilding") display.set_mode((ANCHO, ALTO), SCALED) event.clear()
def graph_loop(mass_lower_limit=0.0, mass_upper_limit=0.0, radius_lower_limit=0.0, radius_upper_limit=0.0, is_gas_drwaf=False): m_lo_l = mass_lower_limit m_hi_l = mass_upper_limit r_lo_l = radius_lower_limit r_hi_l = radius_upper_limit fondo = display.set_mode((witdh, height), SCALED) rect = Rect(60, 2, 529, 476) lineas = LayeredUpdates() linea_h = Linea(rect, rect.x, rect.centery, rect.w, 1, lineas) linea_v = Linea(rect, rect.centerx, rect.y, 1, rect.h, lineas) punto = Punto(rect, rect.centerx, rect.centery, lineas) data = {} if any([ mass_lower_limit < 0, mass_upper_limit < 0, radius_lower_limit < 0, radius_upper_limit < 0 ]): raise ValueError() lim_mass_a = int(find_and_interpolate(m_lo_l, mass_keys, exes)) if m_lo_l else 0 lim_mass_b = int(find_and_interpolate(m_hi_l, mass_keys, exes)) if m_hi_l else 0 lim_radius_a = int(find_and_interpolate(r_lo_l, radius_keys, yes)) if r_lo_l else 0 lim_radius_b = int(find_and_interpolate(r_hi_l, radius_keys, yes)) if r_hi_l else 0 move_x, move_y = True, True lockx, locky = False, False mass_value = 0 radius_value = 0 mass_color = negro radius_color = negro mouse.set_pos(rect.center) event.clear() done = False composition_text_comp = None while not done: for e in event.get(): if e.type == QUIT: py_quit() if __name__ == '__main__': sys.exit() elif e.type == MOUSEBUTTONDOWN: if e.button == 1: if (not lockx) or (not locky): if (not lockx) and (not move_x): lockx = True elif (not locky) and (not move_y): locky = True elif not punto.disabled: data['mass'] = round(mass_value, 3) data['radius'] = round(radius_value, 3) data['gravity'] = round( mass_value / (radius_value**2), 3) data['density'] = round( mass_value / (radius_value**3), 3) done = True else: data = {} done = True elif e.button == 3: if lockx: lockx = False move_x = not lockx if locky: locky = False move_y = not locky elif e.type == MOUSEMOTION: px, py = e.pos if move_y: linea_h.move_y(py) punto.move_y(py) if move_x: linea_v.move_x(px) punto.move_x(px) point_x, point_y = punto.rect.center if rect.collidepoint(point_x, point_y) and (move_x or move_y): if mascara.get_at((point_x, point_y)): punto.select() for name in _lineas: if [point_x, point_y] in _lineas[name]: composition_text_comp = name break else: punto.deselect() elif e.type == KEYDOWN: if e.key == K_ESCAPE: py_quit() sys.exit() if e.key == K_LSHIFT: move_x = False elif e.key == K_LCTRL: move_y = False elif e.key == K_SPACE: data['mass'] = round(mass_value, 3) data['radius'] = round(radius_value, 3) data['gravity'] = round(mass_value / (radius_value**2), 3) data['density'] = round(mass_value / (radius_value**3), 3) done = True elif e.type == KEYUP: if e.key == K_LSHIFT: if not lockx: move_x = True elif e.key == K_LCTRL: if not locky: move_y = True px, py = punto.rect.center alto, bajo = 0, 0 if rect.collidepoint((px, py)): for _y in reversed(range(0, py)): if mascara.get_at((px, _y)): alto = _y break for _y in range(py, 476): if mascara.get_at((px, _y)): bajo = _y break a, b = 0, 0 # creo que esto se puede escribir con oneliners. for name in _lineas: if [px, alto] in _lineas[name]: a = name break for name in _lineas: if [px, bajo] in _lineas[name]: b = name break if a and b: c = composiciones silicates = interpolate(py, alto, bajo, c[a]['silicates'], c[b]['silicates']) hydrogen = interpolate(py, alto, bajo, c[a]['hydrogen'], c[b]['hydrogen']) helium = interpolate(py, alto, bajo, c[a]['helium'], c[b]['helium']) iron = interpolate(py, alto, bajo, c[a]['iron'], c[b]['iron']) water_ice = interpolate(py, alto, bajo, c[a]['water ice'], c[b]['water ice']) values = [ i for i in [silicates, hydrogen, helium, iron, water_ice] if i != 0 ] # sólo mostramos los valores mayores a 0% keys, compo = [], [] if silicates: compo.append(str(round(silicates, 2)) + '% silicates') keys.append('silicates') if hydrogen: compo.append(str(round(hydrogen, 2)) + '% hydrogen') keys.append('hydrogen') if helium: compo.append(str(round(helium, 2)) + '% helium') keys.append('helium') if iron: compo.append(str(round(iron, 2)) + '% iron') keys.append('iron') if water_ice: compo.append(str(round(water_ice, 2)) + '% water ice') keys.append('water ice') composition_text_comp = ', '.join(compo) data['composition'] = dict(zip(keys, values)) if hydrogen or helium: data['clase'] = 'Gas Dwarf' data['albedo'] = 30 else: data['clase'] = 'Terrestial Planet' data['albedo'] = 25 else: data = {} mass_value = find_and_interpolate(linea_v.rect.x, exes, mass_keys) radius_value = find_and_interpolate_flipped(linea_h.rect.y, yes, radius_keys) block = Surface(rect.size, SRCALPHA) block_mask = mask.from_surface(block) if any([lim_mass_b, lim_mass_a, lim_radius_a, lim_radius_b]): block_rect = block.get_rect(topleft=rect.topleft) alpha = 150 if lim_mass_a: block.fill([0] * 3 + [alpha], (0, rect.y - 2, lim_mass_a - rect.x, rect.h)) if lim_mass_b: block.fill([0] * 3 + [alpha], (lim_mass_b - rect.x, rect.y - 2, rect.w, rect.h)) if lim_radius_a: block.fill([0] * 3 + [alpha], (0, lim_radius_a, rect.w, rect.h - lim_radius_a)) if lim_radius_b: block.fill([0] * 3 + [alpha], (0, rect.y - 2, rect.w, lim_radius_b)) if is_gas_drwaf: block.blit(gas_drawf, (0, 0)) block_mask = mask.from_surface(block) point_x, point_y = punto.rect.center if block_rect.collidepoint((point_x, point_y)): if block_mask.get_at((point_x - rect.x, point_y - rect.y)): punto.disable() radius_color = rojo mass_color = rojo else: punto.enable() mass_color = negro radius_color = negro mass_text = 'Mass:' + str(round(mass_value, 3)) radius_text = 'Radius:' + str(round(radius_value, 3)) gravity_text = 'Density:' + str( round(mass_value / (radius_value**3), 3)) density_text = 'Gravity:' + str( round(mass_value / (radius_value**2), 3)) if not done: fondo.fill(blanco) fondo.blit(graph, (0, 0)) if block_mask.count() != 0: fondo.blit(block, rect) if punto.disabled: fondo.blit(texto3, rectT3) else: fondo.blit(fuente1.render(mass_text, True, mass_color), (5, rect.bottom + 43)) fondo.blit(fuente1.render(radius_text, True, radius_color), (140, rect.bottom + 43)) fondo.blit(fuente1.render(density_text, True, negro), (130 * 2 - 5, rect.bottom + 43)) fondo.blit(fuente1.render(gravity_text, True, negro), (140 * 3, rect.bottom + 43)) if composition_text_comp is not None: composition_text = 'Composition:' + composition_text_comp fondo.blit( fuente1.render(composition_text, True, negro, blanco), (5, rect.bottom + 64)) fondo.blit(texto1, rectT1) fondo.blit(texto2, rectT2) punto.update() lineas.update() lineas.draw(fondo) display.update() display.quit() return data
def __init__(self): parser = OptionParser( usage="Usage: %prog [OPTIONS] [HOST]", version="NATOcubes 0.5", epilog="If HOST is not specified, the game will start in local mode. Otherwise it will start in client mode, with HOST as server.") parser.add_option('-s', '--server', action="store_true", dest="server", default=False, help="server mode") parser.add_option('-p', '--port', type="int", dest="port", default=12345, help="set port (client & server mode) [default: %default]") parser.add_option('-x', type="int", dest="x", default=5, help="field width (server & local mode) [default: %default]") parser.add_option('-y', type="int", dest="y", default=5, help="field height (server & local mode) [default: %default]") parser.add_option('-z', '--size', type="int", dest="size", default=75, help="size of one field [default: %default]") parser.add_option('-l', '--player', type="int", dest="numplayers", default=2, help="number of players (local mode) [default: %default]") options, args = parser.parse_args() self.xsize, self.ysize, self.fieldsize = options.x, options.y, options.size if options.server: self.handler = server('', options.port, options.x, options.y) else: if len(args) > 0: self.handler = client(args[0], options.port) self.xsize, self.ysize = self.handler.getsize() else: self.handler = local(options.numplayers) self.player, self.localplayer, self.numplayers = self.handler.getopts() self.counts = [] self.f = Field(self.xsize, self.ysize, self.fieldsize) display.set_mode(((self.xsize * (self.fieldsize + 1) - 1), 18 + (self.ysize * (self.fieldsize + 1) - 1))) display.set_caption('NATOcubes') surf = self.f.render() self.handler.surface(surf, self.player, self.fieldsize) display.get_surface().blit(surf, (0, 0)) display.update() ev = event.wait() while ev.type != QUIT: event.clear() display.update() if self.player == self.localplayer or self.localplayer == -1: ev = event.wait() if ev.type == MOUSEBUTTONDOWN: px, py = ev.pos x = px / (self.fieldsize + 1) y = (py - 18) / (self.fieldsize + 1) if self.f.turn(self.player, x, y): self.handler.onTurn(x, y) surf = self.f.render(x, y) self.handler.surface(surf, self.newplayer(), self.fieldsize) display.get_surface().blit(surf, (0, 0)) display.update() if self.after_turn(): return else: recv = self.handler.recv_data() if recv and len(recv) == 2: x = ord(recv[0]) y = ord(recv[1]) if self.f.turn(self.player, x, y): self.handler.distribute_data(x, y) surf = self.f.render(x, y) self.handler.surface(surf, self.newplayer(), self.fieldsize) display.get_surface().blit(surf, (0,0)) display.update() if self.after_turn(): return else: self.handler.failed_turn() elif recv == '\x00': s = smallfont.render('Lost Connection', True, Color('#FFFFFF'), Color('#000000')) sw, sh = s.get_size() display.get_surface().blit(s, (((self.xsize * self.fieldsize) - sw) / 2, ((self.ysize * self.fieldsize) - sh) / 2 + 18)) display.update() while event.wait().type != QUIT: pass return else: sleep(0.1) ev = event.poll()
def Lobby(): title = FONT_TITLE.render('KnatanK', True, RED, YELLOW) start_button = FONT_TITLE.render(' Start! ', True, WHITE, RED) start_button = ( start_button , Rect(60, SCREEN_HEIGHT-60-FONT_TITLE.get_height() , *start_button.get_size())) info = "Waiting for players..." event.set_allowed((pygame.MOUSEBUTTONDOWN, pygame.KEYDOWN, pygame.QUIT)) event.clear() players = {} import uuid my_id = uuid.uuid4().get_hex() I_am_ready = False all_ready = False while not all_ready: for e in event.get(): if((e.type == pygame.MOUSEBUTTONDOWN and start_button[1].collidepoint(e.pos)) or (e.type == pygame.KEYDOWN and e.key == pygame.K_SPACE) ): I_am_ready = True elif( e.type == pygame.QUIT or (e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE) ): print "User quit." pygame.quit() exit() from cPickle import dumps, loads SEND(b'KL' + dumps((my_id, I_am_ready))) for msg, address in RECVFROM(): if msg.startswith(b'KL'): player = loads(msg[2:]) players[player[0]] = player info = str(len(players)) + ' players connected.' if player[0] not in players: print "New player from", address, ":", player, ".", info print players FILL(YELLOW, Rect(40, 40, SCREEN_WIDTH-80, SCREEN_HEIGHT-80)) xy = XY(50, 50) BLIT(title, xy) xy = xy + XY(0, FONT_TITLE.get_linesize()) BLIT(FONT_MENU.render(info, True, BLACK, YELLOW), xy) xy = xy + XY(0, FONT_MENU.get_height()*2) # Brief up all players: playerlist = sorted(players.itervalues()) for p, tank, player in zip(xrange(1,99), TANKS, playerlist): tank.render(xy) BLIT(FONT_MENU.render("Player " + str(p) + (" (you!)" if player[0] == my_id else "") + (" READY!" if player[1] else "") , True, BLACK, YELLOW) , xy + XY(tank.sx+10, (tank.sy-FONT_MENU.get_height())/2)) xy += XY(0, tank.sy) BLIT(*start_button) all_ready = players and all(p[1] for p in playerlist) pygame.display.flip() time.sleep(1) nplayers = len(playerlist) for tn, tank in enumerate(TANKS,1): if tn > nplayers: game.AIControl(tn, tank) elif playerlist[tn-1][0] == my_id: game.LocalControl(tn, tank) else: game.RemoteControl(tn, tank) Game(nplayers) print "Game Over."
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 setUp(self): pygame.display.init() fastevent.init() event.clear() self.assert_(not event.get())
fuente = font.SysFont('verdana',16,bold=True) txt1 = fuente.render('Average', 1, (0,0,0),(125,125,125)) txt2 = fuente.render('Luminosity', 1, (0,0,0),(125,125,125)) txt3 = fuente.render('Lightness', 1, (0,0,0),(125,125,125)) text_rect1 = txt1.get_rect(centerx=rect0.centerx) text_rect2 = txt2.get_rect(centerx=rect1.centerx) text_rect3 = txt3.get_rect(centerx=rect2.centerx) text_rect1.bottom = fondorect.bottom text_rect2.bottom = fondorect.bottom text_rect3.bottom = fondorect.bottom while True: events = Event.get(KEYDOWN) Event.clear() fondo.fill((0,0,0)) for event in events: if event.type == KEYDOWN: py_quit() sys.exit() fondo.blit(rendera,rect0) fondo.blit(renderb,rect1) fondo.blit(rendera,rect2) fondo.blit(txt1,text_rect1) fondo.blit(txt2,text_rect2) fondo.blit(txt3,text_rect3) pantalla.flip()
def rotation_loop(): display.quit() fps = time.Clock() rect_a = rect_top rect_b = rect_mid screen = display.set_mode((400, 440)) rotation_delta = 0 text = render_text_b actual_rotation = 0 instruction = instruction1 running = True rot = [] rotation = 270 while running: fps.tick(60) events = event.get([QUIT, KEYDOWN, KEYUP]) event.clear() for ev in events: if (ev.type == QUIT) or (ev.type == KEYDOWN and ev.key == K_ESCAPE): quit() exit() elif ev.type == KEYDOWN: if ev.key == K_UP: rotation_delta = -1 elif ev.key == K_DOWN: rotation_delta = +1 elif ev.key == K_SPACE: if rect_a == rect_top: rect_a = rect_mid rect_b = rect_top text = render_text_a instruction = instruction2 else: running = False rot.append(q(actual_rotation, 'degree')) rotation = 270 elif ev.type == KEYUP: rotation_delta = 0 if -90 <= rotation + rotation_delta <= 270: rotation += rotation_delta actual_rotation = round(abs(rotation - 270), 3) canvas = draw_ellipse(rotation) screen.fill(Color('grey')) screen.blit(canvas, (0, 0)) screen.blit(render_x, rect_x) screen.blit(render_y, rect_a) screen.blit(render_z, rect_b) screen.blit(text, rect_text) screen.blit(instruction, rect_instruction) screen.blit(render_rotation, rect_rotation) screen.blit( fuente2.render(str(actual_rotation) + '°', 1, Color('black')), rect_rotation.topright) display.update() return rot
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 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: numbers = [ K_KP0, K_KP1, K_KP2, K_KP3, K_KP4, K_KP5, K_KP6, K_KP7, K_KP8, K_KP9 ] if e.key in numbers: digit = numbers.index(e.key) EventHandler.trigger('Key', cls.origin, {'value': str(digit)}) elif e.key == K_KP_PERIOD: EventHandler.trigger('Key', cls.origin, {'value': '.'}) elif 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 }) 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) cls.origin = widgets[0].on_mousebuttondown(e) 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)): widget.on_mouseover() cls.contents.update()
def setUp(self): pygame.display.init() fastevent.init() event.clear()
def __init__(self): parser = OptionParser( usage="Usage: %prog [OPTIONS] [HOST]", version="NATOcubes 0.5", epilog= "If HOST is not specified, the game will start in local mode. Otherwise it will start in client mode, with HOST as server." ) parser.add_option('-s', '--server', action="store_true", dest="server", default=False, help="server mode") parser.add_option( '-p', '--port', type="int", dest="port", default=12345, help="set port (client & server mode) [default: %default]") parser.add_option( '-x', type="int", dest="x", default=5, help="field width (server & local mode) [default: %default]") parser.add_option( '-y', type="int", dest="y", default=5, help="field height (server & local mode) [default: %default]") parser.add_option('-z', '--size', type="int", dest="size", default=75, help="size of one field [default: %default]") parser.add_option( '-l', '--player', type="int", dest="numplayers", default=2, help="number of players (local mode) [default: %default]") options, args = parser.parse_args() self.xsize, self.ysize, self.fieldsize = options.x, options.y, options.size if options.server: self.handler = server('', options.port, options.x, options.y) else: if len(args) > 0: self.handler = client(args[0], options.port) self.xsize, self.ysize = self.handler.getsize() else: self.handler = local(options.numplayers) self.player, self.localplayer, self.numplayers = self.handler.getopts() self.counts = [] self.f = Field(self.xsize, self.ysize, self.fieldsize) display.set_mode(((self.xsize * (self.fieldsize + 1) - 1), 18 + (self.ysize * (self.fieldsize + 1) - 1))) display.set_caption('NATOcubes') surf = self.f.render() self.handler.surface(surf, self.player, self.fieldsize) display.get_surface().blit(surf, (0, 0)) display.update() ev = event.wait() while ev.type != QUIT: event.clear() display.update() if self.player == self.localplayer or self.localplayer == -1: ev = event.wait() if ev.type == MOUSEBUTTONDOWN: px, py = ev.pos x = px / (self.fieldsize + 1) y = (py - 18) / (self.fieldsize + 1) if self.f.turn(self.player, x, y): self.handler.onTurn(x, y) surf = self.f.render(x, y) self.handler.surface(surf, self.newplayer(), self.fieldsize) display.get_surface().blit(surf, (0, 0)) display.update() if self.after_turn(): return else: recv = self.handler.recv_data() if recv and len(recv) == 2: x = ord(recv[0]) y = ord(recv[1]) if self.f.turn(self.player, x, y): self.handler.distribute_data(x, y) surf = self.f.render(x, y) self.handler.surface(surf, self.newplayer(), self.fieldsize) display.get_surface().blit(surf, (0, 0)) display.update() if self.after_turn(): return else: self.handler.failed_turn() elif recv == '\x00': s = smallfont.render('Lost Connection', True, Color('#FFFFFF'), Color('#000000')) sw, sh = s.get_size() display.get_surface().blit( s, (((self.xsize * self.fieldsize) - sw) / 2, ((self.ysize * self.fieldsize) - sh) / 2 + 18)) display.update() while event.wait().type != QUIT: pass return else: sleep(0.1) ev = event.poll()
def clear(self): self._last_press = [None, None] self._last_press_start = [0, 0] self._last_press_times = [0, 0] event.clear()