日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python實(shí)現(xiàn)坦克大戰(zhàn)游戲 附詳細(xì)注釋

系統(tǒng) 1939 0

本文實(shí)例為大家分享了python實(shí)現(xiàn)坦克大戰(zhàn)的具體代碼,供大家參考,具體內(nèi)容如下

            
#功能實(shí)現(xiàn)游戲主窗口
import pygame,time,random#導(dǎo)入模塊
_display = pygame.display#賦值給一個變量 調(diào)用時方便
color_red = pygame.Color(255,0,0)#同上  v
class MainGame(object):
 screen_width = 900#游戲界面寬度
 screen_height = 550#界面的高度
 Tank_p1 = None#坦克對象
 window = None #窗口對象
 EnemyTank_list = []# 存儲所有敵方坦克
 EnemTank_count = 10# 要創(chuàng)建的敵方坦克的數(shù)量
 Bullet_list = [] #創(chuàng)建我方子彈列表
 EnemyTank_bullet_list = []
 Explode_list= []
 wall_list = []
 def startGame(self):
  pygame.display.init()#初始化游戲模塊的顯示
  MainGame.window = _display.set_mode([MainGame.screen_width,MainGame.screen_height])#生成并加載游戲窗口、\
  #pygame.display模塊及set_mode方法和pygame相關(guān)方法調(diào)用設(shè)置
  # 見<
            
              > UC瀏覽器實(shí)現(xiàn)自動翻譯
  pygame.display.set_caption("坦克大戰(zhàn)v1.0")#s設(shè)置游戲標(biāo)題
  self.creatEnemyTank()#類中調(diào)用初始敵方坦克方法
  self.creatMyTank()#創(chuàng)建我方坦克
  self.creatWalls()#創(chuàng)建障礙物
 
  while True:#無限循環(huán) 所有行為方法都要無限制的顯示
   MainGame.window.fill(pygame.Color(0,0,0))#窗口顏色設(shè)置 Window在開始方法已設(shè)置為游戲窗口
   self.getEvent()#死循環(huán)中 獲取事件的值 對其進(jìn)行相應(yīng)處理
   MainGame.window.blit(self.drawText("剩余敵方數(shù)量%d" %len(MainGame.EnemyTank_list)),(7, 7))#循環(huán)游戲窗口加載文本 bilt方法在頁面寫入另一個
 
   self.blitWalls()
   if MainGame.Tank_p1 and MainGame.Tank_p1.alive:
    MainGame.Tank_p1.displayTank()#循環(huán)調(diào)用生成的坦克對象(顯示)方法
 
 
   self.blitEnemyTank()# 此類中用self 循環(huán)展示敵方坦克
 
   if MainGame.Tank_p1 and not MainGame.Tank_p1.stop:
    MainGame.Tank_p1.move()# 移動
    MainGame.Tank_p1.hitWall()#撞擊墻壁
    MainGame.Tank_p1.hitEnemyTank()#撞擊敵方坦克方法
   self.blitEnemyBullet()#顯示敵方坦克子彈
   self.blitBullet()#顯示炮彈
   self.blitExplode()#顯示爆炸效果
   time.sleep(0.02)
   _display.update()#獲取更新
   #將帶有文字的surface 繪制到窗口中 循環(huán)
  # 創(chuàng)建敵方坦克
 
 def creatEnemyTank(self):#創(chuàng)建敵方坦克
 
  top = 100
 
  for i in range(MainGame.EnemTank_count):#MainGame.EnemTank_count=5 五次循環(huán)創(chuàng)建敵方坦克
   speed = random.randint(3, 6) # 隨機(jī)模塊 random.randint
   # 每次都隨機(jī)生成一個left值
   left = random.randint(1, 7)
   eTank = EnemyTank(left * 100, top, speed)#生成敵方坦克類對象 傳入?yún)?shù) left為隨機(jī)
   MainGame.EnemyTank_list.append(eTank)#將創(chuàng)建的每一個敵方坦克添加到列表
  # 將坦克加入到窗口中
 def creatMyTank(self):
  MainGame.Tank_p1 = MyTank(400, 480) # 生成一個坦克類的實(shí)例對象
  music = Music("img/start.wav")
  music.play()
 def creatWalls(self):
  for i in range(1,10):
   wall = Wall(60*i,250)
   MainGame.wall_list.append(wall)
 def blitWalls(self):
  for wall in MainGame.wall_list:
   if wall.live == True:
    wall.displayWall()
   else:
    MainGame.wall_list.remove(wall)
 def blitEnemyTank(self):#顯示敵方坦克 若出現(xiàn)坦克圖片重疊也是符合邏輯
  for eTank in MainGame.EnemyTank_list:
   if eTank.live :
    eTank.displayTank()#將列表中每一個進(jìn)行顯示 eTank為敵方坦克類對象 調(diào)用父類Tank類中顯示方法
    eTank.randMove()
    eTank.hitWall()
    eTank.hitMyTank()
    ebullet = eTank.shot()
 
    if ebullet:#如果不為空
     MainGame.EnemyTank_bullet_list.append(ebullet)
   else:
    MainGame.EnemyTank_list.remove(eTank)
 def blitEnemyBullet(self):#將敵方坦克加入到窗口中
  for ebullet in MainGame.EnemyTank_bullet_list:
   if ebullet.alive:
    ebullet.display_bullet()
    ebullet.bulletMove()
    ebullet.hitWalls()
    if MainGame.Tank_p1.alive:
     ebullet.hitMyTank()
   else:
    MainGame.EnemyTank_bullet_list.remove(ebullet)
 def blitBullet(self):#顯示子彈
  for bullet in MainGame.Bullet_list:#事件中獲的子彈的列表進(jìn)行遍歷 類似顯示坦克方法 逐個展示
   if bullet.alive:#Bullet類中設(shè)置的標(biāo)簽 來判斷子彈的存活 True為生 根據(jù)炮彈移動方法bulletmove()中所加限制條件
    bullet.display_bullet()#調(diào)用列表中子彈對象的顯示方法
    bullet.bulletMove()#子彈的移動
    bullet.hitEnemyTank()#調(diào)用與敵方坦克的碰撞檢測方法
    bullet.hitWalls()#d調(diào)用子彈碰撞墻壁
   else:
 
    MainGame.Bullet_list.remove(bullet)#如果為False bulletmove()中觸碰墻壁就是False 就從列表刪除 循環(huán)執(zhí)行
 def blitExplode(self):
  for explode in MainGame.Explode_list:
   if explode.live:
    explode.display_explode()
    music = Music("img/blast.wav")
    music.play()
   else:
    MainGame.Explode_list.remove(explode)
 def drawText(self,content):#文本 寫入游戲窗口
  pygame.font.init()#初始化字體
  font = pygame.font.SysFont("kaiti",18)#創(chuàng)建字體對象
  text_sf = font.render(content,True,color_red)#字體樣式對象
  return text_sf #返回內(nèi)容的surface
 def getEvent(self):#獲取所有事件
  eventlist = pygame.event.get()#所有事件列表
  for event in eventlist:#遍歷每一個事件進(jìn)行判斷 鍵盤輸入的字符
   #type屬性
   if event.type == pygame.QUIT:#如果是QUIT(就是點(diǎn)擊窗口的退出按鈕 叉號)
    print("退出游戲")
    self.gameOver()#退出方法
   if event.type == pygame.KEYUP:#如果鍵盤按鈕抬起 并且是上下左右鍵
    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP\
    or event.key == pygame.K_DOWN:
     if MainGame.Tank_p1 and MainGame.Tank_p1.alive:
      MainGame.Tank_p1.stop = True#stop為True 按鈕抬起就停止 start方法中的開關(guān) 實(shí)現(xiàn)坦克按住按鈕持續(xù)移動
 
   if event.type == pygame.KEYDOWN:#如果事件的類型為按下按鍵進(jìn)行如下判斷
    if event.key == pygame.K_ESCAPE :
     self.creatMyTank()
    if MainGame.Tank_p1 and MainGame.Tank_p1.alive:
     if event.key == pygame.K_LEFT:#如果為左方向鍵 如下為同一類型
      print("向左移動")
      MainGame.Tank_p1.direction = "L"#設(shè)置坦克方向進(jìn)行判斷向左就是L,
      # 并設(shè)置游戲窗口的界限 還可以利用方向作為字典的鍵獲取坦克圖片 坦克的移動方向
      #就是加載不同方向的坦克圖片 呈現(xiàn)出移動的效果
      MainGame.Tank_p1.stop = False#坦克移動的開關(guān) 循環(huán)使用 False為移動
     if event.key == pygame.K_RIGHT:
      print("向右移動")
      MainGame.Tank_p1.direction = "R"
      MainGame.Tank_p1.stop = False
     if event.key ==pygame.K_UP:
      print("向上移動")
      MainGame.Tank_p1.direction = "U"
      MainGame.Tank_p1.stop = False
     if event.key == pygame.K_DOWN:
      print("向下移動")
      MainGame.Tank_p1.direction = "D"
      MainGame.Tank_p1.stop = False
     if event.key == pygame.K_SPACE:#空格鍵發(fā)射子彈
      if len(MainGame.Bullet_list) < 3:#控制子彈在屏幕顯示的數(shù)量 太多沒有游戲體驗(yàn) 列表中存儲三個
       m = Bullet(MainGame.Tank_p1)#子彈類對象 添加到列表 開始方法調(diào)用顯示子彈 子彈觸碰墻壁列表內(nèi)移除對象
       MainGame.Bullet_list.append(m)
       music =Music("img/fire.wav")
       music.play()
 def gameOver(self):#游戲結(jié)束方法
  exit()
