Project 1 of Python 13: alien invasion game 04 (reconstruct check Hou event() and make the spacecraft launch bullets)

In order to modularize and structure the code, we reconstruct the key response in the check event() function into two functions: check keydown() [response key] and check keyup() [response release].

The code after refactoring is as follows: (this code is part of the code in this section, the whole code will be later, just have a look at this code)

# Response key 03
def check_keydown(event, ai_settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        # Move the ship to the right
        ship.moving_right = True
        # ship.rect.centerx += 10
    elif event.key == pygame.K_LEFT:
        # Move the ship to the left
        # ship.rect.centerx -= 10
        ship.moving_left = True


# Response release 03
def check_keyup(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


# Respond to key and mouse events
def check_event(ai_setting, screen, ship, bullets):  # 03

    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            sys.exit()

        elif i.type == pygame.KEYDOWN:
            check_keydown(i, ai_setting, screen, ship, bullets) # Restructure
        # 03   if i.key == pygame.K_RIGHT:
        # 03        # Move the ship to the right
        # 03        ship.moving_right = True
        # 03        # ship.rect.centerx += 10
        # 03    elif i.key == pygame.K_LEFT:
        # 03        # Move the ship to the left
        # 03        # ship.rect.centerx -= 10
        # 03        ship.moving_left = True

        elif i.type == pygame.KEYUP:
            check_keyup(i, ship)  # Restructure
            # 03 if i.key == pygame.K_RIGHT:
            # 03    ship.moving_right = False
            # 03 elif i.key == pygame.K_LEFT:
            # 03    ship.moving_left = False

Then the next step is to add more bullets. For adding bullets, we need to add the attributes of bullets in the settings.py file first. Then, write a bullet.py file, save the Bullet class, to create a Bullet's rect object, and let the Bullet draw from the screen. The specific documents are as follows:

The code of bullet.py is as follows:

import pygame
from pygame.sprite import Sprite        # import wizard

# A class that manages the bullets fired by a spaceship
class Bullet(Sprite):
    def __init__(self,ai_setting,screen,ship):
        # Create a bullet object where the ship is located
        super().__init__()    # Initialize the super (bullet, self) of the parent class 2.7
        self.screen = screen

        # Create a rectangle representing the bullet at (0, 0) and set the correct position
        # We created the bullet's attribute rect. The bullet is not image-based, so we have to use the pygame.Rect() class to create a rectangle starting with white space
        # We create the rectangle at (0, 0), but the next two lines of code move it to the right place
        self.rect = pygame.Rect(0,0,ai_setting.bullet_width,ai_setting.bullet_height)
        # We set the centerx of the bullet to rect.centerx of the spacecraft.
        # The bullet should shoot from the top of the spacecraft, so we set the top attribute of rect that represents the bullet to the top attribute of rect of the spacecraft,
        # To make the bullets look like they were fired from a spaceship
        self.rect.centerx = ship.rect.centerx
        self.rect.top = ship.rect.top

        # Store bullet position in decimal
        self.y = float(self.rect.y)

        self.color = ai_setting.bullet_color
        self.speed = ai_setting.bullet_speed_factor

    # Move the bullet up
    def update(self, *args):
        # Update the small value indicating the bullet position
        self.y -= self.speed
        # Update the position of the rect that represents the bullet position
        self.rect.y = self.y

    # Draw bullets on the screen
    def draw_bullet(self):
        # The draw.rect() function fills the screen portion occupied by the rect representing the bullet with the color stored in self.color
        pygame.draw.rect(self.screen,self.color,self.rect)

Then attach the updated additional. py file code.

Those marked with 03 are all about updating!!!

settings.py

class Setting():            # Store all settings in alien invasion
    def __init__(self):     # Initialize game settings
        self.screen_width = 1200        # screen setting
        self.screen_height = 800
        self.bg_color = (230,230,230)

        self.ship_speed_factor = 1.5    # 02 set airship speed

        # 03 set up bullets
        self.bullet_speed_factor = 1    # Bullet speed
        self.bullet_width = 3           # Bullet width
        self.bullet_height = 15         # Bullet length
        self.bullet_color = 60,60,60    # Bullet color
        self.bullet_allowed = 3         #Limit the number of bullets to 3

game_funtion.py

import sys
import pygame
from alien.bullet import Bullet  # 03


# Response key 03
def check_keydown(event, ai_settings, screen, ship, bullets):
    if event.key == pygame.K_RIGHT:
        # Move the ship to the right
        ship.moving_right = True
        # ship.rect.centerx += 10
    elif event.key == pygame.K_LEFT:
        # Move the ship to the left
        # ship.rect.centerx -= 10
        ship.moving_left = True
    # 03 create a bullet and add it to the group bullets
    elif event.key == pygame.K_SPACE:
        if len(bullets) < ai_settings.bullet_allowed:   # Limit three bullets
            # When players press the space bar, they create a new Bullet (a Bullet instance named new_bullet),
            new_bullet = Bullet(ai_settings, screen, ship)
            # And add it to the group bullets using the method add()
            bullets.add(new_bullet)


# Response release 03
def check_keyup(event, ship):
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False


# Respond to key and mouse events
def check_event(ai_setting, screen, ship, bullets):  # 03

    for i in pygame.event.get():
        if i.type == pygame.QUIT:
            sys.exit()

        elif i.type == pygame.KEYDOWN:
            check_keydown(i, ai_setting, screen, ship, bullets) # Restructure
        # 03   if i.key == pygame.K_RIGHT:
        # 03        # Move the ship to the right
        # 03        ship.moving_right = True
        # 03        # ship.rect.centerx += 10
        # 03    elif i.key == pygame.K_LEFT:
        # 03        # Move the ship to the left
        # 03        # ship.rect.centerx -= 10
        # 03        ship.moving_left = True

        elif i.type == pygame.KEYUP:
            check_keyup(i, ship)  # Restructure
            # 03 if i.key == pygame.K_RIGHT:
            # 03    ship.moving_right = False
            # 03 elif i.key == pygame.K_LEFT:
            # 03    ship.moving_left = False

def update_screen(ai_setting, screen, ship, bullets):  # Update the image on the screen and switch to the new screen
    # Redraw the screen every time you cycle
    screen.fill(ai_setting.bg_color)
    # 03 redraw all the bullets behind the spaceship and the alien
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()
    # Make the most recently drawn screen visible
    pygame.display.flip()

# 03 update bullet position and delete bullets that have disappeared
def update_bullet(bullets):
    bullets.update()        # Update bullet position

    # 03 delete bullets that have disappeared
    for bull in bullets.copy():
        if bull.rect.bottom <= 0:
            bullets.remove(bull)
    print(len(bullets))

alien_invasion.py

# 02 import sys
import pygame
from alien.settings import Setting      # 01
from alien.ship import Ship             # 01
import alien.game_function as gf        # 02
from pygame.sprite import Group         # 03 the pygame.sprite.group class is similar to a list, but provides additional features to help develop the game


def run_game():          # Initialize the game and create a screen object
    pygame.init()        # Initialize background settings so Pygame works correctly
    # 01 screen = pygame.display.set_mode((1200, 800))     # Create a display window called screen with tuples in brackets!!!
    # 01                                                   # All graphic elements of the game will be drawn in it
    ai_set = Setting()                                     # Code replacement due to import class
    screen = pygame.display.set_mode(
        (ai_set.screen_width,ai_set.screen_height)
    )
    # 01 bg_color = (230,230,230)         # Set background color

    pygame.display.set_caption('Alien invasion')
    # Create a spaceship object
    ship = Ship(ai_set,screen)
    # 03 import the Group class and create a Group instance to store bullet groups
    bullets = Group()

    # In order for the program to respond to events, we write an event loop to listen for events and perform corresponding tasks according to the events.
    while True:  # The main cycle of the game
        # 02 for event in pygame.event.get():    # Monitor keyboard and mouse
        # 02     if event.type == pygame.QUIT:   #Write a series of if statements to detect and respond to specific events
        # 02         sys.exit()                  # We call sys.exit() to exit the game
        gf.check_event(ai_set,screen,ship,bullets)    # 02 03
        ship.update()           # 02

        gf.update_bullet(bullets)      # 03
        # 03 bullets.update()   # 03
        # # 03 delete bullets that have disappeared
        # for bull in bullets.copy():
        #     if bull.rect.bottom <= 0:
        #         bullets.remove(bull)
        # print(len(bullets))

        # 01screen.fill(bg_color)                # Redraw screen every cycle
        # 02 screen.fill(ai_set.bg_color)
        # 02 ship.blitme()                       # Call blitme function to make the spaceship appear
        # 02 pygame.display.flip()               # Make the most recently drawn screen visible

        gf.update_screen(ai_set,screen,ship,bullets)     # 02 03

run_game()

 

Tags: Attribute

Posted on Fri, 31 Jan 2020 11:45:16 -0500 by djkanebo