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