12-5。 Sideways Shooter - Python速成课程

时间:2018-04-08 15:08:48

标签: python pygame

如何更改现有代码,使船不在屏幕底部,而是放在屏幕左侧,同时仍允许玩家上下移动船只。船仍然需要能够发射,但子弹需要穿过屏幕而不是向上,因为船不再在屏幕的底部。此外,我需要确保一旦子弹从屏幕上消失就删除它们。这是我的代码。

Alien Invasion 5.py     导入pygame

from pygame.sprite import Group
from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

  # Make a ship.
    ship = Ship(ai_settings, screen)
  # Make a group to store bullets in.
    bullets = Group()

    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullets(bullets)
        gf.update_screen(ai_settings, screen, ship, bullets)

run_game()

game_functions.py

import sys

import pygame
from bullet import Bullet

def check_keydown_events(event, ai_settings, screen, ship, bullets):
    """Respond to keypresses."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = True
    elif event.key == pygame.K_LEFT:
        ship.moving_left = True
    elif event.key == pygame.K_SPACE:
    fire_bullet(ai_settings, screen, ship, bullets)


def fire_bullet(ai_settings, screen, ship, bullets):
    """Fire a bullet if limit not reached yet."""
    # Create a new bullet and add it to the bullets group.
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet) 


def check_keyup_events(event, ship):
    """Respond to key releases."""
    if event.key == pygame.K_RIGHT:
        ship.moving_right = False
    elif event.key == pygame.K_LEFT:
        ship.moving_left = False                

def check_events(ai_settings, screen, ship, bullets):
    """Respond to keypresses and mouse events."""
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, ship, bullets)
        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

def update_screen(ai_settings, screen, ship, bullets):
    """Update images on the screen and flip to the new screen."""
    # Redraw the screen during each pass through the loop.
    screen.fill(ai_settings.bg_color)
    # Redraw all bullets behind the ship and aliens.
    for bullet in bullets.sprites():
        bullet.draw_bullet()
    ship.blitme()

def update_bullets(bullets):
    """Update position of bullets and get rid of old bullets."""
    # Update bullet positions.
    bullets.update()

    # Get rid of bullets that have disappeared.
    for bullet in bullets.copy():
        if bullet.rect.bottom <=0:
            bullets.remove(bullet)  

    # Make the most recently drawn screen visible.
    pygame.display.flip()           

settings.py

类设置():     msgstr“”“用于存储Alien Invasion的所有设置的类。”“”

def __init__(self):
    """Initialize the game's settings."""
    # Screen settings
    self.screen_width = 1200
    self.screen_height = 800
    self.bg_color = (230,230,230)

    # Ship settings
    self.ship_speed_factor = 1.5

    # Bullet settings
    self.bullet_speed_factor = 1
    self.bullet_width = 3
    self.bullet_height = 15
    self.bullet_color = 60,60,60
    self.bullets_allowed = 3

bullet.py

导入pygame 来自pygame.sprite导入精灵

class Bullet(精灵):     “”用于管理从他发射的子弹射击的类“”

def __init__(self, ai_settings, screen, ship):
    """Create a bullet object at the ship's current position."""
    super(Bullet, self).__init__()
    self.screen = screen

    # Create a bullet rect at (0,0) and then set correct position.
    self.rect = pygame.Rect(0,0, ai_settings.bullet_width,
        ai_settings.bullet_height)
    self.rect.centerx = ship.rect.centerx
    self.rect.top = ship.rect.top

    # Store the bullet's position as a decimal value.
    self.y = float(self.rect.y)

    self.color = ai_settings.bullet_color
    self.speed_factor = ai_settings.bullet_speed_factor

def update(self):
    """Move the bullet up the screen."""
    # Update the decimal position of the bullet.
    self.y -= self.speed_factor
    # Update the rect position.
    self.rect.y = self.y

def draw_bullet(self):
    """Draw the bullet to the screen."""
    pygame.draw.rect(self.screen, self.color, self.rect)            

2 个答案:

答案 0 :(得分:0)

def update_bullets(bullets):
    """Update position of bullets and get rid of old bullets."""
    # Update bullet positions.
    bullets.update()

    # Get rid of bullets that have disappeared.
    for bullet in bullets.copy():
        if bullet.rect.bottom <=0:
            bullets.remove(bullet)  

您将必须插入另一个参数ai_settings,以确保当子弹穿过屏幕宽度时将其删除。 试试这个,它应该可以工作:

def update_bullets(bullets,ai_settings):

    """Update the position of bullets and get rid of the old bullets."""
    #Update bullet positions.
    bullets.update()
    ai_settings = Settings()

    #Get rid of bullets that have disappeared.

    for bullet in bullets.copy():
        if bullet.rect.x >ai_settings.screen_width:
            bullets.remove(bullet)

答案 1 :(得分:0)

我相信以下内容可以更好地说明用于“ Python速成课程”问题12-5的项目符号类。

import pygame

# The name used to create the .py where settings are stored 

from problem123settings import Settings   

ai_settings = Settings()

# Allow the grouping of related elements of the game and act on all the 
# grouped elements of the game at once with Sprite.

from pygame.sprite import Sprite

class Bullet(Sprite):
    """A class to manage bullets fired from the ship."""

    def __init__(self, ai_settings, screen, ship):
        """Create a bullet object at the ship's current position."""

        # Super is called to inherit properly from Sprite.
        super().__init__()

        self.screen = screen

        # Create a bullet rect at  (0, 0) [x and y coordinates at the top left
        # corner of the screen] and then set the correct position.

        self.rect = pygame.Rect(0, 0, ai_settings.bullet_width,
        ai_settings.bullet_height)

        # Set bullet's centerx at the center of the ship.

        self.rect.centerx = ship.rect.centerx

        # Set the bullet height at the center of the ship, therefore
        # making it appear that the bullet comes from the front of the ship.

        self.rect.center = ship.rect.center

        # Store the bullet's position as a decimal value.

        self.x = float(self.rect.x)

        self.color = ai_settings.bullet_color
        self.speed_factor = ai_settings.bullet_speed_factor


    def update(self):       
        """Move the bullet across the screen."""

        '''
        The update() method manages the bullets position.  When a bullet is 
        fired, it moves across the screen, which corresponds to an increasing
        x-coordinate value; so to update the position, we add the amount 
        stored in self.speed_factor to self.x.  We then use the value of
        self.x to set the value of self.rect.x.  Once fired the bullets
        y-coordinate value never changes.

        ''' 
        self.x += self.speed_factor


        # Update the rect position of the bullet.

        self.rect.x = self.x


    def draw_bullet(self):
        """Draw the bullet to the screen."""

        pygame.draw.rect(self.screen, self.color, self.rect)