为什么重启后游戏无法重置?

时间:2019-01-29 07:34:35

标签: python-3.x

您可以在第56行看到我的game_functions.py。它说“ stats.reset_stats”对吗?但是游戏开始时并未重置比分。怎么会发生?(代码很长,但是请耐心等待。)

我正在遵循《 Python Crash Course》这本书的第14章。我将其与源代码进行了比较。除了提交和之后的内容之外,我没有发现其他不同之处。

alien_invasion.py

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf
from pygame.sprite import Group
from game_stats import GameStats
from button import Button
from scoreboard import Scoreboard

def run_game():
    #create the game
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    #create a ship
    ship = Ship(ai_settings, screen)

    #create the bullets
    bullets = Group()

    #create the Aliens
    aliens = Group()

    #create alien Group
    gf.create_fleet(ai_settings, screen,ship , aliens)

    #Create a instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    #Make the Play button.
    play_button = Button(ai_settings, screen, "Play")

    #Start the main loop for the game.
    while True:
        gf.check_events(ai_settings ,screen, stats,play_button,ship,aliens,
                        bullets)
        if stats.game_activate == True:
            ship.update()
            bullets.update()
            gf.update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets)
            gf.update_aliens(ai_settings,stats,screen,ship,aliens,bullets)
        gf.update_screen(ai_settings,screen,stats, sb,ship,aliens , bullets,
                         play_button)

run_game()

settings.py

class Settings():
    """Store all the settings in Alien Invasion"""

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

        #Ship settings
        self.ship_limit = 3

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

        #Alien settings
        self.fleet_drop_speed = 10
        self.fleet_direction = 1

        #How quickly the alien value increase.
        self.score_scale = 1.5

        #How quickly the game speeds up
        self.speedup_scale = 1.1

        self.initialize_dynamic_settings()

    def initialize_dynamic_settings(self):
        """Initialize settings that change throughout the game."""
        self.ship_speed_factor = 1.5
        self.bullet_speed_factor = 3
        self.alien_speed_factor = 1

        #fleet direction of 1 represents right; -1 represents left.
        self.fleet_direction = 1

        #Scoring
        self.alien_points = 50
    def increase_speed(self):
        """Increase speed settings and alien point values."""
        self.ship_speed_factor *= self.speedup_scale
        self.bullet_speed_factor *= self.speedup_scale
        self.alien_speed_factor *= self.speedup_scale
        self.alien_points = int(self.alien_points * self.score_scale)

game_functions.py

import sys
import pygame
from bullet import Bullet
from alien import Alien
from time import sleep

def check_keydown_events(event ,stats,ai_settings ,screen, ship, bullets):
    """Respond to key presses."""
    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)
    elif event.key == pygame.K_q:
        sys.exit()
    elif event.key == pygame.K_p:
        stats.game_activate = True

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, stats,play_button,ship,aliens, bullets):
    """Respond to key presses 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,stats,ai_settings,screen, ship,bullets)

        elif event.type == pygame.KEYUP:
            check_keyup_events(event, ship)

        elif event.type == pygame.MOUSEBUTTONDOWN:
            mouse_x,mouse_y = pygame.mouse.get_pos()
            check_play_button(ai_settings,screen, stats, play_button, ship,
                              aliens,bullets, mouse_x, mouse_y)

def check_play_button(ai_settings, screen, stats ,play_button, ship, aliens,
                      bullets, mouse_x, mouse_y):
    """Start a new game when the player clicks Play"""
    button_clicked = play_button.rect.collidepoint(mouse_x,mouse_y)
    if button_clicked and not stats.game_activate:
        #Reset the game settings.
        ai_settings.initialize_dynamic_settings()

        #Hide the mouse cursor.
        pygame.mouse.set_visible(False)

        #Reset the game statistics
        stats.reset_stats()
        stats.game_activate = True

        #Empty the list of aliens and bullets.
        aliens.empty()
        bullets.empty()

        #Create a new fleet and center the ship.
        create_fleet(ai_settings, screen, ship, aliens)
        ship.center_ship()

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

    ship.blitme()
    aliens.draw(screen)

    #Draw the score information.
    sb.show_score()
    #Draw the play_button if the game is inactivate.
    if not stats.game_activate:
        play_button.draw_button()
    #make the current surface visible
    pygame.display.flip()

def update_bullets(ai_settings,screen,stats,sb,ship,aliens,bullets):
    """update the position of the bullet and delete invisible bullets"""
    bullets.update()
    #delete invisible bullets
    for bullet in bullets.copy():
        if bullet.rect.bottom <= 0:
            bullets.remove(bullet)
    check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,
                                  bullets)

def check_bullet_alien_collisions(ai_settings,screen,stats,sb,ship,aliens,
                                  bullets):
    """check bullet alien collisions"""
    collisions = pygame.sprite.groupcollide(bullets,aliens, True , True)
    if collisions:
        for aliens in collisions.values():
            stats.score += ai_settings.alien_points * len(aliens)
            sb.prep_score()

    if len(aliens) == 0:
        #Destroy existing bullets, speed up game, and create new fleet.
        bullets.empty()
        ai_settings.increase_speed()
        create_fleet(ai_settings,screen,ship,aliens)

def fire_bullet(ai_settings, screen, ship, bullets):
    """if it doesn't touch the limit ,shoot a bullet"""
    #create a bullet and join it to group 'bullets'
    if len(bullets) < ai_settings.bullets_allowed:
        new_bullet = Bullet(ai_settings, screen, ship)
        bullets.add(new_bullet)

