def connect(self, player_adds, num_players, my_player_id): self.connections = [None] * num_players for p in range(num_players): if p == my_player_id: continue connection = None iAmServer = p > my_player_id if iAmServer: connection = MessageQueueHolder(True) connection.start_connect(player_adds[my_player_id], 25565 + p) else: connection = MessageQueueHolder(False) connection.start_connect(player_adds[p], 25565 + my_player_id) self.connections[p] = connection print("Started connection to host " + str(p)) for p in range(num_players): if p == my_player_id: continue connection = self.connections[p] print("Connecting to host " + str(p) + " (" + connection.host + ":" + str(connection.port) + ")") while not connection.connected: SDL_Delay(100) print("Connected to host " + str(p)) connection.start_update() print("Finished connecting")
def run(self): menu_input = Input() last_update_time = SDL_GetTicks() # units.MS while self.running: start_time = SDL_GetTicks() # units.MS menu_input.begin_new_frame() menu_events = get_events() for event in menu_events: if event.type == SDL_KEYDOWN: menu_input.key_down_event(event) elif event.type == SDL_KEYUP: menu_input.key_up_event(event) elif event.type == SDL_QUIT: self.running = False break # Exit if menu_input.was_key_pressed(SDLK_ESCAPE): self.running = False # Move the cursor elif menu_input.was_key_pressed(SDLK_UP): if self.cursor_position != 0: self.cursor_position -= 1 elif menu_input.was_key_pressed(SDLK_DOWN): if self.cursor_position != 4: self.cursor_position += 1 # Select option elif menu_input.was_key_pressed(SDLK_RETURN): self.running = False if self.cursor_position == 0: self.launch_game() current_time = SDL_GetTicks() # units.MS elapsed_time = current_time - last_update_time # units.MS self.update(min(elapsed_time, MAX_FRAME_TIME)) last_update_time = current_time self.renderer.process(self.world, self.sprites) # This loop lasts 1/60th of a second, or 1000/60th ms ms_per_frame = 1000 // FPS # units.MS elapsed_time = SDL_GetTicks() - start_time # units.MS if elapsed_time < ms_per_frame: SDL_Delay(ms_per_frame - elapsed_time)
def drift_correct(self, location=None, target=None, fill_color=None, draw_target=True): """Checks the accuracy of the eye tracker's calibration by presenting a fixation stimulus and requiring the participant to press the space bar while looking directly at it. If there is a large difference between the gaze location at the time the key was pressed and the true location of the fixation, it indicates that there has been drift in the calibration. In TryLink mode, drift correct targets are still displayed the same as with a hardware eye tracker. Simulated drift corrects are performed by clicking the drift correct target with the mouse. Args: location (Tuple(int, int), optional): The (x,y) pixel coordinates where the drift correct target should be located. Defaults to the center of the screen. target: A :obj:`Drawbject` or other :func:`KLGraphics.blit`-able shape to use as the drift correct target. Defaults to a circular :func:`drift_correct_target`. fill_color: A :obj:`List` or :obj:`Tuple` containing an RGBA colour to use for the background for the drift correct screen. Defaults to the value of ``P.default_fill_color``. draw_target (bool, optional): A flag indicating whether the function should draw the drift correct target itself (True), or whether it should leave it to the programmer to draw the target before :meth:`drift_correct` is called (False). Defaults to True. """ show_mouse_cursor() target = drift_correct_target() if target is None else target draw_target = EL_TRUE if draw_target in [EL_TRUE, True] else EL_FALSE location = P.screen_c if location is None else location if not iterable(location): raise ValueError("'location' must be a pair of (x,y) pixel coordinates.") dc_boundary = CircleBoundary('drift_correct', location, P.screen_y // 30) while True: event_queue = pump(True) ui_request(queue=event_queue) if draw_target == EL_TRUE: fill(P.default_fill_color if not fill_color else fill_color) blit(target, 5, location) flip() else: SDL_Delay(2) # required for pump() to reliably return mousebuttondown events for e in event_queue: if e.type == SDL_MOUSEBUTTONDOWN and dc_boundary.within([e.button.x, e.button.y]): hide_mouse_cursor() if draw_target == EL_TRUE: fill(P.default_fill_color if not fill_color else fill_color) flip() return 0
def connect(self, host, port): if self.isServer: self.sock.bind((host, port)) self.sock.listen(1) self.sock, self.addr = self.sock.accept() else: connected = False while not connected: SDL_Delay(1000) try: self.sock.connect((host, port)) connected = True except Exception: print("Connection to " + host + " failed, retrying")
def wait(milliseconds): """Pause the program for an amount of time. Will pause for a given number of milliseconds. This function sleeps the process to share the processor with other programs. A program that waits for even a few milliseconds will consume very little processor time. Usage: wait(milliseconds) Returns: int (the actual number of milliseconds used) """ start = SDL_GetTicks() SDL_Delay(int(milliseconds)) return SDL_GetTicks() - start
def render(self): # Render background SDL_SetRenderDrawColor(self._renderer, BLACK_COLOR.r, BLACK_COLOR.g, BLACK_COLOR.b, BLACK_COLOR.a) SDL_RenderClear(self._renderer) # Render game objects top_piece = None win_box = None for game_object in self._game_objects: if game_object.id == "piece" and globals( )["Piece"].top == game_object: top_piece = game_object elif game_object.id == "win_box": win_box = game_object else: game_object.draw(self._renderer) if top_piece: top_piece.draw(self._renderer) if win_box: win_box.draw(self._renderer) # Update renderer SDL_RenderPresent(self._renderer) SDL_Delay(SCREEN_TICKS_PER_FRAME) # ~16ms ~60fps
def event_loop(configs, joy_map, tty_fd): event = SDL_Event() # keep of dict of active joystick devices as a dict of # instance_id -> (config_id, SDL_Joystick object) active_devices = {} # keep an event queue populated with the current active inputs # indexed by joystick index, input type and input index # the values consist of: # - the event list (as taked from the event configuration) # - the number of times event was emitted (repeated) # - the last time when the event was fired # e.g. { event_hash -> ([event_list], repeat_no, last_fire_time) } event_queue = {} # keep track of axis previous values axis_prev_values = {} def handle_new_input(e: SDL_Event, axis_norm_value: int = 0) -> bool: """ Event handling for button press/hat movement/axis movement Only needed when an new input is present Returns True when 'event_queue' is modified with a new event """ dev_index = active_devices[event.jdevice.which][0] if e.type == SDL_JOYBUTTONDOWN: mapped_events = configs[dev_index].get_btn_event( event.jbutton.button) event_index = f'{dev_index}_btn{event.jbutton.button}' elif e.type == SDL_JOYHATMOTION: mapped_events = configs[dev_index].get_hat_event( event.jhat.hat, event.jhat.value) event_index = f'{dev_index}_hat{event.jhat.hat}' elif e.type == SDL_JOYAXISMOTION and axis_norm_value != 0: mapped_events = configs[dev_index].get_axis_event( event.jaxis.axis, axis_norm_value) event_index = f'{dev_index}_axis{event.jaxis.axis}' if mapped_events is not None: event_queue[event_index] = [mapped_events, 0, SDL_GetTicks()] return True return False running = True while running: input_started = False while SDL_PollEvent(byref(event)): if event.type == SDL_QUIT: running = False break if event.type == SDL_JOYDEVICEADDED: stick = joystick.SDL_JoystickOpen(event.jdevice.which) name = joystick.SDL_JoystickName(stick).decode('utf-8') guid = create_string_buffer(33) joystick.SDL_JoystickGetGUIDString( joystick.SDL_JoystickGetGUID(stick), guid, 33) LOG.debug( f'Joystick #{joystick.SDL_JoystickInstanceID(stick)} {name} added' ) conf_found = False # try to find a configuration for the joystick for key, dev_conf in enumerate(configs): if dev_conf.name == str( name) or dev_conf.guid == guid.value.decode(): # Add the matching joystick configuration to the watched list active_devices[joystick.SDL_JoystickInstanceID( stick)] = (key, stick) LOG.debug( f'Added configuration for known device {configs[key]}' ) conf_found = True break # add the default configuration for unknown/un-configured joysticks if not conf_found: LOG.debug( f'Un-configured device "{str(name)}", mapped using generic mapping' ) active_devices[joystick.SDL_JoystickInstanceID(stick)] = ( 0, stick) # if the device has axis inputs, initialize to zero their initial position if joystick.SDL_JoystickNumAxes(stick) > 0: axis_prev_values[joystick.SDL_JoystickInstanceID( stick)] = [ 0 for x in range(joystick.SDL_JoystickNumAxes(stick)) ] continue if event.jdevice.which not in active_devices: continue else: dev_index = active_devices[event.jdevice.which][0] if event.type == SDL_JOYDEVICEREMOVED: joystick.SDL_JoystickClose( active_devices[event.jdevice.which][1]) active_devices.pop(event.jdevice.which, None) axis_prev_values.pop(event.jdevice.which, None) LOG.debug(f'Removed joystick #{event.jdevice.which}') if event.type == SDL_JOYBUTTONDOWN: input_started = handle_new_input(event) if event.type == SDL_JOYBUTTONUP: event_queue.pop(f'{dev_index}_btn{event.jbutton.button}', None) if event.type == SDL_JOYHATMOTION: if event.jhat.value != SDL_HAT_CENTERED: input_started = handle_new_input(event) else: event_queue.pop(f'{dev_index}_hat{event.jhat.hat}', None) if event.type == SDL_JOYAXISMOTION: # check if the axis value went over the deadzone threshold if (abs(event.jaxis.value) > JS_AXIS_DEADZONE) \ != (abs(axis_prev_values[event.jdevice.which][event.jaxis.axis]) > JS_AXIS_DEADZONE): # normalize the axis value to the movement direction or stop the input if abs(event.jaxis.value) <= JS_AXIS_DEADZONE: event_queue.pop(f'{dev_index}_axis{event.jaxis.axis}', None) else: if event.jaxis.value < 0: axis_norm_value = -1 else: axis_norm_value = 1 input_started = handle_new_input( event, axis_norm_value) # store the axis current values for tracking axis_prev_values[event.jdevice.which][ event.jaxis.axis] = event.jaxis.value # process the current events in the queue if len(event_queue): emitted_events = filter_active_events(event_queue) if len(emitted_events): LOG.debug(f'Events emitted: {emitted_events}') # send the events mapped key code(s) to the terminal for k in emitted_events: if k in joy_map: for c in joy_map[k]: fcntl.ioctl(tty_fd, termios.TIOCSTI, c) SDL_Delay(JS_POLL_DELAY)
def wait(milliseconds): """...""" start = SDL_GetTicks() SDL_Delay(int(milliseconds)) return SDL_GetTicks() - start
def run(self): game_input = Input() speed_x, speed_y = 2, 1 player_pos = [-100, -100] # motion_type = self.player_motion_type # facing = self.player_facing self.running = True last_update_time = SDL_GetTicks() # units.MS while self.running: start_time = SDL_GetTicks() # units.MS game_input.begin_new_frame() game_events = get_events() for event in game_events: if event.type == SDL_KEYDOWN: game_input.key_down_event(event) elif event.type == SDL_KEYUP: game_input.key_up_event(event) elif event.type == SDL_QUIT: self.running = False break if not self.running: self.clear() break # Exit if game_input.was_key_pressed(SDLK_ESCAPE): self.clear() self.running = False break # Player movement if game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held( SDLK_UP): player_pos[0] -= speed_x player_pos[1] += speed_y self.player.velocity.vx = speed_x self.player.velocity.vy = -speed_y self.player.facing.set("right_up") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held( SDLK_DOWN): player_pos[0] -= speed_x player_pos[1] -= speed_y self.player.velocity.vx = speed_x self.player.velocity.vy = speed_y self.player.facing.set("right_down") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held( SDLK_UP): player_pos[0] += speed_x player_pos[1] += speed_y self.player.velocity.vx = -speed_x self.player.velocity.vy = -speed_y self.player.facing.set("left_up") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held( SDLK_DOWN): player_pos[0] += speed_x player_pos[1] -= speed_y self.player.velocity.vx = -speed_x self.player.velocity.vy = speed_y self.player.facing.set("left_down") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_LEFT): player_pos[0] += speed_x self.player.velocity.vx = -speed_x self.player.facing.set("left") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_RIGHT): player_pos[0] -= speed_x self.player.velocity.vx = speed_x self.player.facing.set("right") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_UP): player_pos[1] += speed_y self.player.velocity.vy = -speed_y self.player.facing.set("up") self.player.motiontype.set("walking") elif game_input.is_key_held(SDLK_DOWN): player_pos[1] -= speed_y self.player.velocity.vy = speed_y self.player.facing.set("down") self.player.motiontype.set("walking") # elif game_input.was_key_pressed(SDLK_i): # self.player.toggle_inventory() # Player Attack elif game_input.is_key_held(SDLK_SPACE): pass # motion_type = MotionType.CASTING # Nothing else: self.player.velocity.vx = 0 self.player.velocity.vy = 0 self.player.motiontype.set("standing") current_time = SDL_GetTicks() # units.MS elapsed_time = current_time - last_update_time # units.MS last_update_time = current_time self.world.process() # This loop lasts 1/60th of a second, or 1000/60th ms ms_per_frame = 1000 // FPS # units.MS elapsed_time = SDL_GetTicks() - start_time # units.MS if elapsed_time < ms_per_frame: SDL_Delay(ms_per_frame - elapsed_time)
def run(self): game_input = Input() speed_x, speed_y = 2, 1 player_pos = [0, 0] motion_type = self.player.motion_type facing = self.player.facing running = True last_update_time = SDL_GetTicks() # units.MS while running: start_time = SDL_GetTicks() # units.MS game_input.begin_new_frame() game_events = get_events() for event in game_events: if event.type == SDL_KEYDOWN: game_input.key_down_event(event) elif event.type == SDL_KEYUP: game_input.key_up_event(event) elif event.type == SDL_QUIT: running = False break # Exit if game_input.was_key_pressed(SDLK_ESCAPE): running = False # Player movement if game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held( SDLK_UP): player_pos[0] -= speed_x player_pos[1] += speed_y motion_type = MotionType.WALKING facing = Facing.RIGHT_UP elif game_input.is_key_held(SDLK_RIGHT) and game_input.is_key_held( SDLK_DOWN): player_pos[0] -= speed_x player_pos[1] -= speed_y motion_type = MotionType.WALKING facing = Facing.RIGHT_DOWN elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held( SDLK_UP): player_pos[0] += speed_x player_pos[1] += speed_y motion_type = MotionType.WALKING facing = Facing.LEFT_UP elif game_input.is_key_held(SDLK_LEFT) and game_input.is_key_held( SDLK_DOWN): player_pos[0] += speed_x player_pos[1] -= speed_y motion_type = MotionType.WALKING facing = Facing.LEFT_DOWN elif game_input.is_key_held(SDLK_LEFT): player_pos[0] += speed_x motion_type = MotionType.WALKING facing = Facing.LEFT elif game_input.is_key_held(SDLK_RIGHT): player_pos[0] -= speed_x motion_type = MotionType.WALKING facing = Facing.RIGHT elif game_input.is_key_held(SDLK_UP): player_pos[1] += speed_y motion_type = MotionType.WALKING facing = Facing.UP elif game_input.is_key_held(SDLK_DOWN): player_pos[1] -= speed_y motion_type = MotionType.WALKING facing = Facing.DOWN elif game_input.was_key_pressed(SDLK_i): self.player.toggle_inventory() # Player Attack elif game_input.is_key_held(SDLK_SPACE): motion_type = MotionType.CASTING # Nothing else: motion_type = MotionType.STANDING current_time = SDL_GetTicks() # units.MS elapsed_time = current_time - last_update_time # units.MS self.update(player_pos, motion_type, facing, min(elapsed_time, MAX_FRAME_TIME)) last_update_time = current_time self.get_sprites() self.renderer.process(self.world, self.sprites) self.sprites.clear() # This loop lasts 1/60th of a second, or 1000/60th ms ms_per_frame = 1000 // FPS # units.MS elapsed_time = SDL_GetTicks() - start_time # units.MS if elapsed_time < ms_per_frame: SDL_Delay(ms_per_frame - elapsed_time)
def run(): # Create the environment, in which our particles will exist. world = sdl2ext.World() # Set up the globally available information about the current mouse # position. We use that information to determine the emitter # location for new particles. world.mousex = 400 world.mousey = 300 # Create the particle engine. It is just a simple System that uses # callback functions to update a set of components. engine = particles.ParticleEngine() # Bind the callback functions to the particle engine. The engine # does the following on processing: # 1) reduce the life time of each particle by one # 2) create a list of particles, which's life time is 0 or below. # 3) call createfunc() with the world passed to process() and # the list of dead particles # 4) call updatefunc() with the world passed to process() and the # set of particles, which still are alive. # 5) call deletefunc() with the world passed to process() and the # list of dead particles. deletefunc() is respsonible for # removing the dead particles from the world. engine.createfunc = createparticles engine.updatefunc = updateparticles engine.deletefunc = deleteparticles world.add_system(engine) # We create all particles at once before starting the processing. # We also could create them in chunks to have a visually more # appealing effect, but let's keep it simple. createparticles(world, None, 300) # Initialize the video subsystem, create a window and make it visible. sdl2ext.init() window = sdl2ext.Window("Particles", size=(800, 600)) window.show() # Create a hardware-accelerated sprite factory. The sprite factory requires # a rendering context, which enables it to create the underlying textures # that serve as the visual parts for the sprites. renderer = sdl2ext.RenderContext(window) factory = sdl2ext.SpriteFactory(sdl2ext.TEXTURE, renderer=renderer) # Create a set of images to be used as particles on rendering. The # images are used by the ParticleRenderer created below. images = (factory.from_image(RESOURCES.get_path("circle.png")), factory.from_image(RESOURCES.get_path("square.png")), factory.from_image(RESOURCES.get_path("star.png"))) # Center the mouse on the window. We use the SDL2 functions directly # here. Since the SDL2 functions do not know anything about the # sdl2.ext.Window class, we have to pass the window's SDL_Window to it. SDL_WarpMouseInWindow(window.window, world.mousex, world.mousey) # Hide the mouse cursor, so it does not show up - just show the # particles. SDL_ShowCursor(0) # Create the rendering system for the particles. This is somewhat # similar to the SoftSpriteRenderer, but since we only operate with # hundreds of particles (and not sprites with all their overhead), # we need an own rendering system. particlerenderer = ParticleRenderer(renderer, images) world.add_system(particlerenderer) # The almighty event loop. You already know several parts of it. running = True while running: for event in sdl2ext.get_events(): if event.type == SDL_QUIT: running = False break if event.type == SDL_MOUSEMOTION: # Take care of the mouse motions here. Every time the # mouse is moved, we will make that information globally # available to our application environment by updating # the world attributes created earlier. world.mousex = event.motion.x world.mousey = event.motion.y # We updated the mouse coordinates once, ditch all the # other ones. Since world.process() might take several # milliseconds, new motion events can occur on the event # queue (10ths to 100ths!), and we do not want to handle # each of them. For this example, it is enough to handle # one per update cycle. SDL_FlushEvent(SDL_MOUSEMOTION) break world.process() SDL_Delay(1) sdl2ext.quit() return 0