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