class BaseItem(pygame.sprite.Sprite):
 def __init__(self):
  pygame.sprite.Sprite.__init__(self)
class Tank(BaseItem):#坦克的父類
 def __init__(self,left,top):
  #坦克圖片集合
  self.images = {"U":pygame.image.load("img/p1tankU.gif"),
      "D": pygame.image.load("img/p1tankD.gif"),
      "L":pygame.image.load("img/p1tankL.gif"),
      "R": pygame.image.load("img/p1tankR.gif"),}#坦克各方向圖片的加載
   #坦克的方向
  self.direction = "U"
  #坦克初始化時候的默認(rèn)圖片,根據(jù)坦克的方向從字典里去提取
  self.image = self.images[self.direction]
  #坦克的區(qū)域(left,top,width,height)坦克位置以及坦克的大小
  self.rect = self.image.get_rect()
  self.rect.left = left#坦克距離左邊位置修改默認(rèn)參數(shù)指定的位置
  self.rect.top = top#將坦克距離上邊的位置修改我指定的位置
  self.speed = 15#設(shè)置坦克的速度
  self.stop = True #設(shè)置移動的開關(guān)
  self.oldtop = self.rect.top
  self.oldleft = self.rect.left
 def move(self):
  self.oldtop = self.rect.top
  self.oldleft = self.rect.left
  if self.direction == "U":#向上時
   if self.rect.top > 0:#self.rect = self.image.get_rect()
    # self.rect.top = top#將坦克距離上邊的位置修改我指定的位置
    self.rect.top -= self.speed#坦克的速度距離每一次調(diào)用時相減 直到<0時
  elif self.direction == "D":#向下時
   if self.rect.top < MainGame.screen_height-MainGame.Tank_p1.rect.height:#下邊界小于窗口的高度減去坦克自身的高度的距離
    self.rect.top += self.speed #距離加速度的距離 循環(huán)一次添加一次
  elif self.direction == "L":
   if self.rect.left > 0:
    self.rect.left -= self.speed
  elif self.direction == "R":
   if self.rect.left < MainGame.screen_width -MainGame.Tank_p1.rect.width:
    self.rect.left += self.speed
 def stay(self):
  self.rect.left = self.oldleft
  self.rect.top = self.oldtop
 def hitWall(self):
  for wall in MainGame.wall_list:
   if pygame.sprite.collide_rect(wall,self):
    self.stay()
 def shot(self):
  return Bullet(self)
 def displayTank(self):#坦克顯示方法
  #1.重新設(shè)置坦克的圖片
  self.image = self.images[self.direction]
  #2.將坦克加入到窗口中
  MainGame.window.blit(self.image,self.rect)#調(diào)用MainGame window方法
  # 傳入圖片和位置 self.rect = self.image.get_rect()
