码迷,mamicode.com
首页 > 其他好文 > 详细

项目1——飞机大战游戏

时间:2020-04-23 01:13:17      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:append   split   get   while   飞机大战   eve   pre   break   sys   

1.开发环境

技术图片

2.游戏框架

技术图片

3.游戏流程

技术图片

4游戏图片素材

网址:https://www.jianshu.com/p/0993c99f6000

5游戏所需创建:技术图片

我是把所有有关飞船的图片放在了一个图片里命名为:shoot.png

score.txt为记录分数排行榜的文本文件如图:技术图片

600, 400...为所得分数,初始设置为0

6代码

import codecs
import pygame
import random
from pygame.locals import *#pygame常量
from sys import exit
#--设置游戏屏幕大小--
screen_width=480
screen_height=600
#子弹类
class Bullet(pygame.sprite.Sprite):
def __init__(self,bullet_img,init_pos):#加入子弹图片和发射位置
pygame.sprite.Sprite.__init__(self)
self.image=bullet_img
self.rect=self.image.get_rect()
self.rect.midbottom=init_pos#确定发射位置
self.speed=10#子弹速度
def move(self):
self.rect.top-=self.speed

#飞机类创建
class Player(pygame.sprite.Sprite):
def __init__(self,plane_img,player_rect,init_pos):#加入飞机图片,图片位置,飞机位置
pygame.sprite.Sprite.__init__(self)#调用初始化方法
self.image=[]
for i in range(len(player_rect)):
self.image.append(plane_img.subsurface(player_rect[i]).convert_alpha())
self.rect=player_rect[0]
self.rect.topleft=init_pos
self.speed=8#飞机速度
self.bullets=pygame.sprite.Group()#飞机发射的子弹类图片
self.image_index=0
self.is_hit=False#默认没有击中
#发射子弹
def shoot(self ,bullet_img):
bullet=Bullet(bullet_img,self.rect.midtop)#子弹的位置
self.bullets.add(bullet)

#向上
def moveUp(self):
if self.rect.top<=0:
self.rect.top=0
else:
self.rect.top-=self.speed
#向下
def moveDown(self):
if self.rect.top>=screen_height-self.rect.height:#屏幕高度-飞机高度
self.rect.top=screen_height-self.rect.height
else:
self.rect.top+=self.speed
#向左
def moveleft(self):
if self.rect.left<=0:
self.rect.left=0
else:
self.rect.left-=self.speed
#向右
def moveright(self):
if self.rect.left >= screen_width- self.rect.width: # 屏幕宽度-飞机宽度
self.rect.left = screen_width- self.rect.width
else:
self.rect.left += self.speed
#敌机创建
class Enemy(pygame.sprite.Sprite):
def __init__(self,enemy_img,enemy_down_imgs,init_pos):#加入敌机图片,敌机销毁图片,敌机位置
pygame.sprite.Sprite.__init__(self)#调用初始化方法
self.image=enemy_img
self.rect=self.image.get_rect()
self.rect.topleft=init_pos#敌机当前位置
self.down_imgs=enemy_down_imgs
self.speed=2
self.down_index=0#图片游标
def move(self):
self.rect.top+=self.speed
#写入文本txt
def write_txt(context, srtim, path, ):#srtim代表写入方式
f = codecs.open(path,srtim,‘utf8‘)
f.write(str(context))
f.close()


#读取txt
def read_txt(path):
with open(path,‘r‘,encoding=‘utf8‘) as f:
lines=f.readlines()
return lines




#初始化pygame一定把图片路径补充完整
pygame.init()
screen=pygame.display.set_mode((screen_width,screen_height))#设置窗体大小
pygame.display.set_caption(‘飞机大战‘)
ic_launcher= pygame.image.load("G:/py-学习/实战项目/飞机大战小游戏/recourse/image/ic_launcher.png").convert_alpha()#加载图片
pygame.display.set_icon(ic_launcher)#设置窗体的icon图标
#背景图片
background=pygame.image.load("G:/py-学习/实战项目/飞机大战小游戏/recourse/image/background.png")
#游戏结束图片
game_over=pygame.image.load("G:/py-学习/实战项目/飞机大战小游戏/recourse/image/game_over.jpg")
#玩家,子弹,敌机等图片
plane_img=pygame.image.load("G:/py-学习/实战项目/飞机大战小游戏/recourse/image/shoot.png")

