python从入门到实践课后习题13-3,13-4

 

import pygame
import sys
from pygame.sprite import Group

class Rain(pygame.sprite.Sprite):
    def __init__(self, screen_height):
        super().__init__()
        self.image = pygame.image.load('images/rain.jpg')
        self.rect = self.image.get_rect()
        self.screen_height = screen_height
        self.speed = 1
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.y = float(self.rect.y)

    def check_edges(self):
        if self.rect.top >= self.screen_height:
            return True

    def update(self):
        self.rect.y += self.speed

def create_rain(rains, number_rain, number_row, screen_height):
    rain = Rain(screen_height)
    rain.rect.x = rain.rect.width + 2 * rain.rect.width * number_rain
    rain.rect.y = rain.rect.height + 2 * rain.rect.height * number_row
    rains.add(rain)

def create_initial_rain(rains, screen_width, screen_height):
    rain = Rain(screen_height)
    numbers_rain = get_numbers_rain(screen_width, rain.rect.width)
    numbers_row = get_numbers_row(screen_height, rain.rect.height)

    for number_row in range(numbers_row):
        for number_rain in range(numbers_rain):
            create_rain(rains, number_rain, number_row, screen_height)


def create_new_rains(rains, screen_width, screen_height):
    rain = Rain(screen_height)
    availabel_space_x = screen_width - rain.rect.width
    numbers_rain = int(availabel_space_x / rain.rect.width)
    for number_rain in range(numbers_rain):
        create_rain(rains, number_rain, 0, screen_height)

def get_numbers_rain(screen_width, rain_width):
    availabel_space_x = screen_width - rain_width
    numbers_rain = int(availabel_space_x / rain_width)
    return numbers_rain

def get_numbers_row(screen_height, rain_height):
    availabel_space_y = screen_height - rain_height
    numbers_row = int(availabel_space_y / rain_height)
    return numbers_row

def show_screen():
    pygame.init()
    screen = pygame.display.set_mode((1960, 1080))

    screen.fill((255, 255, 255))

    rains = Group()

    create_initial_rain(rains, 1960, 1080)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    sys.exit()

        for rain in rains:
            if rain.check_edges():
                create_new_rains(rains, 1960, 1080)
                # print(rain.rect.width, rain.rect.height)
                break

        for rain in rains:
            if rain.check_edges():
                rains.remove(rain)

        rains.update()
        rains.draw(screen)
        pygame.display.flip()

show_screen()
可以实现题目的要求,但是存在一个小bug,在雨滴刚刚全部创建的,往下落的时候,会立刻创建一行新的雨滴。然后跟着一起落,不知道问题在哪里。

你可能感兴趣的:(python习题,python)