1. 程式人生 > 程式設計 >python3實現飛機大戰

python3實現飛機大戰

本文例項為大家分享了python3實現飛機大戰的具體程式碼,供大家參考,具體內容如下

以下是親測Python飛機大戰全部程式碼,在保證有pygame環境支援並且有Python3直譯器的話完全沒問題!

如果大家喜歡的話麻煩點個贊!

執行效果如下圖:

python3實現飛機大戰

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 匯入需要使用的模組
import pygame
from pygame.locals import *
from sys import exit 
import random

# 設定螢幕大小的變數
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800
import codecs
# 子彈類
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.img_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 

# 對檔案的操作
# 寫入文字
# 要寫入的內容,寫入方式,寫入檔案所在的位置
def write_txt(contert,strim,path):
 f = codecs.open(path,'utf8')
 f.write(str(contert))
 f.close()

# 讀取文字
def read_txt(path):
 with open(path,'r',encoding='utf8') as f:
  lines = f.readlines()
 return lines 




# 初始化pygame
pygame.init()
# 設定遊戲介面的大小,背景圖片,標題
# 介面startGame(
screen = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
# 標題
pygame.display.set_caption('飛機大戰')
# 圖示
ic_launcher = pygame.image.load('resources/image/ic_launcher.png').convert_alpha()
pygame.display.set_icon(ic_launcher)
# 背景圖
background = pygame.image.load('resources/image/background.png').convert()
# 遊戲結束
game_over = pygame.image.load('resources/image/gameover.png')
# 飛機及子彈的圖片
plane_img = pygame.image.load('resources/image/shoot.png')

