Aim and Shoot Bullets

Screenshot of using sprites to shoot things
sprite_bullets_aimed.py
  1"""
  2Sprite Bullets
  3
  4Simple program to show basic sprite usage.
  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_bullets_aimed
 10"""
 11
 12import random
 13import arcade
 14import math
 15
 16SPRITE_SCALING_PLAYER = 0.6
 17SPRITE_SCALING_COIN = 0.4
 18SPRITE_SCALING_LASER = 0.8
 19COIN_COUNT = 50
 20
 21WINDOW_WIDTH = 1280
 22WINDOW_HEIGHT = 720
 23WINDOW_TITLE = "Sprites and Bullets Aimed Example"
 24
 25BULLET_SPEED = 5
 26
 27window = None
 28
 29
 30class GameView(arcade.View):
 31    """ Main application class. """
 32
 33    def __init__(self):
 34        """ Initializer """
 35        # Call the parent class initializer
 36        super().__init__()
 37
 38        # Variables that will hold sprite lists
 39        self.player_list = None
 40        self.coin_list = None
 41        self.bullet_list = None
 42
 43        # Set up the player info
 44        self.player_sprite = None
 45        self.score = 0
 46        self.score_text = None
 47
 48        # Load sounds. Sounds from kenney.nl
 49        self.gun_sound = arcade.sound.load_sound(":resources:sounds/laser1.wav")
 50        self.hit_sound = arcade.sound.load_sound(":resources:sounds/phaseJump1.wav")
 51
 52        self.background_color = arcade.color.AMAZON
 53
 54    def setup(self):
 55
 56        """ Set up the game and initialize the variables. """
 57
 58        # Sprite lists
 59        self.player_list = arcade.SpriteList()
 60        self.coin_list = arcade.SpriteList()
 61        self.bullet_list = arcade.SpriteList()
 62
 63        # Set up the player
 64        self.score = 0
 65
 66        # Image from kenney.nl
 67        self.player_sprite = arcade.Sprite(
 68            ":resources:images/animated_characters/female_person/femalePerson_idle.png",
 69            scale=SPRITE_SCALING_PLAYER)
 70        self.player_sprite.center_x = 50
 71        self.player_sprite.center_y = 70
 72        self.player_list.append(self.player_sprite)
 73
 74        # Create the coins
 75        for i in range(COIN_COUNT):
 76
 77            # Create the coin instance
 78            # Coin image from kenney.nl
 79            coin = arcade.Sprite(
 80                ":resources:images/items/coinGold.png",
 81                scale=SPRITE_SCALING_COIN,
 82            )
 83
 84            # Position the coin
 85            coin.center_x = random.randrange(WINDOW_WIDTH)
 86            coin.center_y = random.randrange(120, WINDOW_HEIGHT)
 87
 88            # Add the coin to the lists
 89            self.coin_list.append(coin)
 90
 91        # Set the background color
 92        self.background_color = arcade.color.AMAZON
 93
 94    def on_draw(self):
 95        """ Render the screen. """
 96
 97        # This command has to happen before we start drawing
 98        self.clear()
 99
100        # Draw all the sprites.
101        self.coin_list.draw()
102        self.bullet_list.draw()
103        self.player_list.draw()
104
105        # Put the text on the screen.
106        output = f"Score: {self.score}"
107        arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14)
108
109    def on_mouse_press(self, x, y, button, modifiers):
110        """ Called whenever the mouse button is clicked. """
111
112        # Play the gun sound
113        self.gun_sound.play()
114
115        # Create a bullet
116        bullet = arcade.Sprite(
117            ":resources:images/space_shooter/laserBlue01.png",
118            scale=SPRITE_SCALING_LASER,
119        )
120
121        # Position the bullet at the player's current location
122        start_x = self.player_sprite.center_x
123        start_y = self.player_sprite.center_y
124        bullet.center_x = start_x
125        bullet.center_y = start_y
126
127        # Get from the mouse the destination location for the bullet
128        # IMPORTANT! If you have a scrolling screen, you will also need
129        # to add in self.view_bottom and self.view_left.
130        dest_x = x
131        dest_y = y
132
133        # Do math to calculate how to get the bullet to the destination.
134        # Calculation the angle in radians between the start points
135        # and end points. This is the angle the bullet will travel.
136        x_diff = dest_x - start_x
137        y_diff = dest_y - start_y
138        angle = math.atan2(y_diff, x_diff)
139
140        # Rotate the sprite clockwise to align it with its travel path
141        bullet.angle = - math.degrees(angle)
142        print(f"Bullet angle: {bullet.angle:.2f}")
143
144        # Use the angle to calculate the velocity's change_x and
145        # change_y from speed. Speed is a directionless value, but
146        # the idea of velocity also includes direction.
147        bullet.change_x = math.cos(angle) * BULLET_SPEED
148        bullet.change_y = math.sin(angle) * BULLET_SPEED
149
150        # Add the bullet to the appropriate lists
151        self.bullet_list.append(bullet)
152
153    def on_update(self, delta_time):
154        """ Movement and game logic """
155
156        # Call update on all sprites
157        self.bullet_list.update()
158
159        # Loop through each bullet
160        for bullet in self.bullet_list:
161
162            # Check this bullet to see if it hit a coin
163            hit_list = arcade.check_for_collision_with_list(bullet, self.coin_list)
164
165            # If it did, get rid of the bullet and play the hit sound
166            if len(hit_list) > 0:
167                bullet.remove_from_sprite_lists()
168
169                self.hit_sound.play()
170
171            # For every coin we hit, add to the score and remove the coin
172            for coin in hit_list:
173                coin.remove_from_sprite_lists()
174                self.score += 1
175
176            # If the bullet flies off-screen, remove it.
177            if (bullet.bottom > self.width or
178                bullet.top < 0 or
179                bullet.right < 0 or
180                bullet.left > self.width
181            ):
182                bullet.remove_from_sprite_lists()
183
184
185def main():
186    """ Main function """
187    # Create a window class. This is what actually shows up on screen
188    window = arcade.Window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)
189
190    # Create and setup the GameView
191    game = GameView()
192    game.setup()
193
194    # Show GameView on screen
195    window.show_view(game)
196
197    # Start the arcade game loop
198    arcade.run()
199
200
201if __name__ == "__main__":
202    main()