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
 24WINDOW_WIDTH = 1280
 25WINDOW_HEIGHT = 720
 26WINDOW_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 GameView(arcade.View):
 74    """ Our custom Window Class"""
 75
 76    def __init__(self):
 77        """ Initializer """
 78        # Call the parent class initializer
 79        super().__init__()
 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.window.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(
107            ":resources:images/animated_characters/female_person/femalePerson_idle.png",
108            scale=SPRITE_SCALING_PLAYER,
109        )
110        self.player_sprite.center_x = 50
111        self.player_sprite.center_y = 50
112        self.player_list.append(self.player_sprite)
113
114        # Create the coins
115        for i in range(COIN_COUNT):
116            # Create the coin instance
117            # Coin image from kenney.nl
118            coin = Coin(":resources:images/items/coinGold.png", scale=SPRITE_SCALING_COIN)
119
120            # Position the coin
121            coin.center_x = random.randrange(WINDOW_WIDTH)
122            coin.center_y = random.randrange(WINDOW_HEIGHT)
123
124            # Add the coin to the lists
125            self.coin_list.append(coin)
126
127    def on_draw(self):
128        """ Draw everything """
129        self.clear()
130        self.coin_list.draw()
131        self.player_list.draw()
132
133        # Put the text on the screen.
134        output = f"Score: {self.score}"
135        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)
136
137    def on_mouse_motion(self, x, y, dx, dy):
138        """ Handle Mouse Motion """
139
140        # Move the center of the player sprite to match the mouse x, y
141        self.player_sprite.center_x = x
142        self.player_sprite.center_y = y
143
144    def on_update(self, delta_time):
145        """ Movement and game logic """
146
147        for coin in self.coin_list:
148            coin.follow_sprite(self.player_sprite)
149
150        # Generate a list of all sprites that collided with the player.
151        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
152
153        # Loop through each colliding sprite, remove it, and add to the score.
154        for coin in hit_list:
155            coin.kill()
156            self.score += 1
157
158
159def main():
160    """ Main function """
161    # Create a window class. This is what actually shows up on screen
162    window = arcade.Window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)
163
164    # Create and setup the GameView
165    game = GameView()
166    game.setup()
167
168    # Show GameView on screen
169    window.show_view(game)
170
171    # Start the arcade game loop
172    arcade.run()
173
174
175if __name__ == "__main__":
176    main()