首页 > 电脑

python武装飞船允许不断移动代码写好打不开

更新时间2019-06-21 10:27:48

alen_invasion.py

import sys

 

import pygame

 

from settings import Settings

from ship import Ship

import game_functions as gf

 

def run_game():

# 初始化pygame、设置和屏幕对象

pygame.init()

ai_settings = Settings()

screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))

pygame.display.set_caption("Alien Invasion")

 

# 创建一艘飞船

ship = Ship(screen)

 

# 开始游戏的主循环

while True:

gf.check_events(ship)

ship.update()

gf.update_screen(ai_settings, screen, ship)

 

# 监视键盘和鼠标事件

for event in pygame.event.get():

if event.type == pygame.QUIT:

sys.exit()

 

# 每次循环时都重绘屏幕

screen.fill(ai_settings.bg_color)

ship.blitme()

 

# 让最近绘制的屏幕可见

pygame.display.flip()

 

run_game()

 

ship.py

 

import pygame

 

class Ship():

 

def __init__(self, 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.rect.centerx = self.screen_rect.centerx

self.rect.bottom = self.screen_rect.bottom

 

# 移动标志

self.moving_right= False

self.moving_left = False

 

def update(self):

"""根据移动标志调整飞船的位置"""

if self.moving_right:

self.rect.centerx += 1

if self.moving_left:

self.rect.centerx -= 1

 

def blitme(self):

"""在指定位置放置飞船"""

self.screen.blit(self.image, self.rect)

 

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

elif event.key == pygame.K_LEFT:

ship.moving_left = True

 

elif event.type == pygame.KEYUP:

if event.key == pygame.K_RIGHT:

ship.moving_right = False

elif event.key == pygame.K_LEFT:

ship.moving_left = False

 

#向右移动飞船

ship.rect.centerx += 1

 

def update_screen(ai_settings, screen, ship):

"""更新屏幕上的图像,并切换到新屏幕"""

# 每次循环时都重绘屏幕

screen.fill(ai_settings.bg_color)

ship.blitme()

 

# 让最近绘制的屏幕可见

pygame.display.flip()


去CSDN上找找吧,前段时间我还在上面发布了我重构过的版本,可以参考

上一篇:图文快印erp中,订单显示是不是实时刷新的?

下一篇:如何去掉回车自动生成编号功能?