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