13_1-13_2

 图片命名:star.png,在上述代码文件夹中,新建文件夹images,将图片放置在新文件夹即可

 13_1 星星主程序:

import sysimport pygamefrom settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alienclass AlienInvasion:"""Overall class to manage game assets and behavior."""def __init__(self):"""Initialize the game, and create game resources."""pygame.init()self.settings = Settings()self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)self.settings.screen_width = self.screen.get_rect().widthself.settings.screen_height = self.screen.get_rect().heightpygame.display.set_caption("Alien Invasion")self.ship = Ship(self)self.bullets = pygame.sprite.Group()self.aliens = pygame.sprite.Group()self._create_fleet()def run_game(self):"""Start the main loop for the game."""while True:self._check_events()self.ship.update()self._update_bullets()self._update_screen()def _check_events(self):"""Respond to keypresses and mouse events."""for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.KEYDOWN:self._check_keydown_events(event)elif event.type == pygame.KEYUP:self._check_keyup_events(event)def _check_keydown_events(self, event):"""Respond to keypresses."""if event.key == pygame.K_RIGHT:self.ship.moving_right = Trueelif event.key == pygame.K_LEFT:self.ship.moving_left = Trueelif event.key == pygame.K_q:sys.exit()elif event.key == pygame.K_SPACE:self._fire_bullet()def _check_keyup_events(self, event):"""Respond to key releases."""if event.key == pygame.K_RIGHT:self.ship.moving_right = Falseelif event.key == pygame.K_LEFT:self.ship.moving_left = Falsedef _fire_bullet(self):"""Create a new bullet and add it to the bullets group."""if len(self.bullets) < self.settings.bullets_allowed:new_bullet = Bullet(self)self.bullets.add(new_bullet)def _update_bullets(self):"""Update position of bullets and get rid of old bullets."""# Update bullet positions.self.bullets.update()# Get rid of bullets that have disappeared.for bullet in self.bullets.copy():if bullet.rect.bottom <= 0:self.bullets.remove(bullet)def _create_fleet(self):"""Create the fleet of aliens."""# Create an alien and find the number of aliens in a row.# Spacing between each alien is equal to one alien width.alien = Alien(self)alien_width, alien_height = alien.rect.sizeavailable_space_x = self.settings.screen_width - (2 * alien_width)  # 可以用于放置外星人的水平空间(为了求一行能放多少外星人)number_aliens_x = available_space_x // (2 * alien_width)  # 计算出一行能容纳的外星人个数# Determine the number of rows of aliens that fit on the screen.ship_height = self.ship.rect.heightavailable_space_y = (self.settings.screen_height -(3 * alien_height) - ship_height)  # 可用于放置外星人的垂直空间(为了求能放多少行外星人)number_rows = available_space_y // (2 * alien_height)  # 计算出能容纳多少行外星人# Create the full fleet of aliens.for row_number in range(number_rows):for alien_number in range(number_aliens_x):self._create_alien(alien_number, row_number)  # 调用辅助方法_create_alien,添加外星人到编组aliensdef _create_alien(self, alien_number, row_number):"""Create an alien and place it in the row."""alien = Alien(self)alien_width, alien_height = alien.rect.sizealien.x = alien_width + 2 * alien_width * alien_numberalien.rect.x = alien.x  # 每一个alien的属性的x坐标,必须定义x,y坐标,python才知道要将每一个外星人绘制到哪个位置alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number  # 每一个alien的rect属性y坐标self.aliens.add(alien)def _update_screen(self):"""Update images on the screen, and flip to the new screen."""self.screen.fill(self.settings.bg_color)self.ship.blitme()for bullet in self.bullets.sprites():bullet.draw_bullet()self.aliens.draw(self.screen)  # 根据定义的alien.rect.x和alien.rect.y,绘制外星人到屏幕上pygame.display.flip()if __name__ == '__main__':# Make a game instance, and run the game.ai = AlienInvasion()ai.run_game()

13_2更逼真的星星主程序:

