|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在aline_invasion.py的while循环里面需要先运行gf.check_events(ship)后再运行ship.update(),check_event(ship)这个函数里面的for循环不断接受我键盘按下的命令,在for循环运行的时候gf.check_events(ship)还没执行完,所以while循环里面的ship.update()是没有执行的,所以飞船位置在我连续发出某一指令的时候不是不会动吗?可实际上飞船还是动了,而且是连续移动,这是为什么呢?当我把ship.update()放到check_events(ship)的for循环里面之后发现飞船不能连续移动,这又是为什么?
aline_invasion.py
import sys
import pygame
from settings import settings
from ship import Ship
import game_functions as gf
def run_game():
#初始化游戏并创建一个屏幕对象
pygame.init()
ai_settings = settings()
screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
pygame.display.set_caption("Alien Inversion")
#创建一艘飞船
ship = Ship(ai_settings, screen)
#开始游戏的主循环
while True:
gf.check_events(ship)
ship.update()
gf.update_screen(ai_settings, screen, ship)
run_game()
game_functions.py
import sys
import pygame
def check_keydown_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
def check_keyup_events(event, ship):
if event.key == pygame.K_RIGHT:
ship.moving_right = False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
def check_events(ship):
# 监视键盘和鼠标事件
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ship)
elif event.type == pygame.KEYUP:
check_keyup_events(event, ship)
else:
pass
def update_screen(ai_settings, screen, ship):
# 每次循环都重绘屏幕
screen.fill(ai_settings.bg_color)
ship.blitme()
# 刷新屏幕
pygame.display.flip()
ship.py
import pygame
class Ship():
def __init__(self, ai_settings, screen):
"""设置飞船并设置其初始位置"""
self.screen = screen
#加载飞船图像并且获取其外接矩形
self.image = pygame.image.load('images/ship.bmp')
self.rect = self.image.get_rect()
self.screen_rect = screen.get_rect()
self.ai_settings = ai_settings
#将每艘飞船放在屏幕底部中央
self.rect.centerx = self.screen_rect.centerx
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 and self.rect.right < self.screen_rect.right:
self.center += self.ai_settings.ship_speed_factor
if self.moving_left and self.rect.left > 0:
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
class settings():
"""存储游戏中所有的类"""
def __init__(self):
"""初始化游戏设置"""
self.screen_width = 1200
self.screen_height = 800
self.bg_color = (230, 230, 230)
self.ship_speed_factor = 1.5
|
|