如何让飞船不会出下边界?
go_plane_main.py:
# coding=utf-8
# 导入模块
import sys
import pygame
from settings import Settings
from hero import Hero
# 类
# 管理类
class one_pl:
def __init__(self):
pygame.init()
self.settings=Settings()
self.screen=pygame.display.set_mode((self.settings.screen_w,self.settings.screen_h))
pygame.display.set_caption("游戏—按Q键退出")
self.hero=Hero(self)
def run_game(self):
while True:
self._check_events()
self.hero.update()
self._update_screen()
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
elif event.key == pygame.K_RIGHT:
self.hero.moving_right=True
elif event.key == pygame.K_LEFT:
self.hero.moving_left=True
elif event.key == pygame.K_UP:
self.hero.moving_up=True
elif event.key == pygame.K_DOWN:
self.hero.moving_down=True
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
self.hero.moving_right=False
elif event.key == pygame.K_LEFT:
self.hero.moving_left=False
elif event.key == pygame.K_UP:
self.hero.moving_up=False
elif event.key == pygame.K_DOWN:
self.hero.moving_down=False
def _update_screen(self):
self.screen.fill(self.settings.bg_color)
self.hero.blitme()
pygame.display.flip()
def the_main():
ai=one_pl()
ai.run_game()
if __name__ == '__main__':
the_main()
hero.py:
# 导入模块
import pygame
# 英雄类
class Hero:
def __init__(self, ai_game):
self.screen=ai_game.screen
self.settings=ai_game.settings
self.screen_rect=ai_game.screen.get_rect()
self.image=pygame.image.load('./images/ship/ship_hero.png') # 设置图片路径
self.rect=self.image.get_rect()
self.rect.midbottom=self.screen_rect.midbottom # 设置图片在下中位置
self.x=float(self.rect.x)
self.y=float(self.rect.y)
self.moving_right=False
self.moving_left=False
self.moving_up=False
self.moving_down=False
def update(self):
if self.moving_right and self.rect.right < self.screen_rect.right:
self.x+=self.settings.ship_speed
if self.moving_left and self.rect.left > 0:
self.x-=self.settings.ship_speed
if self.moving_up and self.rect.y > 0:
self.y-=self.settings.ship_speed
if self.moving_down and self.rect.y < self.settings.screen_h:
self.y+=self.settings.ship_speed
self.rect.x=self.x
self.rect.y=self.y
def blitme(self):
self.screen.blit(self.image,self.rect)
settings.py:
class Settings:
def __init__(self):
self.screen_w=800
self.screen_h=600
self.bg_color=(39,39,39)
self.ship_speed=(1.5)