import sys
import pygame
from setting import Setting
from ship import Ship
class Game:
def __init__(self):
self.setting = Setting(self)
self.screen = pygame.display.set_mode((1200, 800))
self.screen_rect = self.screen.get_rect()
pygame.display.set_caption("外星人入侵")
self.ship = Ship(self)
self.clock=pygame.time.Clock()
def run_game(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
self.check_keydown(event)
if event.type == pygame.KEYUP:
self.check_keyup(event)
self.ship.update()
self.screen.fill(self.setting.bg_color)
self.ship.blitme()
pygame.display.flip()
self.clock.tick(60)
def check_keydown(self,event):
if event.key == pygame.K_LEFT:
self.ship.moving_left = True
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
if event.key == pygame.K_UP:
self.ship.moving_up = True
if event.key == pygame.K_DOWN:
self.ship.moving_down = True
if event.key == pygame.K_q:
sys.exit()
def check_keyup(self,event):
if event.key == pygame.K_LEFT:
self.ship.moving_left = False
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
if event.key == pygame.K_UP:
self.ship.moving_up = False
if event.key == pygame.K_DOWN:
self.ship.moving_down = False
ai=Game()
ai.run_game()
import pygame
class Ship:
def __init__(self,ai):
self.ai = ai
self.setting=ai.setting
self.screen = ai.screen
self.screen_rect = ai.screen.get_rect()
self.image=pygame.image.load('images/3.png')
self.rect = self.image.get_rect()
self.rect.midbottom=self.screen_rect.midbottom
self.moving_right=False
self.moving_left=False
self.moving_up=False
self.moving_down=False
self.x=float(self.rect.x)
self.y=float(self.rect.y)
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x+=self.setting.ship_speed
if self.moving_left and self.rect.left>0:
self.x-=self.setting.ship_speed
if self.moving_up and self.rect.top>0:
self.y-=self.setting.ship_speed
if self.moving_down and self.rect.bottom<self.screen_rect.bottom:
self.y+=self.setting.ship_speed
self.rect.x=self.x
self.rect.y=self.y
def blitme(self):
self.screen.blit(self.image,self.rect)
```新手提问,这是我写的代码,为什么飞机运动时会有部分会飞出屏幕?请各位大神指教