class MyTank(Tank):
 def __init__(self,left,top):
  super(MyTank,self).__init__(left,top)
 def hitEnemyTank(self):
  for etank in MainGame.EnemyTank_list:
   if pygame.sprite.collide_rect(etank,self):
    self.stay()
class EnemyTank(Tank):#敵方坦克類
 def __init__(self,left,top,speed):#初始化敵方坦克 三個參數(shù)
  self.images = {"U": pygame.image.load("img/enemy1U.gif"),
      "D": pygame.image.load("img/enemy1D.gif"),
      "L": pygame.image.load("img/enemy1L.gif"),
      "R": pygame.image.load("img/enemy1R.gif"), }#加載敵方坦克圖片
  # 坦克的方向
  self.direction = self.randDirection()#自定義坦克的隨機(jī)方向
  self.image = self.images[self.direction]#坦克的信息 從字典中以鍵獲得值
  # 坦克所在的區(qū)域 Rect->
  self.rect = self.image.get_rect()#獲得坦克圖片的距離 距左和距上
  # 指定坦克初始化位置 分別距x,y軸的位置
  self.rect.left = left#距左的位置>>形參
  self.rect.top = top#距上的位置
  # 新增速度屬性
  self.speed = speed #速度>>初始化時設(shè)置
  self.stop = True
  self.step = 50#設(shè)置步數(shù)
  self.live = True
 def randDirection(self):#隨機(jī)生成敵方坦克的方向圖片
  num = random.randint(1, 4)
  if num == 1:
   return 'U'
  elif num == 2:
   return 'D'
  elif num == 3:
   return 'L'
  elif num == 4:
   return 'R'
 def randMove(self):#敵方坦克隨機(jī)移動
  if self.step <= 0:#如果步數(shù)為0
   self.direction = self.randDirection()#方向?yàn)殡S機(jī)方向
   self.step = 30# 重置步數(shù)
  else:
   self.move()#移動 坦克位置不斷改變
   self.step -= 1#步數(shù)每次循環(huán)減一
 def shot(self):
  s = random.randint(1,1000)
  if s <30:
   return Bullet(self)
 def hitMyTank(self):
  if pygame.sprite.collide_rect(self,MainGame.Tank_p1):
   self.stay()
