Game Controller/Joystick

sprite_move_joystick.py
  1"""
  2Move Sprite with Joystick
  3
  4Simple program to show basic sprite usage.
  5
  6Artwork from http://kenney.nl
  7
  8If Python and Arcade are installed, this example can be run from the command line with:
  9python -m arcade.examples.sprite_move_joystick
 10"""
 11
 12import arcade
 13import os
 14
 15SPRITE_SCALING = 0.5
 16
 17SCREEN_WIDTH = 800
 18SCREEN_HEIGHT = 600
 19SCREEN_TITLE = "Move Sprite with Joystick Example"
 20
 21MOVEMENT_SPEED = 5
 22DEAD_ZONE = 0.05
 23
 24
 25class Player(arcade.Sprite):
 26    """ Player sprite """
 27    def __init__(self, filename, scale):
 28        super().__init__(filename, scale)
 29
 30        # Get list of game controllers that are available
 31        joysticks = arcade.get_joysticks()
 32
 33        # If we have any...
 34        if joysticks:
 35            # Grab the first one in  the list
 36            self.joystick = joysticks[0]
 37
 38            # Open it for input
 39            self.joystick.open()
 40
 41            # Push this object as a handler for joystick events.
 42            # Required for the on_joy* events to be called.
 43            self.joystick.push_handlers(self)
 44        else:
 45            # Handle if there are no joysticks.
 46            print("There are no joysticks, plug in a joystick and run again.")
 47            self.joystick = None
 48
 49    def update(self):
 50        """ Move the player """
 51
 52        # If there is a joystick, grab the speed.
 53        if self.joystick:
 54
 55            # x-axis
 56            self.change_x = self.joystick.x * MOVEMENT_SPEED
 57            # Set a "dead zone" to prevent drive from a centered joystick
 58            if abs(self.change_x) < DEAD_ZONE:
 59                self.change_x = 0
 60
 61            # y-axis
 62            self.change_y = -self.joystick.y * MOVEMENT_SPEED
 63            # Set a "dead zone" to prevent drive from a centered joystick
 64            if abs(self.change_y) < DEAD_ZONE:
 65                self.change_y = 0
 66
 67        # Move the player
 68        self.center_x += self.change_x
 69        self.center_y += self.change_y
 70
 71        # Keep from moving off-screen
 72        if self.left < 0:
 73            self.left = 0
 74        elif self.right > SCREEN_WIDTH - 1:
 75            self.right = SCREEN_WIDTH - 1
 76
 77        if self.bottom < 0:
 78            self.bottom = 0
 79        elif self.top > SCREEN_HEIGHT - 1:
 80            self.top = SCREEN_HEIGHT - 1
 81
 82    # noinspection PyMethodMayBeStatic
 83    def on_joybutton_press(self, _joystick, button):
 84        """ Handle button-down event for the joystick """
 85        print("Button {} down".format(button))
 86
 87    # noinspection PyMethodMayBeStatic
 88    def on_joybutton_release(self, _joystick, button):
 89        """ Handle button-up event for the joystick """
 90        print("Button {} up".format(button))
 91
 92    # noinspection PyMethodMayBeStatic
 93    def on_joyhat_motion(self, _joystick, hat_x, hat_y):
 94        """ Handle hat events """
 95        print("Hat ({}, {})".format(hat_x, hat_y))
 96
 97class MyGame(arcade.Window):
 98    """
 99    Main application class.
100    """
101
102    def __init__(self, width, height, title):
103        """
104        Initializer
105        """
106
107        # Set the working directory (where we expect to find files) to the same
108        # directory this .py file is in. You can leave this out of your own
109        # code, but it is needed to easily run the examples using "python -m"
110        # as mentioned at the top of this program.
111        file_path = os.path.dirname(os.path.abspath(__file__))
112        os.chdir(file_path)
113
114        # Call the parent class initializer
115        super().__init__(width, height, title)
116
117        # Variables that will hold sprite lists
118        self.all_sprites_list = None
119
120        # Set up the player info
121        self.player_sprite = None
122
123        # Set the background color
124        arcade.set_background_color(arcade.color.AMAZON)
125
126    def setup(self):
127        """ Set up the game and initialize the variables. """
128
129        # Sprite lists
130        self.all_sprites_list = arcade.SpriteList()
131
132        # Set up the player
133        self.player_sprite = Player(":resources:images/animated_characters/female_person/femalePerson_idle.png", SPRITE_SCALING)
134        self.player_sprite.center_x = 50
135        self.player_sprite.center_y = 50
136        self.all_sprites_list.append(self.player_sprite)
137
138    def on_draw(self):
139        """
140        Render the screen.
141        """
142
143        # This command has to happen before we start drawing
144        arcade.start_render()
145
146        # Draw all the sprites.
147        self.all_sprites_list.draw()
148
149    def on_update(self, delta_time):
150        """ Movement and game logic """
151
152        # Call update on all sprites (The sprites don't do much in this
153        # example though.)
154        self.all_sprites_list.update()
155
156    def on_key_press(self, key, modifiers):
157        """Called whenever a key is pressed. """
158
159        if key == arcade.key.UP:
160            self.player_sprite.change_y = MOVEMENT_SPEED
161        elif key == arcade.key.DOWN:
162            self.player_sprite.change_y = -MOVEMENT_SPEED
163        elif key == arcade.key.LEFT:
164            self.player_sprite.change_x = -MOVEMENT_SPEED
165        elif key == arcade.key.RIGHT:
166            self.player_sprite.change_x = MOVEMENT_SPEED
167
168    def on_key_release(self, key, modifiers):
169        """Called when the user releases a key. """
170
171        if key == arcade.key.UP or key == arcade.key.DOWN:
172            self.player_sprite.change_y = 0
173        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
174            self.player_sprite.change_x = 0
175
176
177def main():
178    """ Main method """
179    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
180    window.setup()
181    arcade.run()
182
183
184if __name__ == "__main__":
185    main()