def on_start(self): "Initialize joysticks" self.joystick = [] for x in range(joystick.get_count()): j = joystick.Joystick(x) j.init() if self.test_mode: print 'Joystick_Input enabled joystick #' + str(x) + \ ': ' + j.get_name() self.joystick.append(j) if not joystick.get_count(): if self.test_mode: print 'Joystick_Input: No Joysticks to Initialize' if self.test_mode: # create a mini component because we don't want to slow down # joystick response unless we're in test_mode class Joystick_Test_Component( Component): @component_method def handle_joybuttondown(self, event): print event @component_method def handle_joybuttonup(self, event): print event @component_method def handle_joyaxismotion(self, event): print event self.owner.components.add(Joystick_Test_Component())
def initialize_controllers(self): """ Initialize Controllers/Joysticks """ joystick.init() if joystick.get_count(): self._log.info('%s Controllers found', joystick.get_count()) self.num_controllers = joystick.get_count() self.controllers = [joystick.Joystick(x) for x in range(self.num_controllers)] for c in self.controllers: self.vPosX.append(0) self.vPosY.append(0) c.init() self._log.info('Initialized controller %s', c.get_name()) self._log.info('Initialized all controllers')
def _load_joysticks( self, *args ): #Clear existing state graphics for i in xrange( self.num_joysticks ): self.states[i].clear() #Clear current list of joysticks self.joysticks = [] self.states = [] self.active_joysticks = [False] * 4 self.active_players = [False] * 4 #Reinitialize pygame.joystick to update joystick information js.quit() js.init() self.num_joysticks = js.get_count() #Create Joystick instance for each physical joystick for i in xrange( self.num_joysticks ): self.joysticks.append( js.Joystick( i ) ) self.joysticks[i].init() #Draw state information for i in xrange( self.num_joysticks ): self.states.append( ControllerState( i, self.graphics ) ) self.states[i].update(self.active_joysticks[i], self.active_players[i] )
def __init__(self): joystick.init() self.count = joystick.get_count() self.joysticks = [] for i in xrange(self.count): controller = XboxController(i) self.joysticks.append(controller)
def set_parameters(self, params): """Set joystick and its axes""" if self.i_j != params.i_j and \ params.i_j < joystick.get_count() and \ params.i_j >= 0: self.i_j = params.i_j self.joystick.quit() self.joystick = joystick.Joystick(self.i_j) self.joystick.init() if self.i_x != params.i_x and \ params.i_x < self.joystick.get_numaxes() and \ params.i_x >= 0: self.i_x = params.i_x if self.i_y != params.i_y and \ params.i_y < self.joystick.get_numaxes() and \ params.i_y >= 0 and \ params.i_y != self.i_x: self.i_y = params.i_y if self.i_x == self.i_y: if self.i_x + 1 >= self.joystick.get_numaxes(): self.i_y = self.i_x - 1 else: self.i_y = self.i_x + 1 self.inv_x = params.inv_x self.inv_y = params.inv_y
def __init__(self, arbalet, runtime_control): """ Simple event manager duplicating the pygame events for the system (runtime hardware management) and the user (game control) The get() method and the system-reserved _get() both poll the pygame event list to keep the list up-to-date and also avoid the pygame internal queue to be full TODO: events pygame/touch to be merged into a unique format :param enable_system_events: enable the acquisition of system events, must be False if no Arbalink polls the system event queue :return: """ Thread.__init__(self) self.setDaemon(True) self._system_events = [] self._user_events = [] self._user_events_lock = RLock() self._arbalet = arbalet self._rate = Rate(self._arbalet.config['refresh_rate']) self._runtime_control = runtime_control self.running = False # All joysticks are enabled by default with self._arbalet.sdl_lock: display.init() joystick.init() for j in range(joystick.get_count()): joy = joystick.Joystick(j) joy.init() self.start()
def __init__(self, joystick_number=JOYSTICK_NUMBER): """ Makes a new joystick instance. :param joystick_number: use if there is more than one joystick :returns: the instance :raises RuntimeWarning if no joystick is found or it is unknown type """ self.joy: Optional[joystick.Joystick] = None self.numAxes: Optional[int] = None self.numButtons: Optional[int] = None self.axes = None self.buttons = None self.name: Optional[str] = None self.joystick_number: int = joystick_number self.lastTime = 0 self.lastActive = 0 self.run_user_model_pressed = False # only used to log changes to/from running user model self._rev_was_pressed = False # to go to reverse mode or toggle out of it self._auto_was_pressed = False # to toggle out of autodrive if we pressed Y on joy to enter it joystick.init() count = joystick.get_count() if count < 1: raise RuntimeWarning('no joystick(s) found') self.platform = platform.system() self.lastActive = time.time() try: self.joy = joystick.Joystick(self.joystick_number) except: if self.platform == 'Linux': # Linux list joysticks from 3 to 0 instead of 0 to 3 if self.joystick_number == 0: self.joy = joystick.Joystick(3) else: self.joy = joystick.Joystick(4 - self.joystick_number) self.joy.init() self.numAxes = self.joy.get_numaxes() self.numButtons = self.joy.get_numbuttons() self.name = self.joy.get_name() logger.info(f'joystick is named "{self.name}"') if not self.name == my_joystick.XBOX_ONE_BLUETOOTH_JOYSTICK \ and not self.name == my_joystick.XBOX_360_WIRELESS_RECEIVER \ and not self.name == my_joystick.XBOX_ELITE \ and not self.name == my_joystick.XBOX_WIRED \ and not self.name == my_joystick.PS4_WIRELESS_CONTROLLER \ and not self.name == my_joystick.PS4_DUALSHOCK4: logger.warning('Name: {}'.format(self.name)) logger.warning( 'Unknown joystick type {} found.' 'Add code to correctly map inputs by running my_joystick as main' .format(self.name)) raise RuntimeWarning('unknown joystick type "{}" found'.format( self.name)) logger.debug( 'joystick named "{}" found with {} axes and {} buttons'.format( self.name, self.numAxes, self.numButtons))
def main(): pygame.init() print("Initiating mobotctl.") sticks = joystick.get_count() if sticks <= 0: print("Error: gamepad not connected.") pad = joystick.Joystick(0) pad.init() axes = [] buttons = [] while True: event.pump() for a in range(pad.get_numaxes()): for b in range(pad.get_numbuttons()) if __name__ == "__main__": main()
def __init__( self, port=65001, rate=10 ): """ Initialize pygame based joystick interface INPUTS: port -- int -- udp port for communication mode -- string -- either 0 which pushes events out or 1 which polls at a given rate rate -- float -- polling frequency """ self.DEBUG = [] self.port = port self.rate = rate # Initialize socket self.sock = socket(AF_INET, SOCK_DGRAM) display.init() # Initialize joystick object joystick.init() num_joys = joystick.get_count() if num_joys < 1: print "No joysticks detected" exit self.j = joystick.Joystick(0) self.j.init() self.t0 = now()
def run(self): ''' Main loop running at ~50Hz ''' next_run = time.time() + 0.02 while not self._exiting: if time.time() > next_run: # Next runtime for 50Hz next_run = time.time() + 0.02 # Get new pygame events. pygame.event.pump() # Iterate over all joysticks. for j in range(joystick.get_count()): stick = joystick.Joystick(j) # Iterate over all axes and emit events. for a in range(stick.get_numaxes()): self.__getattribute__("axis_update_j_{}_a_{}".format(j, a)).emit(int(100 * stick.get_axis(a))) # Iterate over all buttons and emit events if previous state was False and now is True for b in range(stick.get_numbuttons()): current_state = stick.get_button(b) if self._last_button_state[j][b] == False and current_state == True: self._last_button_state[j][b] = True self.button_pressed.emit(j, b) if self._last_button_state[j][b] == True and current_state == True: if self._last_button_time[j][b] == 0: self._last_button_time[j][b] = time.time() else: if time.time() - self._last_button_time[j][b] > 0.5: self.button_pressed.emit(j, b) self._last_button_time[j][b] = 0 if self._last_button_state[j][b] == True and current_state == False: self._last_button_state[j][b] = False self._last_button_time[j][b] = 0 # Give the CPU a bit of rest. time.sleep(0.01)
def main(argv=[]): display.init() joystick.init() if len(argv) > 1: for sz in argv[1:]: try: joystick.Joystick(int(sz)).init() except: pass else: for i in xrange(joystick.get_count()): joystick.Joystick(i).init() e = event.wait() while e.type != QUIT: if e.type == JOYAXISMOTION: print 'js', e.joy, 'axis', e.axis, round(e.value, P) elif e.type == JOYBALLMOTION: print 'js', e.joy, 'ball', e.ball, round(e.rel, P) elif e.type == JOYHATMOTION: print 'js', e.joy, 'hat', e.hat, h[e.value] elif e.type == JOYBUTTONUP: print 'js', e.joy, 'button', e.button, 'up' elif e.type == JOYBUTTONDOWN: print 'js', e.joy, 'button', e.button, 'down' e = event.wait()
def __init__(self, parent = None): pygame.init() joyCount = joystick.get_count() self.axisObservers = defaultdict(list) self.hatObservers = defaultdict(list) self.buttonObservers = defaultdict(list) self.current = -1 self.joyList = {} self.lastAxisValue = [[] for i in range(joyCount)] self.lastHatValue = [[] for i in range(joyCount)] self.lastButtonValue = [[] for i in range(joyCount)] for jid in reversed(range(joystick.get_count())): self.__createJoystick__(jid) self.current = jid self.dispatcher = EventDispatcher(self) self.dispatcher.start()
def __init__(self): if hasattr(EventManager, "_singleton"): return key.set_repeat(DELAY, RATE) event.set_allowed(None) event.set_allowed([KEYDOWN, JOYBUTTONDOWN, JOYAXISMOTION, JOYBUTTONUP, PLAYER]) for i in range(joystick.get_count()): joystick.Joystick(i).init() # Information for joystick repeat. self._last_press = [None, None] self._last_press_start = [0, 0] self._last_press_times = [0, 0] # Maps key values to player numbers. self.players = { K_w: 0, K_a: 0, K_s: 0, K_d: 0, K_q: 0, K_e: 0, K_i: 1, K_j: 1, K_k: 1, K_l: 1, K_u: 1, K_o: 1, K_LEFT: 0, K_RIGHT: 0, K_UP: 0, K_DOWN: 0, K_SPACE: 0, K_KP_ENTER: 0, K_RETURN: 0, K_2: 1, K_1: 0, K_BACKSPACE: 1 } # Maps key values to internal event keys. self.events = { K_w: UP, K_a: LEFT, K_s: DOWN, K_d: RIGHT, K_q: ROT_CC, K_e: ROT_CW, K_i: UP, K_j: LEFT, K_k: DOWN, K_l: RIGHT, K_u: ROT_CC, K_o: ROT_CW, K_LEFT: LEFT, K_RIGHT: RIGHT, K_UP: UP, K_DOWN: DOWN, K_SPACE: ROT_CC, K_KP_ENTER: CONFIRM, K_RETURN: CONFIRM, K_2: CONFIRM, K_BACKSPACE: CONFIRM, K_1: CONFIRM } Singleton.__init__(self)
def __init__(self): self.world = b2World(gravity=(0, 0)) for x, y, ex, ey in ( #50x80 field with 4 static objects (walls) TODO add 2; locations are in (cx,cy,w/2,h/2) (-27.5, 0, .5, 13.5), (27.5, 0, .5, 13.5), (0, -14, 27, .5), (0, 14, 27, .5), ): body = self.world.CreateStaticBody( position=(x, y), shapes=b2PolygonShape(box=(ex, ey)), ) #friction .2 self.robot = self.world.CreateDynamicBody(position=(-20, 0)) box = self.robot.CreatePolygonFixture( box=(3, 3), density=100, friction=.7 ) #TODO use right parameters; 100 kg? 3'x3f; friction does NOTHING for now self.robot.linearDamping = .7 self.robot.angularDamping = 1.4 self.joy = None if joystick.get_count() < 1: print "warning: no joystick" self.joy = None else: self.joy = joystick.Joystick(0) self.joy.init() print "joystick", self.joy.get_name()
def pygame(self): # obsolete, lags maybe due to graphical stuff needed from os import environ environ["SDL_VIDEODRIVER"] = "dummy" # no window needed from pygame import init, joystick, display init() display.set_mode((1,1)) # starts a mini widow joystick.init() count = joystick.get_count() for jno in range(0,count): # initialize them all js = joystick.Joystick(jno) js.init() # assign to multi player interfaces from pygame.event import get from pygame.locals import JOYAXISMOTION, JOYHATMOTION, JOYBUTTONDOWN, JOYBUTTONUP, QUIT self.running = True while self.running: for event in get(): if QUIT == event.type: self.kill() elif hasattr(event,'joy'): # not a gamepad interface = self.interfaces[event.joy] # stick actions # 0 == left stick x # 1 == left stick y # 2 == right stick x # 3 == right stick y # 5 == l2m # 4 == r2m if JOYAXISMOTION == event.type: # 7 self.running = interface.handler(event.type*10+event.axis,event.value) # cross actions # (-1,0) == left # ( 1,0) == right # (0, 1) == up # (0,-1) == down elif JOYHATMOTION == event.type: # 9 if((-1,0)== event.value):self.running = interface.handler(90,1) elif((1,0)== event.value):self.running = interface.handler(91,1) elif((0,-1)== event.value):self.running = interface.handler(92,1) elif((0,1)== event.value):self.running = interface.handler(93,1) else:self.running = interface.handler(94,0) # button actions # 0 == a # 1 == b # 3 == x # 4 == y # 6 == l1 # 7 == r1 # 8 == l2b # 9 == r2b # 10 == select # 11 == start # 13 == l3 # 14 == r3 elif JOYBUTTONUP == event.type: # 11 no value ! self.running = interface.handler(100+event.button,0) elif JOYBUTTONDOWN == event.type: # 10 no value ! self.running = interface.handler(100+event.button,1) self.display.quit()
def restart(): global joy_in, joystick_count joystick.init() joystick_count = joystick.get_count() if joystick_count > 0: joy_in = joystick.Joystick(0) joy_in.init()
def init_joystick(self): JoystickMgrBase.init_joystick(self) pygame.init() joystick.init() self.joysticks = [ joystick.Joystick(idx) for idx in range(joystick.get_count()) ] map(lambda joystick: joystick.init(), self.joysticks) eng.attach_obs(self.on_frame)
def __init__(self): ''' Constructor ''' pygame.init() # Initialise all joysticks. for j in range(0, joystick.get_count()): stick = joystick.Joystick(j) stick.init() # Pre-fill _last_button_state with 0 self._last_button_state = [[ False for b in range(joystick.Joystick(j).get_numbuttons()) ] for j in range(joystick.get_count())] self._last_button_time = [[ 0 for b in range(joystick.Joystick(j).get_numbuttons()) ] for j in range(joystick.get_count())] QtCore.QThread.__init__(self) # Are we exiting the loop? self._exiting = False
def _init_controllers(self): """ Helper method: Setup available PS4 controllers """ if not joystick.get_init(): joystick.init() for joy_id in range(joystick.get_count()): js = joystick.Joystick(joy_id) if PS4C.is_ps4_controller(js.get_name()): js.init() ps4ctrl = PS4C(js) self._controllers.append(ps4ctrl)
def __init__(self, id=0): joystick.init() assert joystick.get_count() self.joystick = joystick.Joystick(id) self.id = id self.joystick.init() self.ctab = { (0, -1): IController.LEFT, (0, 1): IController.RIGHT, (1, 0): IController.DOWN, (-1, 0): IController.UP }
def get_joystick_list(self): """Get a list of connected joysticks. Returns: List of strings describing connected joysticks. """ joystick.init() joysticks = ['None'] for i in range(joystick.get_count()): stick = joystick.Joystick(i) joysticks.append("{0}: {1}".format(i, stick.get_name())) return joysticks
def get_all_gamepads(self): """ Finds all connected joysticks Returns a dictionary with pygame id of joystick as key and name as value """ joysticks = {} for i in range(joystick.get_count()): stick = joystick.Joystick(i) stick.init() joysticks[i] = stick.get_name() stick.quit() return joysticks
def create_players(self): level = self player1 = KnightController(level.spawn_pc()) if joystick.get_count() > 0: self.controllers.append( JoyController(player1, joystick.Joystick(0))) else: self.controllers.append(KeyboardController(player1.update)) self.controllers.append(player1) if joystick.get_count() > 1: print("2-player game") player1.knight.pos.x *= 0.5 player2 = KnightController(level.spawn_pc(color=(0.4, 0.9, 1.1, 1))) player2.knight.pos.x += player1.pos.x self.controllers.append( JoyController(player2, joystick.Joystick(1))) self.controllers.append(player2) else: print("1-player game")
def __init__(self, state): pygame.init() pygame.mixer.init() # pygame.key.set_repeat(300, 50) if not pygame.font: exit() # Detect and register gamepads self.gpads = [] if gpad.get_count() != 0: print "Gamepad(s) detected." count = gpad.get_count() for i in range(count): joy = gpad.Joystick(i) joy.init() print i, joy.get_name() self.gpads.append(joy) self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((self.width, self.height)) resourcemanager.load_resources() self.font_s = pygame.font.Font(resourcemanager.fontpath, 10) self.font_m = pygame.font.Font(resourcemanager.fontpath, 18) self.font_l = pygame.font.Font(resourcemanager.fontpath, 32) pygame.display.set_caption(self.title) self.state = state(self) self.background = pygame.Surface(self.screen.get_size()) self.background = self.background.convert() self.background.fill(self.background_color) self.screen.blit(self.background, (0, 0)) self.state.display(self.screen)
def __init__(self): # Get controllers joystick.init() joys = [joystick.Joystick(x) for x in range(joystick.get_count())] [js.init() for js in joys if not js.get_init()] joy_gen = (js for js in joys if is_valid(js)) # Set attributes self.controllers = [Controller(i, next(joy_gen, None)) for i in (1,2)] self.players = [None,None] self.buffers = [Input(), Input()] self.triggered = [Input(), Input()] self.zipable = self.players, self.controllers, \ self.buffers, self.triggered
def refresh(self): """ Finds all connected gamepads. Must be called at the start of the run loop if there has been a change. Will uninitialize and then initialize the joystick module """ if self.joystick: self.joystick.quit() self.joystick = None joystick.quit() joystick.init() joyDictList = self.get_all_gamepads() # Must be fetched before initializing the ID, since otherwise we delete that ID afterwards, apparently the objects here are global! self.initialize(clamp(self.joystick_id, 0, maxVal((joystick.get_count() - 1), 0))) self.refreshedGamepad.emit(joyDictList) self.statusChanged.emit(self.joystick.get_init() if self.joystick else False)
def __init__(self): ''' Constructor ''' pygame.init() # Initialise all joysticks. for j in range(0, joystick.get_count()): stick = joystick.Joystick(j) stick.init() # Pre-fill _last_button_state with 0 self._last_button_state = [[False for b in range(joystick.Joystick(j).get_numbuttons())] for j in range(joystick.get_count())] self._last_button_time = [[0 for b in range(joystick.Joystick(j).get_numbuttons())] for j in range(joystick.get_count())] QtCore.QThread.__init__(self) # Are we exiting the loop? self._exiting = False
def __init__(self): pygame.init() pygame.display.set_caption(GAME_NAME) pygame.mouse.set_visible(False) pygame.joystick.init() for stick_no in range(joystick.get_count()): stick = joystick.Joystick(stick_no) print "Initialising joystick %d" % stick_no stick.init() if FULL_SCREEN: fullscreen = FULLSCREEN else: fullscreen = False self.window = pygame.display.set_mode(WINDOW_SIZE, fullscreen, COLOR_DEPTH) self.layers = pygame.sprite.LayeredDirty()
def _listConnected(cls) -> tuple: """ List the connected controller. Params: logger: The logger. Returns: The list of connected controller. """ connected = [] for ctrlrId in range(joystick.get_count()): ctrlrName = joystick.Joystick(ctrlrId).get_name() connected.append(ctrlrName) return tuple(connected)
def __init__(self): State.State.__init__(self) if not JoySettings.FONT: JoySettings.FONT = PF.Font("fonts/red_october.ttf", 15) if not JoySettings.SECFONT: JoySettings.SECFONT = PF.Font("fonts/red_october.ttf", 20) self.font = JoySettings.FONT self.font2 = JoySettings.SECFONT self.num_joys = PJ.get_count() self.no_joy = False if self.num_joys == 0: self.no_joy = True return joys = [] for i in range(self.num_joys): joy = PJ.Joystick(i) joy.init() joys.append(joy) self.buttons = [ "Move Up", "Move Down", "Move Left", "Move Right", "Shoot Up", "Shoot Down", "Shoot Left", "Shoot Right", "Activation Key", ] self.instructions = self.font.render( "Press buttons on gamepad to configure." "" " Press X to set to default settings.", True, (255, 255, 255) ) self.surfs = [] for i in range(len(self.buttons)): self.surfs.append(self.font2.render(self.buttons[i], True, (255, 255, 255))) self.index = 0 self.selected_buttons = [] if joys[0].get_numbuttons() < 9: self.no_joy = True return for i in range(joys[0].get_numbuttons()): JoySettings.POSS_BUTTONS.append(i) self.continue_string = self.font2.render("", True, (255, 255, 255)) self.button_pos = set([(1, 0), (-1, 0), (0, 1), (0, -1)])
def setup_joystick(): pygame.init() joystick.init() if joystick.get_count() == 1: stick = joystick.Joystick(0) stick.init() axisNum = stick.get_numaxes() buttonNum = stick.get_numbuttons() joystickMode = 'not active' # toggles to 'position' with 'j' key print('joystick found with ' + str(axisNum) + ' axes and ' + str(buttonNum) + ' buttons') else: stick = None joystickMode = None print('no joystick found, only PD control or no control possible') return stick, joystickMode
def __init__(self, joystick_number=JOYSTICK_NUMBER): """ Makes a new joystick instance. :param joystick_number: use if there is more than one joystick :returns: the instance :raises RuntimeWarning if no joystick is found or it is unknown type """ self.joy:Optional[joystick.Joystick]=None self.car_command:car_command=car_command() self.user_input:user_input = user_input() self.default_car_command=car_command() self.default_user_input=user_input() self.numAxes:Optional[int]=None self.numButtons:Optional[int]=None self.axes=None self.buttons=None self.name:Optional[str]=None self.joystick_number:int=joystick_number self.lastTime = 0 self.lastActive = 0 self._rev_was_pressed=False # to go to reverse mode or toggle out of it joystick.init() count = joystick.get_count() if count<1: raise RuntimeWarning('no joystick(s) found') self.lastActive=time.time() if platform.system() == 'Linux': if self.joystick_number == 0: self.joy = joystick.Joystick(3) # TODO why? else: self.joy = joystick.Joystick(4 - self.joystick_number) # TODO why is this cryptic code needed? What does it do? else: self.joy = joystick.Joystick(self.joystick_number) self.joy.init() self.numAxes = self.joy.get_numaxes() self.numButtons = self.joy.get_numbuttons() self.name=self.joy.get_name() if not self.name==my_joystick.XBOX_ONE_BLUETOOTH_JOYSTICK and not self.name==my_joystick.XBOX_ELITE and not self.name==my_joystick.XBOX_WIRED: logger.warning('Name: {}'.format(self.name)) logger.warning('unknown joystick type {} found: add code to correctly map inputs by running my_joystick as main'.format(self.name)) raise RuntimeWarning('unknown joystick type {} found'.format(self.name)) logger.info('joystick named "{}" found with {} axes and {} buttons'.format(self.name, self.numAxes, self.numButtons))
def __init__(self, argparser): Arbapp.__init__(self, argparser, True) # starting mock mode, init flags (-w and -ng) will be redirected to the server init() joystick.init() self.joysticks = [] self.server_process = None # Joysticks initialization for i in range(joystick.get_count()): joy = joystick.Joystick(i) joy.init() if joy.get_numbuttons()>0: self.joysticks.append(joy) else: joy.quit() print len(self.joysticks), 'joystick(s) with buttons found!'
def __init__(self): self.port = 'COM22' # change this to the com port for your Arduino self.baud = 115200 # baudrate don't change try: self.ser = serial.Serial(self.port, self.baud) print "Successfully opened Serial" print except serial.SerialException: self.ser = None print "Could not open Serial!" print # Initialize Joystick object joystick.init() pygame.display.init() if joystick.get_count(): self.joy = joystick.Joystick(0) self.joy.init() else: self.joy = None self.x_axis = 0 # this is usually 0 self.throttle_axis = 1 # change this to the correct axis for the joystick self.last_turn_val = 0 self.last_sheet_val = 47 self.auto_enabled = False # change to true to use PID self.kite_tracker = KiteTracker(path='cam') self.pos_list = [] self.pid = PID(3.0, 0.4, 1.2) self.pid.setSetPoint( 0.0 ) # Set-point corresponds to heading vector which has angle = 0.0 in its frame. # create log file self.logfile = datetime.datetime.strftime( datetime.datetime.now(), '%Y-%m-%d_%H_%M_%S') + '_log.txt' with open(logfile, 'w') as f: f.write('time,command,turn_val,power_val\n')
def __init__(self, name='demo'): """Initialise pygame and load the parameters for the game indicated by the `name` param. Start the clock for the screen's frame rate and create a window surface for the game's screen size. Create each of the screen objects referenced by the game and store their state, ready to show. """ init() joystick.init() for i in range(joystick.get_count()): joystick.Joystick(i).init() State.game = util.load_cfg(name) State.clock = Clock(10, State.game['frame_rate']) State.window = display.set_mode(State.game['screen_size']) self._last_joystick_action = None self.create_screens()
def __init__(self): State.State.__init__(self) if not JoySettings.FONT: JoySettings.FONT = PF.Font("fonts/red_october.ttf", 15) if not JoySettings.SECFONT: JoySettings.SECFONT = PF.Font("fonts/red_october.ttf", 20) self.font = JoySettings.FONT self.font2 = JoySettings.SECFONT self.num_joys = PJ.get_count() self.no_joy = False if self.num_joys == 0: self.no_joy = True return joys = [] for i in range(self.num_joys): joy = PJ.Joystick(i) joy.init() joys.append(joy) self.buttons = [ "Move Up", "Move Down", "Move Left", "Move Right", "Shoot Up", "Shoot Down", "Shoot Left", "Shoot Right", "Activation Key" ] self.instructions = self.font.render( "Press buttons on gamepad to configure." "" " Press X to set to default settings.", True, (255, 255, 255)) self.surfs = [] for i in range(len(self.buttons)): self.surfs.append( self.font2.render(self.buttons[i], True, (255, 255, 255))) self.index = 0 self.selected_buttons = [] if joys[0].get_numbuttons() < 9: self.no_joy = True return for i in range(joys[0].get_numbuttons()): JoySettings.POSS_BUTTONS.append(i) self.continue_string = self.font2.render("", True, (255, 255, 255)) self.button_pos = set([(1, 0), (-1, 0), (0, 1), (0, -1)])
def init(): import json, os joystick.init() controllers = list() for i in range(joystick.get_count()): print("added") joy = joystick.Joystick(i) joy.init() controller = Controller(joy, i) with open(os.path.join("xbox_keys.json"), 'r+') as file: keys = json.load(file) print(keys) controller.load_controls(keys) controllers.append(controller) return controllers
def app(list_joysticks, list_bluetooth, joy, device): if list_joysticks: joystick.init() print('Joysticks:') for i in range(joystick.get_count()): j = joystick.Joystick(i) print(j.get_id(), j.get_name()) if list_bluetooth: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: list_bluetooth_devices(ble)) if device is not None: ble = Adafruit_BluefruitLE.get_provider() ble.initialize() ble.run_mainloop_with(lambda: get_device(ble, device)) return bluetooth = get_device(ble, device) bluetooth.connect() atexit.register(bluetooth.disconnect) UART.discover(bluetooth) uart = UART(bluetooth) if joy is not None: os.environ['SDL_VIDEODRIVER'] = 'dummy' pygame.init() joystick.init() j = joystick.Joystick(joy) j.init() print('Axes:', j.get_numaxes()) while True: pygame.event.get() for i in range(j.get_numaxes()): if bluetooth and uart: uart.write('{}{}\n'.format(i, j.get_axis(i))) print(' '.join( [str(j.get_axis(i)) for i in range(j.get_numaxes())]), end='\r') time.sleep(0.05)
def init_controls(settings): global movement_keys global stick global use_left_stick global use_hat movement_keys[keys.W] = movement_keys[keys.UP] = Vector2D(+0, -1) movement_keys[keys.S] = movement_keys[keys.DOWN] = Vector2D(+0, +1) movement_keys[keys.A] = movement_keys[keys.LEFT] = Vector2D(-1, +0) movement_keys[keys.D] = movement_keys[keys.RIGHT] = Vector2D(+1, +0) which_joystick = settings['joystick'] if which_joystick < joystick.get_count(): stick = joystick.Joystick(which_joystick) stick.init() axes = stick.get_numaxes() noun = "axis" if axes == 1 else "axes" print(f"[INFO] {axes} joystick analogue {noun}") use_left_stick = ( (max(settings['move x axis'], settings['move y axis']) < axes) and (min(settings['move x axis'], settings['move y axis']) >= 0)) buttons = stick.get_numbuttons() noun = "button" if buttons == 1 else "buttons" print(f"[INFO] {buttons} joystick {noun}") hats = stick.get_numhats() noun = "hat" if hats == 1 else "hats" print(f"[INFO] {hats} joystick {noun}") use_hat = hats >= 1 use_hat = ((settings['hat'] < hats) and (settings['hat'] >= 0)) else: print(f"[WARN] Insufficient joysticks!") print( f"[WARN] We want joystick #{which_joystick}, but only {joystick.get_count()} joysticks detected." ) use_left_stick = use_hat = False stick = None print("[INFO] use left stick?", use_left_stick) print("[INFO] use hat?", use_hat)
def __init__(self): self.port = 'COM22' # change this to the com port for your Arduino self.baud = 115200 # baudrate don't change try: self.ser = serial.Serial(self.port, self.baud) print "Successfully opened Serial" print except serial.SerialException: self.ser = None print "Could not open Serial!" print # Initialize Joystick object joystick.init() pygame.display.init() if joystick.get_count(): self.joy = joystick.Joystick(0) self.joy.init() else: self.joy = None self.x_axis = 0 # this is usually 0 self.throttle_axis = 1 # change this to the correct axis for the joystick self.last_turn_val = 0 self.last_sheet_val = 47 self.auto_enabled = False # change to true to use PID self.kite_tracker = KiteTracker(path='cam') self.pos_list = [] self.pid = PID(3.0, 0.4, 1.2) self.pid.setSetPoint(0.0) # Set-point corresponds to heading vector which has angle = 0.0 in its frame. # create log file self.logfile = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H_%M_%S') + '_log.txt' with open(logfile, 'w') as f: f.write('time,command,turn_val,power_val\n')
def run(self): ''' Main loop running at ~50Hz ''' next_run = time.time() + 0.02 while not self._exiting: if time.time() > next_run: # Next runtime for 50Hz next_run = time.time() + 0.02 # Get new pygame events. pygame.event.pump() # Iterate over all joysticks. for j in range(joystick.get_count()): stick = joystick.Joystick(j) # Iterate over all axes and emit events. for a in range(stick.get_numaxes()): self.__getattribute__("axis_update_j_{}_a_{}".format( j, a)).emit(int(100 * stick.get_axis(a))) # Iterate over all buttons and emit events if previous state was False and now is True for b in range(stick.get_numbuttons()): current_state = stick.get_button(b) if self._last_button_state[j][ b] == False and current_state == True: self._last_button_state[j][b] = True self.button_pressed.emit(j, b) if self._last_button_state[j][ b] == True and current_state == True: if self._last_button_time[j][b] == 0: self._last_button_time[j][b] = time.time() else: if time.time( ) - self._last_button_time[j][b] > 0.5: self.button_pressed.emit(j, b) self._last_button_time[j][b] = 0 if self._last_button_state[j][ b] == True and current_state == False: self._last_button_state[j][b] = False self._last_button_time[j][b] = 0 # Give the CPU a bit of rest. time.sleep(0.01)
def __init__(self): print "Initializing..." pygame.init() window = pygame.display.set_mode((400, 400)) self.state = 0,0 self.queue = Queue.Queue() self.thread = SerialThread(SERIAL_DEVICE, self.queue) self.thread.start() if joystick.get_count() > 0: self.joystick = joystick.Joystick(0) print "Using the first joystick on your system:" print "joystick name: %s" % self.joystick.get_name() print "Initializing joystick..." self.joystick.init() else: self.joystick = None print "Ready." self.loop()
def __init__(self, params): '''Initialize internal variables''' # Find us a joystick pygame.init() joystick.init() if joystick.get_count() == 0: raise OSError("No joysticks found!") self.joystick = joystick.Joystick(0) self.joystick.init() self.i_j = 0 self.i_x = 0 self.i_y = 1 self.inv_x = True self.inv_y = True self.v_max = params[1] self.w_max = params[2] Controller.__init__(self, params[0])
def __init__(self): self.world=b2World(gravity=(0,0)) for x,y,ex,ey in(#50x80 field with 4 static objects (walls) TODO add 2; locations are in (cx,cy,w/2,h/2) (-27.5,0,.5,13.5), (27.5,0,.5,13.5), (0,-14,27,.5), (0,14,27,.5), ): body=self.world.CreateStaticBody( position=(x,y), shapes=b2PolygonShape(box=(ex,ey)), )#friction .2 self.robot=self.world.CreateDynamicBody(position=(-20,0)) box=self.robot.CreatePolygonFixture(box=(3,3),density=100,friction=.7)#TODO use right parameters; 100 kg? 3'x3f; friction does NOTHING for now self.robot.linearDamping=.7 self.robot.angularDamping=1.4 self.joy=None if joystick.get_count()<1: print"warning: no joystick" self.joy=None else: self.joy=joystick.Joystick(0) self.joy.init() print"joystick",self.joy.get_name()
def initgame(self): self.transition = Transitions(loader) self.getparameters() self.GameOver = False self.BlackScreen = 0 self.p_ID = self.b.get() self.p_age = self.d.get() self.p_gender = self.f.get() self.file = open('logs/Reversal3D_logfile_'+str(self.p_ID)+'.txt', 'w') self.file.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t" % ("pID","Age","Gender","TrialNumber","Reversal","Target", "Choice","Correct","TotalScore","RunningTotal", "TrialNumPhase", "Visits0","Visits1", "Visits2","Visits3","ResponseTime")) print "ID:", self.p_ID, "Gender:",self.p_gender,"Age:",self.p_age self.rungame = True self.TotalScore = 0 self.RunningTotal = 0 self.trial_no = -1 self.new_trial = True self.end_aq_after = 5 self.end_rev_after = 5 self.trial_num_phase = 0 if self.p_gender == "Male": self.kiki = CreateActor("Models/baseboy.x","textures/baseboy2.png",0,0,0,0) else: self.kiki = CreateActor("Models/kiki.x","textures/kiki.jpg",0,0,0,0) self.kiki.currentframe= 0 self.kiki.reparentTo(self.render) self.isTurning = False self.lag = 0 self.ScoreText = None self.framerate = 30 globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(self.framerate) self.frames = [int(round(i)) for i in np.arange(0,1200,60./self.framerate)] self.present1 = CreateActor("Models/test.x","textures/presentgrey.png",0,0,0,0) self.present1.reparentTo(self.render) self.present2 = CreateActor("Models/test.x","textures/presentgrey.png",0,0,0,0) self.present2.reparentTo(self.render) self.present3 = CreateActor("Models/test.x","textures/presentgrey.png",0,0,0,0) self.present3.reparentTo(self.render) self.present4 = CreateActor("Models/test.x","textures/presentgrey.png",0,0,0,0) self.present4.reparentTo(self.render) self.presents = [self.present1,self.present2,self.present3,self.present4] self.texgrey = loader.loadTexture("textures/presentgrey.png") if self.boxcol == "A": self.tex1 = loader.loadTexture("textures/presentblue.png") self.tex2 = loader.loadTexture("textures/presentyellow.jpg") self.tex3 = loader.loadTexture("textures/presentpink.jpg") self.tex4 = loader.loadTexture("textures/presentgreen.png") self.tex5 = loader.loadTexture("textures/presentpurple.png") else: self.tex1 = loader.loadTexture("textures/presentbrown.jpg") self.tex2 = loader.loadTexture("textures/presentorange.png") self.tex3 = loader.loadTexture("textures/presentred.png") self.tex4 = loader.loadTexture("textures/presentgreys.png") self.tex5 = loader.loadTexture("textures/presentlightpurple.png") self.textures = [self.tex1,self.tex2,self.tex3,self.tex4] self.star = self.loader.loadModel("Models/star.x") tex = loader.loadTexture("textures/gold_texture.jpg") self.star.setTexture(tex) self.star.setScale(self.starsize) self.star.setPos(0, 0, 3) self.clouds = CreateActor("Models/clouds.x","textures/cotton.jpg",0,0,0,0) self.star.setScale(self.cloudsize) self.environ = self.loader.loadModel("Models/Room.x") self.environ.reparentTo(self.render) if self.wallcol == "A": tex = loader.loadTexture("textures/arena.png") else: tex = loader.loadTexture("textures/room2.png") self.environ.setTexture(tex) self.environ.setScale(2, 2, 2) self.environ.setPos(0, 0, 0) self.starLoc = [] for i in range(4): for j in range(10): self.starLoc.append([i,j]) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.kiki) self.floater.setZ(2.0) self.angle = -2*np.pi*self.kiki.getH()/360 alight = AmbientLight('alight') alight.setColor(VBase4(2, 2, 2, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0, 0, 0, 0)) self.plnp = render.attachNewNode(self.plight) #animation frames: self.runframe = get_frames(1,40,self.framerate) self.digframe = get_frames(60,240,self.framerate) self.presentsframe = get_frames(0,180,self.framerate) self.winframe = get_frames(320,360,self.framerate) self.losingframe = get_frames(380,460,self.framerate) self.dragframe = get_frames(242,302,self.framerate) self.cloudsframe = get_frames(0,180,self.framerate) self.correctbox = fluffle([0,1,2])[0] #np.random.randint(0,3) self.reversal = 0 self.savelog = False self.joystickon = 0 try: if joystick.get_count() > 0: self.joystickon = 1 self.joystick = joystick.Joystick(0) self.joystick.init() except: print "Joystick Error" self.joystickon = 0
player1 = make_player(pos=center - Vector2(200, 0), angle=-math.pi * 0.5) player1.score_label = score2 player2 = make_player(pos=center + Vector2(200, 0), angle=math.pi * 0.5) player2.score_label = score1 star = scene.layers[-1].add_circle(radius=40, fill=False, color=GREEN, stroke_width=LINE_W, pos=(scene.width / 2, scene.height / 2)) objects = [star, player1, player2] joystick.init() sticks = [joystick.Joystick(i) for i in range(min(joystick.get_count(), 2))] for s in sticks: s.init() def pressed(key): return lambda: keyboard[key] controls = [ (player1, pressed(keys.W), pressed(keys.A), pressed(keys.D), keys.E), (player2, pressed(keys.UP), pressed(keys.LEFT), pressed(keys.RIGHT), keys.RETURN), ]
from pygame import joystick, key from pygame.locals import * joystick.init() joyin = None if(joystick.get_count() > 0): joyin = joystick.Joystick(0) joyin.init() def check_input(player): xaxis = yaxis = 0 if joyin: xaxis = joyin.get_axis(0) yaxis = joyin.get_axis(1) if key.get_pressed()[K_LEFT] or xaxis < -0.8: player.angle = 180 player.movex = -20 if key.get_pressed()[K_RIGHT] or xaxis > 0.8: player.angle = 0 player.movex = 20 if key.get_pressed()[K_UP] or yaxis < -0.8: player.angle = 90 player.movey = -20 if key.get_pressed()[K_DOWN] or yaxis > 0.8: player.angle = 270 player.movey = 20
#---------------------Some variables--------------------# mylaby = laby(5, 5) mylaby.generate_laby() perso = Perso(mylaby) perso_time = 0 liste_b1 = Fonction.liste_bip(WW, WH) liste_b2 = Fonction.fill_liste_b2(liste_b1) display.flip() key.set_repeat(50, 55) # FIN if joystick.get_count() > 0: Joy = joystick.Joystick(0) Joy.init() while True: time.Clock().tick(30) Window.fill(const.Porange) for event in handle_widgets(): if event.type == QUIT: quit() exit() elif event.type == JOYAXISMOTION: if event.axis == 1:
def initgame(self): self.transition = Transitions(loader) self.getparameters() self.GameOver = False self.BlackScreen = 0 self.p_ID = self.b.get() self.p_age = self.d.get() self.p_gender = self.f.get() self.file = open( 'logs/Reversal3D_end30_5of6_logfile_' + str(self.p_ID) + '.txt', 'w') # added two extra columns to the log file self.file.write( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t" % ("pID", "Age", "Gender", "TrialNumber", "Reversal", "Target", "Choice", "NovelBox", "PrevReward", "Correct", "TotalScore", "RunningTotal", "Last6TrialsTotal", "TrialNumPhase", "VisitColor0", "VisitColor1", "VisitColor2", "VisitColor3", "Visits0", "Visits1", "Visits2", "Visits3", "ResponseTime")) print "ID:", self.p_ID, "Gender:", self.p_gender, "Age:", self.p_age print "ID:", self.p_ID, "Gender:", self.p_gender, "Age:", self.p_age self.rungame = True self.TotalScore = 0 self.RunningTotal = 0 self.trial_no = -1 self.new_trial = True self.end_aq_after = 30 self.end_rev_after = 30 self.trial_num_phase = 0 self.reverse_now = False self.TrialScoreList = [] self.TrialScoreLastFiveSix = [] self.LastFiveSixCount = 0 self.novel_box = [] self.previous_reward = [] # when starting a new trial, pick gender and kiki parameters self.new_trial = True if self.p_gender == "Male": self.kiki = CreateActor("Models/baseboy.x", "textures/baseboy2.png", 0, 0, 0, 0) else: self.kiki = CreateActor("Models/kiki.x", "textures/kiki.jpg", 0, 0, 0, 0) self.kiki.currentframe = 0 self.kiki.reparentTo(self.render) self.isTurning = False self.lag = 0 self.ScoreText = None # how often screen refreshes self.framerate = 30 globalClock.setMode(ClockObject.MLimited) globalClock.setFrameRate(self.framerate) self.frames = [ int(round(i)) for i in np.arange(0, 1200, 60. / self.framerate) ] # creating the boxes self.present1 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present1.reparentTo(self.render) self.present2 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present2.reparentTo(self.render) self.present3 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present3.reparentTo(self.render) self.present4 = CreateActor("Models/test.x", "textures/presentgrey.png", 0, 0, 0, 0) self.present4.reparentTo(self.render) self.presents = [ self.present1, self.present2, self.present3, self.present4 ] self.texgrey = loader.loadTexture("textures/presentgrey.png") if self.boxcol == "A": self.tex1 = loader.loadTexture("textures/presentblue.png") self.tex2 = loader.loadTexture("textures/presentyellow.jpg") self.tex3 = loader.loadTexture("textures/presentpink.jpg") self.tex4 = loader.loadTexture("textures/presentgreen.png") self.tex5 = loader.loadTexture("textures/presentpurple.png") else: self.tex1 = loader.loadTexture("textures/presentbrown.jpg") self.tex2 = loader.loadTexture("textures/presentorange.png") self.tex3 = loader.loadTexture("textures/presentred.png") self.tex4 = loader.loadTexture("textures/presentgreys.png") self.tex5 = loader.loadTexture("textures/presentlightpurple.png") self.textures = [self.tex1, self.tex2, self.tex3, self.tex4] # making the star and positions self.star = self.loader.loadModel("Models/star.x") tex = loader.loadTexture("textures/gold_texture.jpg") self.star.setTexture(tex) self.star.setScale(self.starsize) self.star.setPos(0, 0, 3) # making the black cloud and their positions self.clouds = CreateActor("Models/clouds.x", "textures/cotton.jpg", 0, 0, 0, 0) self.star.setScale(self.cloudsize) # setting up the room environment self.environ = self.loader.loadModel("Models/Room.x") self.environ.reparentTo(self.render) # setting the wall colors - note that Reversal task uses set "A" and # practice task uses set B if self.wallcol == "A": tex = loader.loadTexture("textures/arena.png") else: # set B tex = loader.loadTexture("textures/room2.png") self.environ.setTexture(tex) self.environ.setScale(2, 2, 2) self.environ.setPos(0, 0, 0) self.starLoc = [] for i in range(4): for j in range(10): self.starLoc.append([i, j]) self.floater = NodePath(PandaNode("floater")) self.floater.reparentTo(self.kiki) self.floater.setZ(2.0) self.angle = -2 * np.pi * self.kiki.getH() / 360 alight = AmbientLight('alight') alight.setColor(VBase4(2, 2, 2, 1)) alnp = render.attachNewNode(alight) render.setLight(alnp) self.plight = PointLight('plight') self.plight.setColor(VBase4(0, 0, 0, 0)) self.plnp = render.attachNewNode(self.plight) #animation frames: self.runframe = get_frames(1, 40, self.framerate) self.digframe = get_frames(60, 240, self.framerate) self.presentsframe = get_frames(0, 180, self.framerate) self.winframe = get_frames(320, 360, self.framerate) self.losingframe = get_frames(380, 460, self.framerate) self.dragframe = get_frames(242, 302, self.framerate) self.cloudsframe = get_frames(0, 180, self.framerate) # this is the new way to randomize the correct box for each subject # this will also reset for reversal # correct box is never going to be #3! # so then number 3 choice is novel! self.correctbox = fluffle([0, 1, 2])[0] #np.random.randint(0,3) self.reversal = 0 self.savelog = False # we don't have the joystick version # will always print error in console self.joystickon = 0 try: if joystick.get_count() > 0: self.joystickon = 1 self.joystick = joystick.Joystick(0) self.joystick.init() except: print "Joystick Error" self.joystickon = 0
import sys sys.path.append('..') from SimulationKit import Simulator from SimulationKit.Robots import SpiderWHydraulics from ControlsKit.filters import LowPassFilter from ControlsKit.time_sources import global_time import pygame.joystick as joystick import time if not joystick.get_init(): joystick.init() if joystick.get_count() != 1: print "Sorry, need joystick" exit() stick = joystick.Joystick(0) stick.init() print "Joystick detected: ", stick.get_name() print "Axes: ", stick.get_numaxes() print "Balls: ", stick.get_numballs() print "Hats: ", stick.get_numhats() print "Buttons: ", stick.get_numbuttons() stick_neutrals = [] d = {'offset': (0, 0, 1.5)} s = Simulator(dt=2e-3, plane=1, pave=0, graphical=1, ground_grade=.00, robot=SpiderWHydraulics,
import pygame as PG import pygame.joystick as PJ import pygame.event as PE import sys PG.init() print PJ.get_count() joy = PJ.Joystick(0) joy.init() print "Name", joy.get_name() print "Hats", joy.get_numhats() print "Buttons", joy.get_numbuttons() print "Axes", joy.get_numaxes() print "Balls", joy.get_numballs() while True: events = PE.get() for event in events: if event.type == QUIT: sys.quit() print pygame.JOYBUTTONUP
def run(self): CLOCK = pygameTime.Clock() self.refresh() # Startup Gamepad. lastEventTime = time.time() while self.shouldDestroy == False: now = time.time() if self.needRefresh: # User wants to check for newly connected or disconnected gamepad, reinits list + gamepads stuff. self.refresh() self.needRefresh = False lastEventTime = now continue if self.joystick_id_switch >= 0: # User wants to select a different gamepad! self.initialize(self.joystick_id_switch) self.joystick_id_switch = -1 continue # Go through the event list and find button, axis and hat events for EVENT in event.get(): eventHappened = False if EVENT.type == JOYBUTTONDOWN or EVENT.type == JOYBUTTONUP: self.read_rover_buttons() eventHappened = True if EVENT.type == JOYAXISMOTION or EVENT.type == JOYHATMOTION: if self.read_rover_axis(): eventHappened = True if eventHappened: lastEventTime = now message = { "Axis" : self.rover_axis, "Buttons" : self.rover_buttons } print(message) UDP.ROVERSERVER.writeToRover(json.dumps(message, separators=(',', ':'))) if (now - lastEventTime) >= (GAMEPAD_REFRESH_INTERVAL_CONNECTED if (joystick and (joystick.get_count() > 0)) else GAMEPAD_REFRESH_INTERVAL_DISCONNECTED): self.refresh() lastEventTime = now # Limit the clock rate to 30 ticks per second CLOCK.tick(30) quit()
#!/usr/bin/python from pygame import joystick, init, display, event import os, sys print "init pygame" os.environ["SDL_VIDEODRIVER"] = "dummy" init() display.init() display.set_mode((1,1)) joystick.init() if joystick.get_count() < 1: print "please plug a joystick" sys.exit(1) j = joystick.Joystick(0) j.init() print "ok" from servo.config import ServoConfig from servo.network import ServoNetwork config = ServoConfig() network = ServoNetwork(config) DEG90=307 DEG45=int(DEG90/2) P180=512 P90=P180-DEG90 P270=P180+DEG90 HEAD_FORWARD=int(P180-DEG90/2)
def joystick_count(self): return joystick.get_count()
def update(self, playerObj, menuObject): """ Pulls events from the event queue """ if self.num_controllers < joystick.get_count(): self._log.error('A controller disconnected unexpectantly! Attempting to reinitialize all controllers...') self.initialize_controllers() # Input event handler for event in pygame.event.get(): action = 0 if event.type == QUIT: action = QUIT_GAME elif event.type == KEYDOWN: if event.key == K_LEFT: action = self.action_mappings["KEY_DOWN_LEFT"] elif event.key == K_RIGHT: action = self.action_mappings["KEY_DOWN_RIGHT"] elif event.key == K_DOWN: action = self.action_mappings["KEY_DOWN_DOWN"] elif event.key == K_UP: action = self.action_mappings["KEY_DOWN_UP"] elif event.key == K_x: action = self.action_mappings["KEY_DOWN_X"] elif event.key == K_SPACE: action = self.action_mappings["KEY_DOWN_SPACE"] elif event.key == K_e: action = self.action_mappings["KEY_DOWN_E"] elif event.key == K_TAB: action = self.action_mappings["KEY_DOWN_TAB"] elif event.key == K_p: action = self.action_mappings["KEY_DOWN_P"] elif event.key == K_q: action = self.action_mappings["KEY_DOWN_Q"] elif event.key == K_1: action = self.action_mappings["KEY_DOWN_1"] elif event.key == K_f: action = self.action_mappings["KEY_DOWN_F"] elif event.key == K_s: action = self.action_mappings["KEY_DOWN_S"] elif event.key == K_BACKSPACE: action = self.action_mappings["KEY_DOWN_BACKSPACE"] elif event.key == K_ESCAPE: action = self.action_mappings["KEY_DOWN_ESCAPE"] elif event.type == KEYUP: # stop moving the player if event.key == K_LEFT: action = self.action_mappings["KEY_UP_LEFT"] elif event.key == K_RIGHT: action = self.action_mappings["KEY_UP_RIGHT"] elif event.key == K_DOWN: action = self.action_mappings["KEY_UP_DOWN"] elif event.key == K_UP: action = self.action_mappings["KEY_UP_UP"] elif event.key == K_SPACE: action = self.action_mappings["KEY_UP_SPACE"] elif event.key == K_e: action = self.action_mappings["KEY_UP_E"] elif event.type == JOYAXISMOTION: # TODO: multiple controllers self._axis_movement(0, playerObj) #for con in range(self.num_controllers): # self._axis_movement(con, self.players[con]) elif event.type == JOYBUTTONDOWN: # TODO: non 10-button controller handling if self.controllers[0].get_button(0): # 'A' action = self.action_mappings["JOY_A"] elif self.controllers[0].get_button(1): # 'B' action = self.action_mappings["JOY_B"] elif self.controllers[0].get_button(2): # 'X' action = self.action_mappings["JOY_X"] elif self.controllers[0].get_button(3): # 'Y' action = self.action_mappings["JOY_Y"] elif self.controllers[0].get_button(4): # 'LB' action = self.action_mappings["JOY_LB"] elif self.controllers[0].get_button(5): # 'RB' action = self.action_mappings["JOY_RB"] elif self.controllers[0].get_button(6): # 'back' (the double window button thing) action = self.action_mappings["JOY_BACK"] elif self.controllers[0].get_button(7): # 'start' (triple lines button thing) action = self.action_mappings["JOY_START"] elif self.controllers[0].get_button(8): # 'LS' depression (maybe) action = self.action_mappings["JOY_LS"] elif self.controllers[0].get_button(9): # 'RS' depression (maybe) action = self.action_mappings["JOY_RS"] else: self._log.error('Controller has more than 10 buttons! OMG!') elif event.type == JOYBUTTONUP: action = NO_PICKUP_OBJECT # ugly ass hack elif event.type == JOYHATMOTION: # TODO: non 1-hat controller handling hat = self.controllers[0].get_hat(0) if hat == HAT_UP: action = self.action_mappings["JOY_HAT_UP"] elif hat == HAT_DOWN: action = self.action_mappings["JOY_HAT_DOWN"] elif hat == HAT_RIGHT: action = self.action_mappings["JOY_HAT_RIGHT"] elif hat == HAT_LEFT: action = self.action_mappings["JOY_HAT_LEFT"] self._perform_action(action=action, playerObj=playerObj, menuObject=menuObject) if pygame.mouse.get_pressed(): self._perform_action(self.action_mappings["MOUSE_PRESSED"], playerObj, menuObject)
def __init__(self): js = None if joy.get_count() > 0: js = joy.Joystick(0) js.init() self.js = js
#!/usr/bin/python import pygame from pygame import joystick from pygame import event from pygame.locals import * import os import time os.system("cellwriter --hide-window &") pygame.init() joystick.init() num_dev = joystick.get_count() accel = None i = 0 while i < num_dev: accel = joystick.Joystick(i) try: accel.init() except pygame.error: print "Error initializing accelerator!" exit(1) i += 1 if accel.get_numaxes() == 3: break if not accel: print "No accelerator device found. Exiting..." exit(1)