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