面向对象学习之pygame坦克大战


Posted in Python onSeptember 11, 2019

经过一天多的奋战,查阅文献,参考别人的代码等等,完成了第一个面向对象的小项目,也深深体会到面向对象编程思想在游戏编程中所扮演的角色。

附上代码,参考了别人的代码,以及对他们代码的完善,又加上了自己的一些东西,收获颇深。

import pygame
import sys
import time
from pygame.locals import *
from random import randint
MOVE_SLEEP = 0.01
class MyTank:
 width = 600
 heights = 500
 speed = 10
 screen = 0
 myshells = []
 enemylist = []
 enemyshells = []
 grade = 0
 life = 3
 cnt = 0
 def startgame(self):
 pygame.init()
 self.screen = pygame.display.set_mode((self.width,self.heights),0,32)
 pygame.display.set_caption("bit tank")
 self.tank = Tank(self.screen,275,450)
 for i in range(6):
  self.enemylist.append(EnmeyTank(self.screen))
 while True:
  key = pygame.key.get_pressed()
  self.screen.fill((0,0,0))
  if key[K_LEFT]:
  self.tank.move('L')
  elif key[K_RIGHT]:
  self.tank.move('R')
  elif key[K_UP]:
  self.tank.move('U')
  elif key[K_DOWN]:
  self.tank.move('D')
  self.get_event()
  for shell in self.myshells:
  if shell.move() == True:
   self.myshells.remove(shell)
  shell.display()
  a = shell.hitTank()
  #子弹碰撞
  if a == True:
   if self.life >0:
   self.myshells.remove(shell)
   self.grade += 1
  #mytank碰撞
  if self.tank.live == True:
  if self.tank.hitTank():
   self.life -= 1
   if self.life <=0:
   self.tank.live =False
   else:self.tank = Tank(self.screen,275,450)
  #mytanke 碰撞子弹
  if self.tank.live == True:
  if self.tank.hitShell():
   self.life -= 1
   if self.life <=0:
   self.tank.live = False
   else:self.tank=Tank(self.screen,275,450)
  #敌方子弹击中我方坦克
  # 游戏结束
  if self.life <=0:
  self.gotGamePrint()
  for enemy in self.enemylist:
  enemy.move()
  print('move')
  enemy.display()
  # 添加敌方子弹
  self.cnt += 1
  if self.cnt % 100 ==0:
  for enemy in self.enemylist:
   self.enemyshells.append(enemy.fire())
  #判断敌方子弹碰撞
  for enemyshell in self.enemyshells:
  f = enemyshell.move()
  enemyshell.display()
  if f:
   self.enemyshells.remove(enemyshell)
  if len(self.enemylist)<6:
  self.enemylist.append(EnmeyTank(self.screen))
  self.screen.blit(self.getGrade(),(5,5))
  self.tank.display()
  pygame.display.update()
  time.sleep(0.02)
 def get_event(self):
 for event in pygame.event.get():
  if event.type == KEYDOWN:
  if event.key == K_SPACE:
   self.myshells.append(self.tank.fire())
  if event.key == K_ESCAPE:
   pass
 def getGrade(self):
 text = pygame.font.Font('./font/msyhbd.ttc',20).render("分数:{} 生命:{}".format(self.grade,self.life),True,(0,255,0))
 return text
 def gotGamePrint(self):
 text = pygame.font.Font('./font/msyh.ttc',70).render('game over!',True,(0,255,0))
 self.screen.blit(text,(100,200))
