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        # Create a bullet
113        bullet = arcade.Sprite(
114            ":resources:images/space_shooter/laserBlue01.png",
115            scale=SPRITE_SCALING_LASER,
116        )
117
118        # Position the bullet at the player's current location
119        start_x = self.player_sprite.center_x
120        start_y = self.player_sprite.center_y
121        bullet.center_x = start_x
122        bullet.center_y = start_y
123
124        # Get from the mouse the destination location for the bullet
125        # IMPORTANT! If you have a scrolling screen, you will also need
126        # to add in self.view_bottom and self.view_left.
127        dest_x = x
128        dest_y = y
129
130        # Do math to calculate how to get the bullet to the destination.
131        # Calculation the angle in radians between the start points
132        # and end points. This is the angle the bullet will travel.
133        x_diff = dest_x - start_x
134        y_diff = dest_y - start_y
135        angle = math.atan2(y_diff, x_diff)
136
137        # Rotate the sprite clockwise to align it with its travel path
138        bullet.angle = - math.degrees(angle)
139        print(f"Bullet angle: {bullet.angle:.2f}")
140
141        # Use the angle to calculate the velocity's change_x and
142        # change_y from speed. Speed is a directionless value, but
143        # the idea of velocity also includes direction.
144        bullet.change_x = math.cos(angle) * BULLET_SPEED
145        bullet.change_y = math.sin(angle) * BULLET_SPEED
146
147        # Add the bullet to the appropriate lists
148        self.bullet_list.append(bullet)
149
150    def on_update(self, delta_time):
151        """ Movement and game logic """
152
153        # Call update on all sprites
154        self.bullet_list.update()
155
156        # Loop through each bullet
157        for bullet in self.bullet_list:
158
159            # Check this bullet to see if it hit a coin
160            hit_list = arcade.check_for_collision_with_list(bullet, self.coin_list)
161
162            # If it did, get rid of the bullet
163            if len(hit_list) > 0:
164                bullet.remove_from_sprite_lists()
165
166            # For every coin we hit, add to the score and remove the coin
167            for coin in hit_list:
168                coin.remove_from_sprite_lists()
169                self.score += 1
170
171            # If the bullet flies off-screen, remove it.
172            if (bullet.bottom > self.width or
173                bullet.top < 0 or
174                bullet.right < 0 or
175                bullet.left > self.width
176            ):
177                bullet.remove_from_sprite_lists()
178
179
180def main():
181    """ Main function """
182    # Create a window class. This is what actually shows up on screen
183    window = arcade.Window(WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_TITLE)
184
185    # Create and setup the GameView
186    game = GameView()
187    game.setup()
188
189    # Show GameView on screen
190    window.show_view(game)
191
192    # Start the arcade game loop
193    arcade.run()
194
195
196if __name__ == "__main__":
197    main()