低配版飞机大战
以前做的时候想把这个完善一直没做
到现在也不没以前的心了就这样吧
- alien_invasion
import pygame
from settings import Settings
from ship import Ship
import fc
def run_game():
pygame.init()#初始化游戏
ai_s=Settings()
screen=pygame.display.set_mode((ai_s.s_w,ai_s.s_h))#创建窗口,并设置大小
pygame.display.set_caption("飞船大战")
ship=Ship(screen)
#开始游戏的主循环
while True:
fc.ck(ship)
ship.update()
fc.update(ai_s,screen,ship)
run_game()#调用函数
2.settings
```python
class Settings():
def __init__(self):
self.s_w=1200
self.s_h=800
self.bg_c=(230,230,230)
- ship
import pygame
class Ship():
def __init__(self,screen):
self.screen=screen#给self.screen传参
self.image=pygame.image.load('ship.bmp')#加载图片
self.img_rect=self.image.get_rect()#获取图片矩形
self.screen_rect=screen.get_rect()#获取屏幕矩形
self.img_rect.centerx=self.screen_rect.centerx#获取图片矩形横坐标
self.img_rect.bottom=self.screen_rect.bottom#获取图片矩形纵坐标
self.speed=2#控制速度
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.img_rect.right<self.screen_rect.right:
self.img_rect.centerx+=self.speed
if self.moving_left and self.img_rect.left>0:
self.img_rect.centerx-=self.speed
if self.moving_up and self.img_rect.top>0:
self.img_rect.centery-=self.speed
if self.moving_down and self.img_rect.bottom<self.screen_rect.bottom:
self.img_rect.centery+=self.speed
def blite(self):
self.screen.blit(self.image,self.img_rect)#绘制图片
- fc
import os #导入模块
import pygame
def ck_kd(event,ship):
if event.key == pygame.K_RIGHT:#判断右键头
ship.moving_right =True
elif event.key == pygame.K_LEFT:#判断左键头
ship.moving_left = True
elif event.key == pygame.K_UP:#判断上键头
ship.moving_up = True
elif event.key == pygame.K_DOWN:#判断下键头
ship.moving_down = True
def ck_kp(event,ship):
if event.key == pygame.K_RIGHT:
ship.moving_right=False
elif event.key == pygame.K_LEFT:
ship.moving_left = False
elif event.key == pygame.K_UP:
ship.moving_up = False
elif event.key ==pygame.K_DOWN:
ship.moving_down = False
def ck(ship):
for event in pygame.event.get():#循环事件
if event.type==pygame.QUIT:
os._exit(0)#调用os._exit(0),退出游戏
elif event.type == pygame.KEYDOWN:#判断键盘按下
ck_kd(event,ship)
elif event.type == pygame.KEYUP:#判断键盘离开
ck_kp(event,ship)
def update(ai_s,screen,ship):
screen.fill(ai_s.bg_c)#背景
ship.blite()#绘制飞船
pygame.display.flip()#让最近绘制的屏幕可见