python编程从入门到实践p221页,浮点报错的问题

python编程从入门到实践p221页,浮点报错的问题_第1张图片

ship.py的__init()__写变量少了。改为

def __init__(self,ai_settings,screen):

以下为截止到python编程从入门到实践p221页,浮点移动的程序

ship.py

import pygame
class Ship():
	def __init__(self,ai_settings,screen):
		self.screen = screen
		self.ai_settings = ai_settings
		#加载飞船图像
		self.image = pygame.image.load("images/ship.bmp")
		#获取飞船的属性rect
		self.rect = self.image.get_rect()
		self.screen_rect = screen.get_rect()
		#让游戏元素居中,设置相应rect对象的center,centerx,centery.
		self.rect.centerx = self.screen_rect.centerx
		#让游戏元素与边缘对齐,top,bottom,left,right.
		self.rect.bottom = self.screen_rect.bottom
		self.center = float(self.rect.centerx)
		#移动标志
		self.moving_right = False
		self.moving_left = False

	def update(self):
		"""根据移动标志调整飞船的位置,可以连续移动"""
		if self.moving_right:
			#让游戏元素居中,设置相应rect对象的center,centerx,centery.
			self.center += self.ai_settings.ship_speed_factor

		if self.moving_left:
			self.center -= self.ai_settings.ship_speed_factor
		
		self.rect.centerx = self.center

	def blitme(self):
		#将飞船的图像绘制到屏幕上
		self.screen.blit(self.image,self.rect)

settings.py,在这里有个self.ship_speed_factor = 1.5

class Settings():
	"""存储设置的类"""
	def __init__(self):
		"""初始化游戏设置"""
		#屏幕的设置
		self.screen_width = 800
		self.screen_height = 600
		self.bg_color = (230,230,230)

		#飞船的设置
		self.ship_speed_factor = 1.5
		

game_functions.py

import sys
import pygame
def check_events(ship):
	"""响应鼠标事件"""
	#监听键盘鼠标事件
	for event in pygame.event.get():#键盘鼠标事件
		if event.type == pygame.QUIT:#注意 == 两个等号
			sys.exit()

		elif event.type == pygame.KEYDOWN:
			if event.key == pygame.K_RIGHT:
				ship.moving_right = True

			if event.key == pygame.K_LEFT:
				ship.moving_left = True

		elif event.type == pygame.KEYUP:
			if event.key == pygame.K_RIGHT:
				ship.moving_right = False

			if event.key == pygame.K_LEFT:
				ship.moving_left = False
				
def update_screen(ai_settings,screen,ship):
	"""更新图像"""
	#用背景色填充屏幕
	screen.fill(ai_settings.bg_color)	
	#将飞船的图像绘制到屏幕上
	ship.blitme()
	#在while里面一直刷新屏幕,这一条程序放到最下面
	pygame.display.flip()

alien_invasion.py

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf #as是别名
def run_game():
	#初始化游戏
	pygame.init()#这个是pygame的初始化
	pygame.display.set_caption("飞机大战")
	ai_settings = Settings()
	#创建屏幕对象
	screen = pygame.display.set_mode([ai_settings.screen_width,ai_settings.screen_height])
	#创建一艘飞船
	ship = Ship(ai_settings,screen)
	#游戏的主循环
	while True:#注意True首字母大写
		#监听键盘鼠标事件
		gf.check_events(ship)
		ship.update()

		gf.update_screen(ai_settings,screen,ship)

run_game()

将settings.py中的 self.ship_speed_factor = 5.5,速度就很明显了!

你可能感兴趣的:(python编程从入门到实践)