import sysimport pygamefrom settings import Settings
from ship import Ship
from bullet import Bullet
from alien import Alien
from random import randintclass AlienInvasion:"""Overall class to manage game assets and behavior."""def __init__(self):"""Initialize the game, and create game resources."""pygame.init()self.settings = Settings()self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)self.settings.screen_width = self.screen.get_rect().widthself.settings.screen_height = self.screen.get_rect().heightpygame.display.set_caption("Alien Invasion")self.ship = Ship(self)self.bullets = pygame.sprite.Group()self.aliens = pygame.sprite.Group()self._create_fleet()def run_game(self):"""Start the main loop for the game."""while True:self._check_events()self.ship.update()self._update_bullets()self._update_screen()def _check_events(self):"""Respond to keypresses and mouse events."""for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()elif event.type == pygame.KEYDOWN:self._check_keydown_events(event)elif event.type == pygame.KEYUP:self._check_keyup_events(event)def _check_keydown_events(self, event):"""Respond to keypresses."""if event.key == pygame.K_RIGHT:self.ship.moving_right = Trueelif event.key == pygame.K_LEFT:self.ship.moving_left = Trueelif event.key == pygame.K_q:sys.exit()elif event.key == pygame.K_SPACE:self._fire_bullet()def _check_keyup_events(self, event):"""Respond to key releases."""if event.key == pygame.K_RIGHT:self.ship.moving_right = Falseelif event.key == pygame.K_LEFT:self.ship.moving_left = Falsedef _fire_bullet(self):"""Create a new bullet and add it to the bullets group."""if len(self.bullets) < self.settings.bullets_allowed:new_bullet = Bullet(self)self.bullets.add(new_bullet)def _update_bullets(self):"""Update position of bullets and get rid of old bullets."""# Update bullet positions.self.bullets.update()# Get rid of bullets that have disappeared.for bullet in self.bullets.copy():if bullet.rect.bottom <= 0:self.bullets.remove(bullet)def _create_fleet(self):"""Create the fleet of aliens."""# Create an alien and find the number of aliens in a row.# Spacing between each alien is equal to one alien width.alien = Alien(self)alien_width, alien_height = alien.rect.sizeavailable_space_x = self.settings.screen_width - (2 * alien_width)  # 可以用于放置外星人的水平空间(为了求一行能放多少外星人)number_aliens_x = available_space_x // (2 * alien_width)  # 计算出一行能容纳的外星人个数# Determine the number of rows of aliens that fit on the screen.ship_height = self.ship.rect.heightavailable_space_y = (self.settings.screen_height -(3 * alien_height) - ship_height)  # 可用于放置外星人的垂直空间(为了求能放多少行外星人)number_rows = available_space_y // (2 * alien_height)  # 计算出能容纳多少行外星人# Create the full fleet of aliens.for row_number in range(number_rows):for alien_number in range(number_aliens_x):self._create_alien(alien_number, row_number)  # 调用辅助方法_create_alien,添加外星人到编组aliensdef _create_alien(self, alien_number, row_number):"""Create an alien and place it in the row."""alien = Alien(self)alien_width, alien_height = alien.rect.sizealien.x = randint(0,200) + 2 * alien_width * alien_numberalien.rect.x = alien.x  # 每一个alien的属性的x坐标,必须定义x,y坐标,python才知道要将每一个外星人绘制到哪个位置alien.rect.y = randint(0,300) + 3 * alien.rect.height * row_number  # 每一个alien的rect属性y坐标self.aliens.add(alien)def _update_screen(self):"""Update images on the screen, and flip to the new screen."""self.screen.fill(self.settings.bg_color)self.ship.blitme()for bullet in self.bullets.sprites():bullet.draw_bullet()self.aliens.draw(self.screen)  # 根据定义的alien.rect.x和alien.rect.y,绘制外星人到屏幕上pygame.display.flip()if __name__ == '__main__':# Make a game instance, and run the game.ai = AlienInvasion()ai.run_game()

alien.py (为了便捷,引用了书中代码,只是将外星人的图片替换成了星星图片,类命名未修改)

import pygame
from pygame.sprite import Spriteclass Alien(Sprite):"""A class to represent a single alien in the fleet."""def __init__(self, ai_game):"""Initialize the alien and set its starting position."""super().__init__()self.screen = ai_game.screen# Load the alien image and set its rect attribute.self.image = pygame.image.load('images/star.png')self.rect = self.image.get_rect()# Start each new alien near the top left of the screen.self.rect.x = self.rect.widthself.rect.y = self.rect.height# Store the alien's exact horizontal position.self.x = float(self.rect.x)

ship.py

import pygameclass Ship:"""A class to manage the ship."""def __init__(self, ai_game):"""Initialize the ship and set its starting position."""self.screen = ai_game.screenself.settings = ai_game.settingsself.screen_rect = ai_game.screen.get_rect()# Load the ship image and get its rect.self.image = pygame.image.load('images/ship.bmp')self.rect = self.image.get_rect()# Start each new ship at the bottom center of the screen.self.rect.midbottom = self.screen_rect.midbottom# Store a decimal value for the ship's horizontal position.self.x = float(self.rect.x)# Movement flagsself.moving_right = Falseself.moving_left = Falsedef update(self):"""Update the ship's position based on movement flags."""# Update the ship's x value, not the rect.if self.moving_right and self.rect.right < self.screen_rect.right:self.x += self.settings.ship_speedif self.moving_left and self.rect.left > 0:self.x -= self.settings.ship_speed# Update rect object from self.x.self.rect.x = self.xdef blitme(self):"""Draw the ship at its current location."""self.screen.blit(self.image, self.rect)

settings.py

class Settings:"""A class to store all settings for Alien Invasion."""def __init__(self):"""Initialize the game's settings."""# Screen settingsself.screen_width = 1200self.screen_height = 800self.bg_color = (230, 230, 230)# Ship settingsself.ship_speed = 1.5# Bullet settingsself.bullet_speed = 1.0self.bullet_width = 3self.bullet_height = 15self.bullet_color = (60, 60, 60)self.bullets_allowed = 3

