练习13.1_星星_Python编程:从入门到实践(第3版)

找一副星星图像,并在屏幕上显示一系列排列整齐的星星

star_game.py

import pygame
import sys
from star import Star


class StarsGame:
    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.screen_width, self.screen_height = (1200, 800)
        self.screen = pygame.display.set_mode((self.screen_width, self.screen_height))
        pygame.display.set_caption('Stars')
        self.bg_color = (176, 224, 230)
        self.stars = pygame.sprite.Group()
        self._create_stars()

    def run_game(self):
        while True:
            self._check_events()
            self._update_screen()
            self.clock.tick(60)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)

    def _check_keydown_events(self, event):
        if event.key == pygame.K_q:
            sys.exit()

    def _create_stars(self):
        star = Star(self)
        star_width, star_height = star.rect.size
        current_x, current_y = 2 * star_width, 2 * star_height
        while current_y < (self.screen_height - 3 * star_height):
            while current_x < (self.screen_width - 2 * star_width):
                self._create_star(current_x, current_y)
                current_x += 2 * star_width
            current_x = 2 * star_width
            current_y += 2 * star_height

    def _create_star(self, x_position, y_position):
        new_star = Star(self)
        new_star.rect.x = x_position
        new_star.rect.y = y_position
        self.stars.add(new_star)

    def _update_screen(self):
        self.screen.fill(self.bg_color)  # 调用fill()方法用背景色填充屏幕。
        # fill()方法用于处理surface,只接受一个表示颜色的实参
        self.stars.draw(self.screen)  # 让外星人现身
        # 让最近绘制的屏幕可见
        pygame.display.flip()


if __name__ == '__main__':
    sg = StarsGame()
    sg.run_game()

star.py

import pygame
from pygame.sprite import Sprite


class Star(Sprite):

    def __init__(self, stars_game):
        super().__init__()
        self.screen = stars_game.screen

        self.image = pygame.image.load('images/star.png')
        self.rect = self.image.get_rect()

        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值