面向对象学习之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爬取读者并制作成PDF
Mar 10 Python
详解Python中用于计算指数的exp()方法
May 14 Python
基于python(urlparse)模板的使用方法总结
Oct 13 Python
django定期执行任务(实例讲解)
Nov 03 Python
Python实现KNN(K-近邻)算法的示例代码
Mar 05 Python
PyQt5中多线程模块QThread使用方法的实现
Jan 31 Python
Python 读取WAV音频文件 画频谱的实例
Mar 14 Python
python使用信号量动态更新配置文件的操作
Apr 01 Python
Python新手学习装饰器
Jun 04 Python
Python通过递归函数输出嵌套列表元素
Oct 15 Python
利用python进行文件操作
Dec 04 Python
pandas apply使用多列计算生成新的列实现示例
Feb 24 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
SONY ICF-SW7600的电路分析
2021/03/02 无线电
开发大型PHP项目的方法
2006/10/09 PHP
php分页思路以及在ZF中的使用
2012/05/30 PHP
PHP跳转页面的几种实现方法详解
2013/06/08 PHP
PHP+Mysql+jQuery实现发布微博程序 php篇
2015/10/15 PHP
CI框架整合smarty步骤详解
2016/05/19 PHP
Thinkphp5 微信公众号token验证不成功的原因及解决方法
2017/11/12 PHP
js类后台管理菜单类-MenuSwitch
2007/09/12 Javascript
ImageFlow可鼠标控制图片滚动
2008/01/30 Javascript
20款非常优秀的 jQuery 工具提示插件 推荐
2012/07/15 Javascript
js、css、img等浏览器缓存问题的2种解决方案
2013/10/23 Javascript
JS截取字符串常用方法详细整理
2013/10/28 Javascript
JavaScript中this关键词的使用技巧、工作原理以及注意事项
2014/05/20 Javascript
js对象继承之原型链继承实例
2015/01/10 Javascript
浅析Nodejs npm常用命令
2016/06/14 NodeJs
js+css3制作时钟特效
2016/10/16 Javascript
jquery实现放大镜简洁代码(推荐)
2017/06/08 jQuery
element-ui 远程搜索组件el-select在项目中组件化的实现代码
2019/12/04 Javascript
解决Vue 给mapState中定义的属性赋值报错的问题
2020/06/22 Javascript
利用PHP实现递归删除链表元素的方法示例
2020/10/23 Javascript
python 环境变量和import模块导入方法(详解)
2017/07/11 Python
Python使用matplotlib绘图无法显示中文问题的解决方法
2018/03/14 Python
pygame游戏之旅 创建游戏窗口界面
2018/11/20 Python
详解将Pandas中的DataFrame类型转换成Numpy中array类型的三种方法
2019/07/06 Python
python3 实现口罩抽签的功能
2020/03/11 Python
python topk()函数求最大和最小值实例
2020/04/02 Python
python+selenium+chromedriver实现爬虫示例代码
2020/04/10 Python
Python内置异常类型全面汇总
2020/05/28 Python
python中Array和DataFrame相互转换的实例讲解
2021/02/03 Python
HTML5 3D衣服摇摆动画特效
2016/03/17 HTML / CSS
培训班开班仪式主持词
2014/03/28 职场文书
乡镇党委书记个人整改措施
2014/09/15 职场文书
龙门石窟导游词
2015/02/02 职场文书
2015年秘书个人工作总结
2015/04/25 职场文书
陈斌强事迹观后感
2015/06/17 职场文书
节水宣传标语口号
2015/12/26 职场文书