Sprites That Follow The Player

Screen shot of using sprites to collect coins
sprite_follow_simple.py
  1"""
  2Sprite Follow Player
  3
  4This moves towards the player in both the x and y direction.
  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_follow_simple
 10"""
 11
 12import random
 13import arcade
 14import os
 15
 16# --- Constants ---
 17SPRITE_SCALING_PLAYER = 0.5
 18SPRITE_SCALING_COIN = 0.2
 19COIN_COUNT = 50
 20
 21SCREEN_WIDTH = 800
 22SCREEN_HEIGHT = 600
 23SCREEN_TITLE = "Sprite Follow Player Simple Example"
 24
 25SPRITE_SPEED = 0.5
 26
 27
 28class Coin(arcade.Sprite):
 29    """
 30    This class represents the coins on our screen. It is a child class of
 31    the arcade library's "Sprite" class.
 32    """
 33
 34    def follow_sprite(self, player_sprite):
 35        """
 36        This function will move the current sprite towards whatever
 37        other sprite is specified as a parameter.
 38
 39        We use the 'min' function here to get the sprite to line up with
 40        the target sprite, and not jump around if the sprite is not off
 41        an exact multiple of SPRITE_SPEED.
 42        """
 43
 44        if self.center_y < player_sprite.center_y:
 45            self.center_y += min(SPRITE_SPEED, player_sprite.center_y - self.center_y)
 46        elif self.center_y > player_sprite.center_y:
 47            self.center_y -= min(SPRITE_SPEED, self.center_y - player_sprite.center_y)
 48
 49        if self.center_x < player_sprite.center_x:
 50            self.center_x += min(SPRITE_SPEED, player_sprite.center_x - self.center_x)
 51        elif self.center_x > player_sprite.center_x:
 52            self.center_x -= min(SPRITE_SPEED, self.center_x - player_sprite.center_x)
 53
 54
 55class MyGame(arcade.Window):
 56    """ Our custom Window Class"""
 57
 58    def __init__(self):
 59        """ Initializer """
 60        # Call the parent class initializer
 61        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
 62
 63        # Set the working directory (where we expect to find files) to the same
 64        # directory this .py file is in. You can leave this out of your own
 65        # code, but it is needed to easily run the examples using "python -m"
 66        # as mentioned at the top of this program.
 67        file_path = os.path.dirname(os.path.abspath(__file__))
 68        os.chdir(file_path)
 69
 70        # Variables that will hold sprite lists
 71        self.player_list = None
 72        self.coin_list = None
 73
 74        # Set up the player info
 75        self.player_sprite = None
 76        self.score = 0
 77
 78        # Don't show the mouse cursor
 79        self.set_mouse_visible(False)
 80
 81        arcade.set_background_color(arcade.color.AMAZON)
 82
 83    def setup(self):
 84        """ Set up the game and initialize the variables. """
 85
 86        # Sprite lists
 87        self.player_list = arcade.SpriteList()
 88        self.coin_list = arcade.SpriteList()
 89
 90        # Score
 91        self.score = 0
 92
 93        # Set up the player
 94        # Character image from kenney.nl
 95        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png", SPRITE_SCALING_PLAYER)
 96        self.player_sprite.center_x = 50
 97        self.player_sprite.center_y = 50
 98        self.player_list.append(self.player_sprite)
 99
100        # Create the coins
101        for i in range(COIN_COUNT):
102            # Create the coin instance
103            # Coin image from kenney.nl
104            coin = Coin(":resources:images/items/coinGold.png", SPRITE_SCALING_COIN)
105
106            # Position the coin
107            coin.center_x = random.randrange(SCREEN_WIDTH)
108            coin.center_y = random.randrange(SCREEN_HEIGHT)
109
110            # Add the coin to the lists
111            self.coin_list.append(coin)
112
113    def on_draw(self):
114        """ Draw everything """
115        arcade.start_render()
116        self.coin_list.draw()
117        self.player_list.draw()
118
119        # Put the text on the screen.
120        output = f"Score: {self.score}"
121        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)
122
123    def on_mouse_motion(self, x, y, dx, dy):
124        """ Handle Mouse Motion """
125
126        # Move the center of the player sprite to match the mouse x, y
127        self.player_sprite.center_x = x
128        self.player_sprite.center_y = y
129
130    def on_update(self, delta_time):
131        """ Movement and game logic """
132
133        for coin in self.coin_list:
134            coin.follow_sprite(self.player_sprite)
135
136        # Generate a list of all sprites that collided with the player.
137        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
138
139        # Loop through each colliding sprite, remove it, and add to the score.
140        for coin in hit_list:
141            coin.remove_from_sprite_lists()
142            self.score += 1
143
144
145def main():
146    """ Main method """
147    window = MyGame()
148    window.setup()
149    arcade.run()
150
151
152if __name__ == "__main__":
153    main()