class Shell:
 width = 48
 height = 48
 live = True
 speed = 3
 def __init__(self,screen,tank):
 self.screen = screen
 self.image = pygame.image.load('./images/3.png')
 self.direction = tank.direction
 self.rect = self.image.get_rect()
 self.rect.left = tank.rect.left + (tank.width-self.width)/2.0+18
 # print(tank.rect.left,tank.width,self.width)
 self.rect.top = tank.rect.top + (tank.height - self.height)/2.0
 self.live = True
 def move(self):
 tag = self.isObstacle()
 if self.live == True:
  if self.direction == 'L' and self.direction not in tag:
  self.rect.left -= self.speed
  elif self.direction == 'R' and self.direction not in tag:
  self.rect.left += self.speed
  elif self.direction == 'U' and self.direction not in tag:
  self.rect.top -= self.speed
  elif self.direction == 'D' and self.direction not in tag:
  self.rect.top += self.speed
  else:
  pass
  if self.direction in tag:
  return True
  else:
  return False
 else:
  pass
 def display(self):
 # print(self.rect.left,self.rect.top)
 if self.live == True:
  self.screen.blit(self.image,self.rect)
 def isObstacle(self):
 tag = []
 if self.rect.left <=0:tag.append('L')
 if self.rect.left + self.width >= MyTank.width:tag.append('R')
 if self.rect.top <=0:tag.append('U')
 if self.rect.top + self.height >=MyTank.heights:tag.append('D')
 return tag
 def hitTank(self):
 hitList = pygame.sprite.spritecollide(self,MyTank.enemylist,False)
 for e in hitList:
  e.live = False
  MyTank.enemylist.remove(e)
  self.live = False
  return True
 return False
 def hitMytank(self):
 hitList = pygame.sprite.spritecollide(self,MyTank.tank,False)
 for e in hitList:
  e.live = False
  MyTank.life -= 1
  return True
class BaseTank:
 width = 50
 height = 50
 direction = 'U'
 live = True
 time = 0
 images = {}
 def __init__(self,screen,left,top):
 self.screen = screen
 self.images['L'] = pygame.image.load("images/04.jpg")
 self.images['R'] = pygame.image.load("images/02.jpg")
 self.images['U'] = pygame.image.load("images/01.jpg")
 self.images['D'] = pygame.image.load("images/03.jpg")
 self.image = self.images[self.direction]
 self.rect = self.image.get_rect()
 self.rect.left = left
 self.rect.top = top
 self.live = True # 坦克是否被消灭
 def isObstacle(self):
 tag = []
 if self.rect.left <= 0: tag.append('L')
 if self.rect.left + self.width >= MyTank.width: tag.append('R')
 if self.rect.top <= 0: tag.append('U')
 if self.rect.top + self.height >= MyTank.heights: tag.append('D')
 return tag
 def display(self):
 if self.live == True:
  self.image = self.images[self.direction]
  self.screen.blit(self.image, self.rect)
 def fire(self):
 m = Shell(self.screen,self)
 return m
class Tank(BaseTank):
 images = {}
 def __init__(self,screen,left,top):
 super().__init__(screen,275,450)
 self.screen = screen
 self.speed = 2
 self.images['L'] = pygame.image.load('./images/4.jpg')
 self.images['R'] = pygame.image.load('./images/2.jpg')
 self.images['U'] = pygame.image.load('./images/1.jpg')
 self.images['D'] = pygame.image.load('./images/3.jpg')
 self.image = self.images[self.direction]
 self.rect = self.image.get_rect()
 self.rect.top = top
 self.rect.left = left
 def move(self, direction):
 if self.live == True:
  tag = self.isObstacle()
  if direction == self.direction:
  if self.direction == 'L' and self.direction not in tag:
   self.rect.left -= self.speed
  elif self.direction == 'R' and self.direction not in tag:
   self.rect.left += self.speed
  elif self.direction == 'U' and self.direction not in tag:
   self.rect.top -= self.speed
  elif self.direction == 'D' and self.direction not in tag:
   self.rect.top += self.speed
  else:
   pass
  else:
  self.direction = direction
 def hitTank(self):
 hitList = pygame.sprite.spritecollide(self,MyTank.enemylist,False)
 for e in hitList:
  self.live = False
  return True
 return False
 def hitShell(self):
 hitlist = pygame.sprite.spritecollide(self, MyTank.enemyshells, False)
 for e in hitlist:
  self.live = False
  return True
 return False
class EnmeyTank(BaseTank):
 speed = 1
 def __init__(self,screen):
 super().__init__(screen,randint(1,5)*100,0)
 self.getdirection()
 self.step = 0
 def getdirection(self):
 self.direction = ['L','R','U','D'][randint(0,3)]
 def move(self):
 if self.live == True:
  if self.step == 0 or (self.direction in self.isObstacle()):
  self.getdirection()
  self.step = randint(0, 200)
  else:
  tag = self.isObstacle()
  if self.direction == 'L' and self.direction not in tag:
   self.rect.left -= self.speed
  elif self.direction == 'R' and self.direction not in tag:
   self.rect.left += self.speed
  elif self.direction == 'U' and self.direction not in tag:
   self.rect.top -= self.speed
  elif self.direction == 'D' and self.direction not in tag:
   self.rect.top += self.speed
  else:
   pass
  self.step -= 1