class Bullet(BaseItem):#炮彈類
 def __init__(self,tank):
  self.image = pygame.image.load("img\enemymissile.gif")
  self.direction = tank.direction
  #子彈速度
  self.speed = 18
  self.rect = self.image.get_rect()#獲得子彈的對象的坐標(biāo) 只計(jì)算距離左側(cè)和和上面
  #子彈初始化位置要根據(jù)坦克大方向進(jìn)行調(diào)整 可以自己畫圖計(jì)算
  if self.direction == "U":
   #子彈的位置 left += 坦克寬度的一半 - 子彈的寬度的一半
   self.rect.left = tank.rect.left + tank.rect.width/2 - self.rect.width/2
   self.rect.top = tank.rect.top - self.rect.height
  elif self.direction == "D":
   self.rect.left = tank.rect.left + tank.rect.width / 2 - self.rect.width / 2
   self.rect.top = tank.rect.top - self.rect.height
  elif self.direction == "L":
   self.rect.left = tank.rect.left - tank.rect.width / 2 - self.rect.width / 2
   self.rect.top = tank.rect.top + tank.rect.width/2 -self.rect.width/2
  elif self.direction == "R":
   self.rect.left = tank.rect.left + tank.rect.width / 2
   self.rect.top = tank.rect.top + tank.rect.width/2 -self.rect.width/2
  speed = 10#速度
  alive = True#設(shè)置一個小標(biāo)簽 作判斷
 def bulletMove(self):#炮彈移動
  if self.direction == "U":
   if self.rect.top > 0 :#距離限制計(jì)算 self子彈對象本身 rect.top距離窗口上方 rect.left左側(cè)
    self.rect.top -= self.speed
   else:
    self.alive = False#此為<0時的情況 同下都是觸碰墻壁時的情況
  elif self.direction == "D":
   if self.rect.top < MainGame.screen_height - self.rect.height:#屏幕高度 - 子彈的高度
    self.rect.top += self.speed
   else:
    self.alive = False
  elif self.direction == "L":
   if self.rect.left > 0:
    self.rect.left -= self.speed
   else:
    self.alive = False
  elif self.direction == "R":
   if self.rect.left < MainGame.screen_width - self.rect.width:
    self.rect.left += self.speed
   else:
    self.alive = False
 def hitEnemyTank(self):#我方子彈與敵方坦克相碰
  for etank in MainGame.EnemyTank_list:#敵方坦克列表
   if pygame.sprite.collide_rect(etank,self):#sprite中的相撞測試
    explode = Explode(etank)#產(chǎn)生一個爆炸效果
    MainGame.Explode_list.append(explode)
    self.alive = False
    etank.live = False
 def hitMyTank(self):
  if pygame.sprite.collide_rect(self,MainGame.Tank_p1):
   explode = Explode(MainGame.Tank_p1)
   MainGame.Explode_list.append(explode)
   MainGame.Tank_p1.alive = False
   self.alive = False
 def hitWalls(self):
  for wall in MainGame.wall_list:
   if pygame.sprite.collide_rect(wall,self):
    self.alive = False
    wall.hp -= 1
    if wall.hp <= 0:
     wall.live = False
 def display_bullet(self):#顯示子彈方法
  MainGame.window.blit(self.image,self.rect)#窗口寫入
