Sprites That Follow The Player 2

Screen shot of using sprites to collect coins
sprite_follow_simple_2.py
  1"""
  2Sprite Follow Player 2
  3
  4This calculates a 'vector' towards the player and randomly updates it based
  5on the player's location. This is a bit more complex, but more interesting
  6way of following the player.
  7
  8Artwork from https://kenney.nl
  9
 10If Python and Arcade are installed, this example can be run from the command line with:
 11python -m arcade.examples.sprite_follow_simple_2
 12"""
 13
 14import random
 15import arcade
 16import math
 17
 18# --- Constants ---
 19SPRITE_SCALING_PLAYER = 0.5
 20SPRITE_SCALING_COIN = 0.2
 21COIN_COUNT = 5
 22COIN_SPEED = 0.5
 23
 24SCREEN_WIDTH = 800
 25SCREEN_HEIGHT = 600
 26SCREEN_TITLE = "Sprite Follow Player Simple Example 2"
 27
 28SPRITE_SPEED = 0.5
 29
 30
 31class Coin(arcade.Sprite):
 32    """
 33    This class represents the coins on our screen. It is a child class of
 34    the arcade library's "Sprite" class.
 35    """
 36
 37    def follow_sprite(self, player_sprite):
 38        """
 39        This function will move the current sprite towards whatever
 40        other sprite is specified as a parameter.
 41
 42        We use the 'min' function here to get the sprite to line up with
 43        the target sprite, and not jump around if the sprite is not off
 44        an exact multiple of SPRITE_SPEED.
 45        """
 46
 47        self.center_x += self.change_x
 48        self.center_y += self.change_y
 49
 50        # Random 1 in 100 chance that we'll change from our old direction and
 51        # then re-aim toward the player
 52        if random.randrange(100) == 0:
 53            start_x = self.center_x
 54            start_y = self.center_y
 55
 56            # Get the destination location for the bullet
 57            dest_x = player_sprite.center_x
 58            dest_y = player_sprite.center_y
 59
 60            # Do math to calculate how to get the bullet to the destination.
 61            # Calculation the angle in radians between the start points
 62            # and end points. This is the angle the bullet will travel.
 63            x_diff = dest_x - start_x
 64            y_diff = dest_y - start_y
 65            angle = math.atan2(y_diff, x_diff)
 66
 67            # Taking into account the angle, calculate our change_x
 68            # and change_y. Velocity is how fast the bullet travels.
 69            self.change_x = math.cos(angle) * COIN_SPEED
 70            self.change_y = math.sin(angle) * COIN_SPEED
 71
 72
 73class MyGame(arcade.Window):
 74    """ Our custom Window Class"""
 75
 76    def __init__(self):
 77        """ Initializer """
 78        # Call the parent class initializer
 79        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
 80
 81        # Variables that will hold sprite lists
 82        self.player_list = None
 83        self.coin_list = None
 84
 85        # Set up the player info
 86        self.player_sprite = None
 87        self.score = 0
 88
 89        # Don't show the mouse cursor
 90        self.set_mouse_visible(False)
 91
 92        self.background_color = arcade.color.AMAZON
 93
 94    def setup(self):
 95        """ Set up the game and initialize the variables. """
 96
 97        # Sprite lists
 98        self.player_list = arcade.SpriteList()
 99        self.coin_list = arcade.SpriteList()
100
101        # Score
102        self.score = 0
103
104        # Set up the player
105        # Character image from kenney.nl
106        self.player_sprite = arcade.Sprite(":resources:images/animated_characters/female_person/femalePerson_idle.png",
107                                           scale=SPRITE_SCALING_PLAYER)
108        self.player_sprite.center_x = 50
109        self.player_sprite.center_y = 50
110        self.player_list.append(self.player_sprite)
111
112        # Create the coins
113        for i in range(COIN_COUNT):
114            # Create the coin instance
115            # Coin image from kenney.nl
116            coin = Coin(":resources:images/items/coinGold.png", scale=SPRITE_SCALING_COIN)
117
118            # Position the coin
119            coin.center_x = random.randrange(SCREEN_WIDTH)
120            coin.center_y = random.randrange(SCREEN_HEIGHT)
121
122            # Add the coin to the lists
123            self.coin_list.append(coin)
124
125    def on_draw(self):
126        """ Draw everything """
127        self.clear()
128        self.coin_list.draw()
129        self.player_list.draw()
130
131        # Put the text on the screen.
132        output = f"Score: {self.score}"
133        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)
134
135    def on_mouse_motion(self, x, y, dx, dy):
136        """ Handle Mouse Motion """
137
138        # Move the center of the player sprite to match the mouse x, y
139        self.player_sprite.center_x = x
140        self.player_sprite.center_y = y
141
142    def on_update(self, delta_time):
143        """ Movement and game logic """
144
145        for coin in self.coin_list:
146            coin.follow_sprite(self.player_sprite)
147
148        # Generate a list of all sprites that collided with the player.
149        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
150
151        # Loop through each colliding sprite, remove it, and add to the score.
152        for coin in hit_list:
153            coin.kill()
154            self.score += 1
155
156
157def main():
158    """ Main function """
159    window = MyGame()
160    window.setup()
161    arcade.run()
162
163
164if __name__ == "__main__":
165    main()