if __name__ == '__main__':
 main = MyTank()
 main.startgame()

文件主要有10张图片和2个字体文件,主坦克的四个形态,敌方坦克的四个形态,以及子弹等,10张图片。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现的数据结构与算法之队列详解
Apr 22 Python
python实现定时自动备份文件到其他主机的实例代码
Feb 23 Python
Django Web开发中django-debug-toolbar的配置以及使用
May 06 Python
用python实现k近邻算法的示例代码
Sep 06 Python
python opencv读mp4视频的实例
Dec 07 Python
django基于存储在前端的token用户认证解析
Aug 06 Python
基于python解线性矩阵方程(numpy中的matrix类)
Oct 21 Python
Python pandas自定义函数的使用方法示例
Nov 20 Python
Python数据正态性检验实现过程
Apr 18 Python
Pandas实现一列数据分隔为两列
May 18 Python
keras自定义回调函数查看训练的loss和accuracy方式
May 23 Python
使用Python判断一个文件是否被占用的方法教程
Dec 16 Python
Python整数与Numpy数据溢出问题解决
Sep 11 #Python
python中通过selenium简单操作及元素定位知识点总结
Sep 10 #Python
用Python画一个LinkinPark的logo代码实例
Sep 10 #Python
Pytorch修改ResNet模型全连接层进行直接训练实例
Sep 10 #Python
django drf框架自带的路由及最简化的视图
Sep 10 #Python
Pytorch中accuracy和loss的计算知识点总结
Sep 10 #Python
python3.7环境下安装Anaconda的教程图解
Sep 10 #Python
You might like
第八节 访问方式 [8]
2006/10/09 PHP
PHP字符串的编码问题的详细介绍
2013/04/27 PHP
PHP实现把数字ID转字母ID
2013/08/12 PHP
thinkphp模板赋值与替换实例简述
2014/11/24 PHP
推荐几个开源的微信开发项目
2014/12/28 PHP
PHP实现简单汉字验证码
2015/07/28 PHP
[原创]PHP实现逐行删除文件右侧空格的方法
2015/12/25 PHP
基于yaf框架和uploadify插件,做的一个导入excel文件,查看并保存数据的功能
2017/01/24 PHP
PHP使用curl_multi_select解决curl_multi网页假死问题的方法
2018/08/15 PHP
Json对象与Json字符串互转(4种转换方式)
2013/03/27 Javascript
jquery使用淘宝接口跨域查询手机号码归属地实例
2013/11/28 Javascript
jquery的live使用注意事项
2014/02/18 Javascript
让angularjs支持浏览器自动填表
2014/11/10 Javascript
深入理解JavaScript系列(42):设计模式之原型模式详解
2015/03/04 Javascript
JS+CSS实现简单的二级下拉导航菜单效果
2015/09/21 Javascript
js基础之DOM中元素对象的属性方法详解
2016/10/28 Javascript
JS实现图片上传预览功能
2016/11/21 Javascript
Vue组件实例间的直接访问实现代码
2017/08/20 Javascript
你或许不知道的一些npm实用技巧
2019/07/04 Javascript
node.js中path路径模块的使用方法实例分析
2020/02/13 Javascript
vue实现标签云效果的示例
2020/11/09 Javascript
python每隔N秒运行指定函数的方法
2015/03/16 Python
Python使用os.listdir()和os.walk()获取文件路径与文件下所有目录的方法
2019/04/01 Python
基于Python2、Python3中reload()的不同用法介绍
2019/08/12 Python
python之MSE、MAE、RMSE的使用
2020/02/24 Python
使用Keras 实现查看model weights .h5 文件的内容
2020/06/09 Python
利用Python将多张图片合成视频的实现
2020/11/23 Python
用css3实现当鼠标移进去时当前亮其他变灰效果
2014/04/08 HTML / CSS
HTML5 embed 标签使用方法介绍
2013/08/13 HTML / CSS
在线服装零售商:SheIn
2016/07/22 全球购物
英国最大的在线运动补充剂商店:Discount Supplements
2017/06/03 全球购物
Linux管理员面试经常问道的相关命令
2014/12/12 面试题
精通CAD能手自荐书
2014/01/31 职场文书
《只有一个地球》教学反思
2014/02/14 职场文书
车辆工程专业求职信
2014/06/14 职场文书
PHP中国际化的字符串排序和比较对象详解
2021/08/23 PHP