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

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

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

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张图片。

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

(0)

相关推荐

  • python+pygame实现坦克大战

    本文实例为大家分享了python+pygame实现坦克大战的具体代码,供大家参考,具体内容如下 一.首先导入pygame库 二.源码分享 #coding=utf-8 import pygame import time import random from pygame.sprite import Sprite SCREEN_WIDTH=800 SCREEN_HEIGHT=500 BG_COLOR=pygame.Color(0,0,0) TEXT_COLOR=pygame.Color(255,0,

  • python实现坦克大战游戏 附详细注释

    本文实例为大家分享了python实现坦克大战的具体代码,供大家参考,具体内容如下 #功能实现游戏主窗口 import pygame,time,random#导入模块 _display = pygame.display#赋值给一个变量 调用时方便 color_red = pygame.Color(255,0,0)#同上 v class MainGame(object): screen_width = 900#游戏界面宽度 screen_height = 550#界面的高度 Tank_p1 = No

  • python使用pygame模块实现坦克大战游戏

    本文实例为大家分享了pygame模块实现坦克大战游戏的具体代码,供大家参考,具体内容如下 首先,第一步,游戏简单素材的准备. 炮弹,炮弹,坦克移动.音乐-开火素材. 其次,思路整理. 我们需要几个类,分别是玩家类,敌人类,炮弹类及地图类,开始游戏界面以及结束界面,血条等等. 开始coding. 主函数,new一个对象(java乱入emmm),声明一个对象. # encoding : utf-8 # anthor : comi from gameloop import * from pygame

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

    经过一天多的奋战,查阅文献,参考别人的代码等等,完成了第一个面向对象的小项目,也深深体会到面向对象编程思想在游戏编程中所扮演的角色. 附上代码,参考了别人的代码,以及对他们代码的完善,又加上了自己的一些东西,收获颇深. import pygame import sys import time from pygame.locals import * from random import randint MOVE_SLEEP = 0.01 class MyTank: width = 600 heig

  • Pygame坦克大战游戏开发实战详解代码

    导语 哈喽!哈喽——我是木木子 今天来升级下之前写的坦克大战游戏嘛,哈哈哈 其实也不算是修改,就是稍微的调试一下!​​ 因为之前写的界面都是英文的 ,有的小伙伴儿英文一点儿都不会的可能看着别扭,今天来一款中 文版的给大家嘛! 俗话说的好:“雨露均沾”.哈哈哈.jpg 小简介: <坦克大战>,1985年由日本开发商南梦宫(Namco)开发,是第一款可以双打的红白机游戏. 当时使用的还是小霸王. 很多小朋友以学习的名义买了以后偷偷打的打游戏还被家长发现了有 没得! <坦克大战>红白机原

  • python+pygame实现坦克大战小游戏的示例代码(可以自定义子弹速度)

    python+pygame实现坦克大战小游戏-可以自定义子弹速度: 运行环境–python3.7.pycharm: 源码需要请:点赞留言邮箱: 正常版子弹速度: 普通速度版 加速版子弹速度: 子弹加速版 另外还有多种道具,支持两人一起玩.main()方法如下: def main(): pygame.init() pygame.mixer.init() resolution = 630, 630 screen = pygame.display.set_mode(resolution) pygame

  • python实现简单坦克大战

    基于对面向对象编程的思想完成简单的坦克大战游戏.主要目的锻炼面相对象编程思想 同样的在使用python进行游戏编写时需要安装pygame模块 安装方法: pycharm安装方式:File --> setting 游戏中的主要对象有: 坦克父类:BaseTank 我方坦克:HeroTank 敌方坦克:EnemyTank 子弹类:Bullet 爆炸类:Explode 墙类:Wall 主进程:MainGame 定义一个精灵类: # 定义一个精灵类 class BaseItem(Sprite): def

  • 基于python实现坦克大战游戏

    本文实例为大家分享了python实现坦克大战游戏的具体代码,供大家参考,具体内容如下 游戏界面 pygame游戏引擎的安装 pip安装 windows + R --> cmd --> 命令行输入 pip install 模块名==版本号 pycharm中安装 File --> setting --> Project --> Project Interpreter --> 右侧 + install --> 搜索框输入pygame --> 下方 installP

  • 经典再现 基于JAVA平台开发坦克大战游戏

    一.需求描述  1.功能性需求 在功能需求分析阶段,我们的主要任务是指定系统必须提供哪些服务,定义软件完成哪些功能,提供给那些人使用,功能需求是软件开发的一项基本需求,是需求分析必不可少的一部分.坦克大战是一款经典游戏了,本游戏学习了一些前辈们的经验,整体来说讲,游戏分为敌我双方,主要参与战斗的坦克有玩家控制,敌人坦克可以智能随机出现在屏幕上,并且移动,发射一定数量的子弹:玩家可以在规定的区域内随意移动坦克,当有子弹击中玩家时,玩家死亡,游戏结束:敌人坦克智能运行,敌方坦克由于需要具有一定智能性

  • python实现坦克大战

    本文实例为大家分享了python实现坦克大战的具体代码,供大家参考,具体内容如下 本游戏制作代码量较大 具体代码与图片声源可以在我的GitHub中下载 github地址 下面来看看然后利用python做一个坦克大战游戏 创建子弹类 import pygame class Bullet(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.bullet_up = pygame.imag

随机推荐