class Explode:#爆炸效果
 def __init__(self,tank):
  self.step = 0
  self.rect = tank.rect
  self.images = [pygame.image.load("img/blast0.gif"),
      pygame.image.load("img/blast1.gif"),
      pygame.image.load("img/blast2.gif"),
      pygame.image.load("img/blast3.gif"),
      pygame.image.load("img/blast4.gif"),
      pygame.image.load("img/blast5.gif"),
      pygame.image.load("img/blast6.gif"),
      pygame.image.load("img/blast7.gif"),]
  self.live = True
  self.image = self.images[self.step]
 def display_explode(self):#顯示爆炸效果
  if self.step < len(self.images):
   MainGame.window.blit(self.image,self.rect)
   self.image = self.images[self.step]
   self.step += 1
  else:
   self.live = False
   self.step = 0
class Wall:
 def __init__(self,left,top):
  self.image = pygame.image.load("img/steels.gif")
  self.rect = self.image.get_rect()
 
  self.rect.left = left
  self.rect.top = top
  self.live = True
  self.hp = 3
 def displayWall(self):#顯示障礙物
  MainGame.window.blit(self.image,self.rect)
 
class Music:#音效
 def __init__(self,filename):
  self.filename = filename
  pygame.mixer.init()#混合器的初始
  pygame.mixer.music.load(self.filename)#加載音樂文件
 def play(self):
  pygame.mixer.music.play(loops=0)#播放音樂
 
MainGame().startGame()
            
          

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯(lián)系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發(fā)表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 紫云| 万荣县| 永春县| 九龙坡区| 阜城县| 黑山县| 桦川县| 顺义区| 吴旗县| 沾益县| 赞皇县| 库伦旗| 那曲县| 耒阳市| 宣化县| 内黄县| 巴楚县| 绥中县| 兴仁县| 张家口市| 巨野县| 扶绥县| 米脂县| 玛纳斯县| 平度市| 惠东县| 大新县| 吴川市| 祁东县| 丰城市| 徐州市| 台州市| 法库县| 兰坪| 青河县| 崇左市| 喀喇沁旗| 麟游县| 永顺县| 新乐市| 赤壁市|