def startGame():
 # 1.設定玩家飛機不同狀態的圖片列表,多張圖片展示為動畫效果
 player_rect = []
 # 玩家飛機的圖片
 player_rect.append(pygame.Rect(0,99,102,126))
 player_rect.append(pygame.Rect(165,360,126))
 # 玩家飛機爆炸的圖片
 player_rect.append(pygame.Rect(165,234,126))
 player_rect.append(pygame.Rect(330,634,498,126))
 player_rect.append(pygame.Rect(432,624,126))
 player_pos = [200,600]
 # 生成玩家飛機類
 player = Player(plane_img,player_pos)
 # 加入子彈的圖片
 bullet_rect = pygame.Rect(69,77,10,21)
 bullet_img = plane_img.subsurface(bullet_rect)

 # 加入敵機圖片
 enemy1_rect = pygame.Rect(534,612,57,43) #沒有爆炸前的圖片
 enemy1_img = plane_img.subsurface(enemy1_rect)
 enemy1_down_imgs = [] #飛機銷燬後的圖片
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,347,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(873,679,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(267,296,43)))
 enemy1_down_imgs.append(plane_img.subsurface(pygame.Rect(930,697,43)))
 # 儲存敵機的集合
 enmies1 = pygame.sprite.Group()
 # 儲存被擊毀的敵機的集合
 enemies_down = pygame.sprite.Group()


 # 初始子彈射擊頻率
 shoot_frequency = 0
 # 初始化敵機生成頻率
 enemy_frequency = 0
 # 玩家飛機被擊中後的效果處理
 player_down_index = 16

 # 設定遊戲的幀數
 clock = pygame.time.Clock()
 # 初始化成績
 score = 0
 # 判斷迴圈結束的引數
 running = True
 while running:
  for event in pygame.event.get():
   if event.type == pygame.QUIT:
    exit()
  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_imgs,enemy1_pos)
   # 儲存到集合中
   enmies1.add(enemy1) 
  enemy_frequency += 1
  # 敵機生成到 100 則重新迴圈
  if enemy_frequency >= 100:
   enemy_frequency = 0
  # 敵機的移動
  for enemy in enmies1:
   enemy.move()
   # 敵機與玩家碰撞效果處理
   if pygame.sprite.collide_circle(enemy,player): # pygame判定是否相撞的方法
    enemies_down.add(enemy)  # 將敵機加入到墜毀的集合中
    enmies1.remove(enemy)  # 從敵機集合中移除 
    player.is_hit = True 
    break 
   # 移動出螢幕的敵機
   if enemy.rect.top < 0:
    enmies1.remove(enemy)
  # 與子彈碰撞
  enemies1_down = pygame.sprite.groupcollide(enmies1,player.bullets,1,1)
  for enemy_down in enemies1_down:
   enemies_down.add(enemy_down)
  

  # 繪製玩家飛機
  if not player.is_hit:
   screen.blit(player.image[player.img_index],player.rect)
   # 實現飛機動效
   player.img_index = shoot_frequency // 8
  else:
   # 玩家飛機被擊毀後的動畫效果
   player.img_index = player_down_index // 8 
   screen.blit(player.image[player.img_index],player.rect)
   player_down_index += 1
   if player_down_index > 47:
    running = False
  # 敵機被擊中的效果
  for enemy_down in enemies_down:
   if enemy_down.down_index == 0:
    pass
   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
  
  # 顯示敵機
  enmies1.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()
  text_rect.topleft = [10,10]
  screen.blit(score_text,text_rect)
  # 獲取鍵盤的輸入
  key_pressed = pygame.key.get_pressed()
  if key_pressed[K_UP] or key_pressed[K_w]:
   player.moveUp()
  if key_pressed[K_DOWN] or key_pressed[K_s]:
   player.moveDown()
  if key_pressed[K_LEFT] or key_pressed[K_a]:
   player.moveLeft()
  if key_pressed[K_RIGHT] or key_pressed[K_d]:
   player.moveRight()

  pygame.display.update()
 # 繪製遊戲結束畫面
 screen.blit(game_over,0))
 # 繪製Game Over顯示最終分數
 font = pygame.font.Font(None,48)
 text = font.render("Score:"+str(score),(255,0))
 text_rect = text.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x軸位置
 text_rect.centery = screen.get_rect().centery + 24 # y軸位置
 screen.blit(text,text_rect)
 # 使用字型
 xtfont = pygame.font.SysFont("jamrul",30)
 # 繪製重新開始按鈕
 textstart = xtfont.render('Start',0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x軸位置
 text_rect.centery = screen.get_rect().centery + 120 # y軸位置
 screen.blit(textstart,text_rect)
 # 排行榜按鈕
 textstart = xtfont.render('Ranking',0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x軸位置
 text_rect.centery = screen.get_rect().centery + 180 # y軸位置
 screen.blit(textstart,text_rect)

 # 判斷得分更新排行榜
 # 臨時變數
 j = 0
 # 讀取檔案
 arrayscore = read_txt(r'score.txt')[0].split('mr')
 # 迴圈分數列表在列表裡排序
 for i in range(0,len(arrayscore)):
  if score > int(arrayscore[i]):
   # 大於排行榜上的內容 把分數和當前分數進行替換
   j = arraysco.re[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):
    # 最近新增內容最後一個分數不加 mr
    write_txt(arrayscore[i],'a',r'score.txt')
   else:
    # 不是最後一個分數,新增的時候加 mr
    write_txt(arrayscore[i]+'mr',r'score.txt')










# 定義排行榜函式
def gameRanking():
 # 繪製背景圖片
 screen2 = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
 screen2.fill(0)
 screen2.blit(background,0))
 # 使用系統字型
 xtfont = pygame.font.SysFont('jamrul',30)
 # 1.繪製標題
 textstart = xtfont.render('Ranking',0))
 text_rect = textstart.get_rect()
 text_rect.centerx = screen.get_rect().centerx # x軸位置
 text_rect.centery = 50 # y軸位置
 screen.blit(textstart,text_rect)
 # 2.繪製重新開始按鈕
 textstart = xtfont.render('Start',text_rect)
 # 3.展示排行榜的資料
 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],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:
   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 screen.get_rect().centery + 140 >= event.pos[1]:
    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 screen.get_rect().centery + 200 >= event.pos[1]:
    gameRanking()
pygame.display.update()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。