def startGame():
player_rect=[]
#正常行驶飞机
player_rect.append(pygame.Rect(0,99,100,120))#获取飞机在图片的所在位置
player_rect.append(pygame.Rect(165, 360, 102, 126))
#发生碰撞的飞机
player_rect.append(pygame.Rect(165, 360, 102, 126))
player_rect.append(pygame.Rect(330, 498, 102,126))
player_rect.append(pygame.Rect(330, 498, 102,126))
player_rect.append(pygame.Rect(432, 624, 102, 126))
player_pos=[200,600]#飞机初始位置
player=Player(plane_img,player_rect,player_pos)#创建玩家飞机类,飞机图片,图片位置,飞机位置
#加载子弹,对子弹进行操作修饰
bullet_rect=pygame.Rect(1005,987,10,21)
bullet_img=plane_img.subsurface(bullet_rect)#获得子弹图片
#敌机设置
enemy1_rect=pygame.Rect(530,612,57,43)
enemy1_img=plane_img.subsurface(enemy1_rect)#敌机没有被子弹射击到时图片,开始图片
enemy1_down_ims=[]#装飞机被销毁后的图片
enemy1_down_ims.append(plane_img.subsurface(pygame.Rect(267,347,57,43 )))
enemy1_down_ims.append(plane_img.subsurface(pygame.Rect(873, 697, 57, 43)))
enemy1_down_ims.append(plane_img.subsurface(pygame.Rect(267, 296, 57, 43)))
enemy1_down_ims.append(plane_img.subsurface(pygame.Rect(930, 697, 57, 43)))
shoot_frequency=0#对子弹进行频率设置
enemy_frequency=0#敌机生成频率
player_down_index=16
score=0#碰撞分数
clock=pygame.time.Clock()
enemies1=pygame.sprite.Group()#敌机集合
enemies_down=pygame.sprite.Group()#飞机销毁集合

# 游戏主循环
running = True
while running:
screen.fill(0) # 填充颜色
screen.blit(background, (0, 0))
clock.tick(60)
#生成子弹
if not player.is_hit:
if shoot_frequency%15==0:
player.shoot(bullet_img)
shoot_frequency +=1
if shoot_frequency>=15:
shoot_frequency=0



for bullet in player.bullets:#生成一个子弹集合
bullet.move()
if bullet.rect.bottom<0:#判断子弹是否出了屏幕
player.bullets.remove(bullet)
player.bullets.draw(screen)#显示子弹


#敌机显示
if enemy_frequency%50==0:
enemy1_pos=[random.randint(0,screen_width-enemy1_rect.width),0]#生成位置随机
enemy1=Enemy( enemy1_img,enemy1_down_ims,enemy1_pos)#敌机初始化
enemies1.add(enemy1)
enemy_frequency+=1
if enemy_frequency>=100:
enemy_frequency=0
for enemy in enemies1:
enemy.move()
if enemy.rect.top<0:#判断敌机是否溢出屏幕
enemies1.remove()
if pygame.sprite.collide_circle(enemy,player):#判断敌机与玩家是否相撞
enemies_down.add(enemy)#将销毁敌机加入集合
enemies1.remove(enemy)#消除被击毁的敌机
player.is_hit=True
break
#玩家飞机
if not player.is_hit: # 判断飞机是否被击毁
screen.blit(player.image[player.image_index], player.rect)
player.image_index = shoot_frequency // 8
else:
player.image_index=player_down_index//8
screen.blit(player.image[player.image_index],player.rect)#玩家飞机爆炸图
player_down_index +=1
if player_down_index>47:
running = False