(第2版)Python编程从入门到实践_外星人项目习题13-1-13-2答案更逼真的星星_pygame练习题_python项目练习题相关推荐

  1. Python编程从入门到实践第7章习题答案

    #7-1汽车租赁 #coding:gbk #7-1汽车租赁 sorts = input("Please enter the kind of the car") print('Let ...

  2. Python编程从入门到实践(第二版)课后习题自写代码

    Python编程从入门到实践(第二版)课后习题自写代码 第八章 函数 最近自学的python,动手做了一下课后习题,错误也许会有,和大家一起探讨.多多指教! 8.3 返回值 动手试一试代码片 &quo ...

  3. 《Python编程从入门到实践 第2版》 最强入门Python书籍

    市场上关于Python的书籍是非常多的,细分有入门系列,进阶系列和精通系列,在众多的Python书籍中给我印象最为深刻的当属人民邮电出版社下的图灵系列图书<Python编程从入门到实践>和 ...

  4. 笨办法学习python应该看第几版_求问:完全小白学习Python看《笨方法学Python3》还是看《Python编程从入门到实践》?...

    完全小白,建议看 <Python编程从入门到实践> 或 <像计算机科学家一样思考Python 第2版> 本书以培养读者以计算机科学家一样的思维方式来理解Python语言编程.贯 ...

  5. 《Python编程从入门到实践 第2版》 读后感

    <Python编程从入门到实践 第2版> 读后感 一直在想,一本好的Python书籍应该是怎样的?是将所有的基础知识点都讲解透彻?还是仅仅从方法上对读者授之以渔呢?我想这也是很多著书人在开 ...

  6. python基础学习[python编程从入门到实践读书笔记(连载三)]:django学习笔记web项目

    文章目录 Django项目:学习笔记web网页 项目部署 参考 自己部署的网站,还是小有成就感的,毕竟踩过很多坑,实战技能也有些许进步. 网站链接:http://lishizheng.herokuap ...

  7. 《Python编程从入门到实践》,留言送5本

    你好,我是 zhenguo 我每次送书,一定必选经典.今天图灵出版社的这本<Python编程从入门到实践>,就很值得一读,强调入门学习Python的动手和实践,是一本经典好书.今天一共赠送 ...

  8. cmd 系统找不到指定路径的问题(Python编程从入门到实践1.5.1踩坑)

    对于系统找不到指定路径的问题 大同小异 啊 我是一名Python初学者 在学习Python编程从入门到实践(第二版) 1.5.1在Windows系统中从终端运行Python程序 遇到了这种问题 我是按 ...

  9. python编程 从入门到实践怎么样-python编程从入门到实践这本书怎么样

    <Python编程-从入门到实践>作者: Eric Matthes,已翻译为中文,人民邮电出版社出版. python编程从入门到实践怎么样? 我们一起看看已经学习的同学对这本书的口碑和评价 ...

最新文章

  1. java练习:模拟试下你斗地主的洗牌、发牌、看牌功能
  2. 获取并编译linux源码,android获取源代码、编译、命令
  3. Git 学习(二)版本库创建
  4. iptables的基础知识-iptables中的状态检测
  5. 2层,3层,4层交换机的区别与特点!!
  6. #时间预测算法_基于超级学习者机器学习算法预测ICU患者急性低血压发作
  7. 第四届西安邮电大学acm-icpc校赛 流浪西邮之寻找火石碎片 多体积条件背包
  8. 你用哪种工具进行iOS app自动化功能测试?
  9. 操作系统实验报告12:线程2
  10. scikit-learn学习笔记(三)Generalized Linear Models ( 广义线性模型 )
  11. chrome 控制台 base64加密解密
  12. C#中完美克隆引用类型的对象
  13. chrome实现屏幕取词并翻译
  14. 微信支付商户平台可以绑定多个不同主体的小程序或微信公众号
  15. 内存卡数据被格式化如何恢复?
  16. 嗯,春招两次腾讯面试都挂二面了,分享下我失败+傻傻的面试经历
  17. 竞逐新能源汽车续航,背靠广汽的巨湾技研能否打好“技术牌”?
  18. BZOJ2121 字符串游戏 【dp】
  19. 广告联盟反作弊一些常识
  20. 无心剑英译朱熹《观书有感二首·其一》

热门文章

  1. 软件设计模式与体系结构 课后练习1
  2. flink时间窗口无新的数据进来最后一个窗口不关闭
  3. web渗透测试----5、暴力破解漏洞--(6)VNC密码破解
  4. linux 随机抽取文件中N行
  5. SpringBoot集成WebSocket实现及时通讯聊天功能!!!
  6. 链叨叨直播间丨CryptoMechaKing——末世机甲“元宇宙游戏”来临
  7. php 相同数据合并单元格,elementUI table合并相同数据的单元格
  8. 【最新版】愚人节整人软件大全
  9. 怎么安装VMware tools
  10. 常见面试题的基础总结(JVM篇)