def get_aliens_x(ai_settings, alien_width):
    """calculate how many aliens can be included in one line"""
    available_space_x = ai_settings.screen_width - 2 * alien_width
    number_aliens_x = int(available_space_x / (2*alien_width))
    return number_aliens_x

def get_number_rows(ai_settings, ship_height, alien_height):
    """calculate how many lines can be included on the screen"""
    available_space_y = (ai_settings.screen_height - (3 * alien_height) -
                         ship_height)
    number_rows = int(available_space_y / (2 * alien_height))
    return number_rows

def create_alien(ai_settings, screen, aliens, alien_number, row_number):
    """create an alien and put it in the current line"""
    alien = Alien(ai_settings, screen)
    alien_width = alien.rect.width
    alien.x = alien_width + 2 * alien_width * alien_number
    alien.rect.x = alien.x
    alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
    aliens.add(alien)

def create_fleet(ai_settings, screen,ship , aliens):
    """create alien group """
    alien = Alien(ai_settings, screen)
    number_aliens_x = get_aliens_x(ai_settings, alien.rect.width)
    number_rows = get_number_rows(ai_settings, ship.rect.height,
                                  alien.rect.height)

    #create alien group
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            create_alien(ai_settings, screen, aliens, alien_number, row_number)

def check_fleet_edges(ai_settings, aliens):
    """if aliens touch edge then ... """
    for alien in aliens.sprites():
        if alien.check_edges():
            change_fleet_direction(ai_settings, aliens)
            break

def change_fleet_direction(ai_settings, aliens):
    """move the aliens down and change their direction"""
    for alien in aliens.sprites():
        alien.rect.y += ai_settings.fleet_drop_speed

    ai_settings.fleet_direction *= -1

def ship_hit(ai_settings,stats,screen,ship,aliens,bullets):
    """respond the ship that are hit"""
    if stats.ships_left > 0:
        #change ships_left by -1
        stats.ships_left -= 1

    else:
        stats.game_activate = False
        pygame.mouse.set_visible(True)

    #clear Alien group and Bullet group
    aliens.empty()
    bullets.empty()

    #create a new group of alien, and put the ship BOTTOM-MIDDLE.
    create_fleet(ai_settings, screen, ship, aliens)
    ship.center_ship()

    #pause
    sleep(0.5)

def check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets):
    """check if any aliens touches the edge"""
    screen_rect = screen.get_rect()
    for alien in aliens.sprites():
        if alien.rect.bottom > screen_rect.bottom:
            #do as ship-alien collisions
            ship_hit(ai_settings,stats,screen,ship,aliens,bullets)
            break

def update_aliens(ai_settings,stats,screen,ship,aliens,bullets):
    """update the position of alien groups """
    check_fleet_edges(ai_settings, aliens)
    aliens.update()

    #check alien-ship collisions
    if pygame.sprite.spritecollideany(ship, aliens):
        ship_hit(ai_settings,stats,screen,ship,aliens,bullets)
    check_aliens_bottom(ai_settings, stats, screen, ship, aliens, bullets)

scoreboard.py

import pygame.font

class Scoreboard():
    """A class to report scoring information."""
    def __init__(self, ai_settings, screen, stats):
        """Initialize scorekeeping attributes."""
        self.screen = screen
        self.screen_rect = screen.get_rect()
        self.ai_settings = ai_settings
        self.stats = stats

        #Font settings for scoring information.
        self.text_color = (30,30,30)
        self.font = pygame.font.SysFont(None, 48)

        #Prepare the inital score image.
        self.prep_score()

    def prep_score(self):
        """Turn the score into a rendered image."""
        rounded_score = int(round(self.stats.score, -1))
        score_str = "{:,}".format(rounded_score)
        self.score_image = self.font.render(score_str,True, self.text_color,
                                            self.ai_settings.bg_color)

        #Display the score at the top right of the screen.
        self.score_rect = self.score_image.get_rect()
        self.score_rect.right = self.screen_rect.right - 20
        self.score_rect.top = 20

    def show_score(self):
        """Draw score to the screen."""
        self.screen.blit(self.score_image, self.score_rect)

game_stats.py

class GameStats():
    """Track statistics for Alien Invasion."""
    def __init__(self, ai_settings):
        """Initialize statistics"""
        self.ai_settings = ai_settings
        self.reset_stats()

        #Start game in an inactivate state
        self.game_activate = False

    def reset_stats(self):
        """initialize changeable statistics during the game"""
        self.ships_left = self.ai_settings.ship_limit
        self.score = 0

0 个答案:

没有答案
相关问题