enemies1_down=pygame.sprite.groupcollide(enemies1,player.bullets,1,1)#1为true,发生碰撞的元素为true销毁,为false不销毁
for enemy_down in enemies1_down:
enemies_down.add(enemy_down)
for enemy_down in enemies_down:
if enemy_down.down_index>7:
enemies_down.remove(enemy_down)
score+=100
continue
screen.blit(enemy_down.down_imgs[enemy_down.down_index//2],enemy_down.rect)#绘制飞机爆炸图片
enemy_down.down_index+=1
enemies1.draw(screen)
score_font=pygame.font.Font(None,36)
score_text=score_font.render(str(score),True,(128,128,128))
text_rect=score_text.get_rect()
screen.blit(score_text,text_rect)



#判断玩家飞机
if not player.is_hit:#判断飞机是否被击毁
screen.blit(player.image[player.image_index],player.rect)
player.image_index=shoot_frequency//8
pygame.display.update() # 更新屏幕处理
for event in pygame.event.get():
if event.type == pygame.QUIT: # 判断是否与退出游戏
pygame.quit()
exit()
key_pressed = pygame.key.get_pressed()
if key_pressed[K_w] or key_pressed[K_UP]: # 判断w是否为向上的按键
player.moveUp()
if key_pressed[K_s] or key_pressed[K_DOWN]: # 向下
player.moveDown()
if key_pressed[K_a] or key_pressed[K_LEFT]: # 向左
player.moveleft()
if key_pressed[K_d] or key_pressed[K_RIGHT]: # 向右
player.moveright()

#绘制游戏结束画面
screen.blit(game_over,(0,0))
font=pygame.font.Font(None,48)
text=font.render(‘Score:‘+str(score),True,(255,0,0))#分数的文字颜色
text_rect=text.get_rect()
text_rect.centerx=screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery+24#文字所在位置,x,y坐标
screen.blit(text,text_rect)
#重新开始按钮
xtfont=pygame.font.SysFont(‘SimHei‘,30)
textstart =xtfont.render(‘重新开始‘,True,(255,0,0))
text_rect = textstart.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery +120
screen.blit(textstart, text_rect)
#排行榜
textstart = xtfont.render(‘排行榜‘,True, (255, 0, 0))
text_rect = textstart.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery + 180
screen.blit(textstart, text_rect)
j=0
#更新排行榜,获取内容
arrayscore = read_txt(r‘score.txt‘)[0].split(‘mr‘)#[‘0‘,‘0‘,‘0‘...]
for i in range(0,len(arrayscore)):
#判断当前获取的分数是否大于排行榜上的分数
if score > int(arrayscore[i]):
j=arrayscore[i]
arrayscore[i]=str(score)
score=0
if int(j)>int(arrayscore[i]):
k=arrayscore[i]
arrayscore[i]=str(j)
j=k
#更新的分数写入文本
for i in range (0,len(arrayscore)):
if i==0:
write_txt(arrayscore[i]+‘mr‘,‘w‘,r‘score.txt‘)
else:
if( i==9):
write_txt(arrayscore[i], ‘a‘,r‘score.txt‘)
else:
write_txt(arrayscore[i]+‘mr‘, ‘a‘, r‘score.txt‘)

def gameRanking():
screen2=pygame.display.set_mode((screen_width,screen_height))
screen2.fill(0)
screen2.blit(background,(0,0))
xtfont = pygame.font.SysFont(‘SimHei‘, 30)
textstart = xtfont.render(‘排行榜‘, True, (255, 0, 0))
text_rect = textstart.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = 50
screen2.blit(textstart, text_rect)

textstart = xtfont.render(‘重新开始‘, True, (255, 0, 0))
text_rect = textstart.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.centery = screen.get_rect().centery+120
screen2.blit(textstart, text_rect)

arrayscore = read_txt(r‘score.txt‘)[0].split(‘mr‘)
for i in range(0, len(arrayscore)):
font=pygame.font.Font(None,48)
k=i+1
text=font.render(str(k)+‘‘+arrayscore[i],True,(255,0,0))
text_rect=text.get_rect()
text_rect.centerx=screen2.get_rect().centerx
text_rect.centery=80+30*k
screen2.blit(text,text_rect)


startGame()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT: # 判断是否与退出游戏
pygame.quit()
exit()
#判断鼠标点击位置
elif event.type==pygame.MOUSEBUTTONDOWN:
#点击重新开始
if screen.get_rect().centerx-70<= event.pos[0] and event.pos[0]<=screen.get_rect().centerx+50 and screen.get_rect().centery+100<= event.pos[1] and event.pos[1]<=screen.get_rect().centery+140:
startGame()

#点击排行榜
if screen.get_rect().centerx - 70 <= event.pos[0] and event.pos[0] <= screen.get_rect().centerx +50 and screen.get_rect().centery + 160 <= event.pos[1] and event.pos[1] <= screen.get_rect().centery + 200:
gameRanking()




pygame.display.update()









7显示效果
游戏结束:技术图片

  游戏进行:技术图片

 

排行榜:技术图片

项目1——飞机大战游戏

标签:append   split   get   while   飞机大战   eve   pre   break   sys   

原文地址:https://www.cnblogs.com/txy222/p/12757773.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!