简易坦克大战python版
# -*- coding:utf8 -*-
'''
*author:wasua
*purpose:学习python语言,其中的类以及pygame应用
*date:2019/04/20
''' '''
类:
sprite:
1.游戏主界面 2.坦克:我方坦克\敌方坦克
1.移动
2.发射炮弹
3.炮弹:大炮弹\小炮弹
1.撞到
2.爆炸(也是一个连续图片)
4.障碍物:
1.能否闯过
2.能否击毁
5.爆炸 ''' import pygame, sys, time
from random import randint class TankMain(object):
"""坦克大战的主窗口"""
Width = 1000
Height = 800
live_count = 4 # 3次复活机会
my_tank = None
#steel_wall = []
#block_wall = []
#grass_wall = []
wall=[]
my_tank_missile = []
enemy_list = pygame.sprite.Group()
enemy_missile_list = pygame.sprite.Group()
explode_list = [] # 开始游戏的方法
def startGame(self):
pygame.init()
# 创建一个平面,设置平面大小(宽,高),窗口的属性(0,RESIZEBLE,FULLSCREEN)
screem = pygame.display.set_mode((TankMain.Width, TankMain.Height), 0, 32)
# 设置窗口标题
pygame.display.set_caption('坦克大战')
for i in range(6):#此处应该编写一个函数来进行比较好
TankMain.wall.append(SteelsWall(screem, 100 + i * 60, 100))
TankMain.wall.append(BlockWall(screem, 700, 100 + i * 60))
TankMain.wall.append(GrassWall(screem, 500, 0 + i * 60))
TankMain.wall.append(GrassWall(screem,50,40)) #wall = TankMain.steel_wall + TankMain.grass_wall + TankMain.block_wall
TankMain.my_tank = My_TanK(screem)
for i in range(0, 20):
TankMain.enemy_list.add(Enemy_TanK(screem))
while True:
# if len(TankMain.enemy_list)<5:#地狱模式
# TankMain.enemy_list.add(Enemy_TanK(screem))
# 显示墙
for i in TankMain.wall:
i.display()
i.hit_tank()
i.hit_missile()
if not i.live:
TankMain.wall.remove(i)
pygame.display.update() # 此处不添加则会导致图片不显示
# 设置窗口填充(背景---RGB模式)
screem.fill((0, 0, 0))
# 显示左上角的文字
for index, text in enumerate(self.write_text(TankMain.enemy_list)):
screem.blit(text, (0, 5 + (15 * index)))
# screem.blit(self.write_text(TankMain.enemy_list),(0,0))
self.get_event(TankMain.my_tank, screem)
if TankMain.my_tank:
TankMain.my_tank.hit_enemy_missile()
if TankMain.my_tank and TankMain.my_tank.live:
TankMain.my_tank.display()
TankMain.my_tank.move()
else:
TankMain.my_tank = None
for enemy in TankMain.enemy_list:
enemy.display()
enemy.random_move()
enemy.random_fire()
for m in TankMain.my_tank_missile:
if m.live:
m.display()
m.hit_tank()
m.move()
else:
TankMain.my_tank_missile.remove(m) for m in TankMain.enemy_missile_list:
if m.live:
m.display()
m.move()
else:
TankMain.enemy_missile_list.remove(m) for explode in TankMain.explode_list:
explode.display()
# 显示重置
time.sleep(0.1)
pygame.display.update() # 关闭游戏
def stopGame(self):
sys.exit() # 屏幕左上角显示文字内容
def write_text(self, enemy_list):
# 定义字体
font = pygame.font.SysFont('微软雅黑', 15, (255, 255, 255))
# 根据字体创建一个文件图像
text_sf1 = font.render(u'敌方坦克数量为:%d' % len(enemy_list), True, (255, 255, 255))
text_sf2 = font.render(u'生命数量:%d' % (int(TankMain.live_count) - 1), True, (255, 255, 255))
return text_sf1, text_sf2 # 获取事件,敲击键盘,鼠标点击
def get_event(self, my_tank, screem):
for event in pygame.event.get():
if event.type == pygame.QUIT: # 我方坦克牺牲后不能按Esc恩退出
self.stopGame()
if event.type == pygame.KEYDOWN and (not TankMain.my_tank) and (
event.key == pygame.K_r or event.key == pygame.K_n): # 按n或r复活
TankMain.my_tank = My_TanK(screem) # 我方坦克不复活不可以按Esc退出
TankMain.live_count -= 1
if TankMain.live_count == 0:
sys.exit()
if event.type == pygame.KEYDOWN and my_tank:
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
my_tank.direction = "L"
my_tank.stop = False
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
my_tank.direction = "R"
my_tank.stop = False
if event.key == pygame.K_UP or event.key == pygame.K_w:
my_tank.direction = 'U'
my_tank.stop = False
if event.key == pygame.K_DOWN or event.key == pygame.K_x:
my_tank.direction = "D"
my_tank.stop = False
if event.key == pygame.K_ESCAPE:
self.stopGame()
if event.key == pygame.K_SPACE:
m = my_tank.fire()
m.good = True
TankMain.my_tank_missile.append(m)
if event.type == pygame.K_UP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN or event.key == pygame.K_a or event.key == pygame.K_d or event.key == pygame.K_w or event.key == pygame.K_x:
my_tank.stop = True
if event.type == pygame.MOUSEMOTION:
pass # 坦克大战中所有对象的父类
class BaseItem(pygame.sprite.Sprite):
def __init__(self, screem):
pygame.sprite.Sprite.__init__(self)
self.screem = screem def display(self):
if self.live:
self.image = self.images[self.direction]
self.screem.blit(self.image, self.rect) # 坦克类
class Tank(BaseItem):
Width = 48
Height = 48 def __init__(self, screem, left, top):
super().__init__(screem)
self.screem = screem
self.direction = "D" # 坦克默认方向向下(上下左右)
self.speed = 5 # 坦克移动速度
self.stop = False
self.images = {} # 坦克图集
self.images['L'] = pygame.image.load('image/enemytank/tankl.png')
self.images['R'] = pygame.image.load('image/enemytank/tankr.png')
self.images['U'] = pygame.image.load('image/enemytank/tanku.png')
self.images['D'] = pygame.image.load('image/enemytank/tankd.png')
self.image = self.images[self.direction]
self.rect = self.image.get_rect()
self.rect.left = left
self.rect.top = top
self.live = True # 觉得坦克是否存活
self.oldtop = self.rect.top
self.oldleft = self.rect.left
# 将坦克对相应图片显示在游戏窗口
def stay(self):
self.rect.left = self.oldleft
self.rect.top = self.oldtop
def move(self):
if not self.stop:
self.oldtop = self.rect.left
self.oldleft = self.rect.top
if self.direction == "L":
if self.rect.left > 0: # 坦克是否到达左边界
self.rect.left -= self.speed
else:
self.rect.left = 0
elif self.direction == "R":
if self.rect.right < TankMain.Width:
self.rect.right += self.speed
else:
self.rect.right = TankMain.Width
elif self.direction == "U":
if self.rect.top > 0:
self.rect.top -= self.speed
else:
self.rect.top = 0
elif self.direction == "D":
if self.rect.top < TankMain.Height:
self.rect.top += self.speed
else:
self.rect.top = TankMain.Height
else:
pass
def fire(self):
m = Missile(self.screem, self)
return m class My_TanK(Tank):
def __init__(self, screem):
super().__init__(screem, 275, 450)
self.images = {} # 坦克图集
self.images['L'] = pygame.image.load('image/my_tank/mytankl.png')
self.images['R'] = pygame.image.load('image/my_tank/mytankr.png')
self.images['U'] = pygame.image.load('image/my_tank/mytanku.png')
self.images['D'] = pygame.image.load('image/my_tank/mytankd.png')
self.image = self.images[self.direction]
self.rect = self.image.get_rect() def hit_enemy_missile(self):
hit_list = pygame.sprite.spritecollide(self, TankMain.enemy_missile_list, True)
for m in hit_list: # 我方坦克中弹
m.live = False
TankMain.enemy_missile_list.remove(m)
self.live = False
explode = Explode(self.screem, self.rect)
TankMain.explode_list.append(explode) class Enemy_TanK(Tank):
def __init__(self, screem):
super().__init__(screem, randint(0, TankMain.Height), randint(0, TankMain.Width))
self.step = randint(5, 10)
self.get_random_direction()
def get_random_direction(self):
r = randint(0, 4)
if r == 0:
self.stop = True
elif r == 1:
self.direction = 'L'
self.stop = False
elif r == 2:
self.direction = 'R'
self.stop = False
elif r == 3:
self.direction = 'U'
self.stop = False
elif r == 4:
self.direction = 'D'
self.stop = False
else:
pass
# 敌方坦克按随机方向连续移动多步才改变方向
def random_move(self):
if self.live:
if self.step == 0:
self.get_random_direction()
self.step = randint(5, 10)
else:
self.move()
self.step -= 1
def random_fire(self):
r = randint(0, 50)
if r > 45:
m = self.fire()
TankMain.enemy_missile_list.add(m)
else:
return class Missile(BaseItem):
Width = 8
Height = 8
def __init__(self, screem, tank):
# super().__init__(screem)坑
# print('error')
super().__init__(screem)
self.screem = screem
self.tank = tank
self.direction = tank.direction # 炮弹方向随坦克默认方向向下(上下左右)
self.speed = 60 # 炮弹移动速度
self.stop = False
self.images = {} # 坦克图集
self.images['L'] = pygame.image.load('image/missile/missile.png')
self.images['R'] = pygame.image.load('image/missile/missile.png')
self.images['U'] = pygame.image.load('image/missile/missile.png')
self.images['D'] = pygame.image.load('image/missile/missile.png')
self.image = self.images[self.direction]
self.rect = self.image.get_rect()
self.rect.left = tank.rect.left + (tank.Width - self.Width) / 2
self.rect.top = tank.rect.top + (tank.Height - self.Height) / 2
self.live = True # 决定炮弹是否存在
self.good = False
def move(self):
if self.live:
if self.direction == "L":
if self.rect.left > 0: # 坦克是否到达左边界
self.rect.left -= self.speed
else:
self.live = False
elif self.direction == "R":
if self.rect.right < TankMain.Width:
self.rect.right += self.speed
else:
self.live = False
elif self.direction == "U":
if self.rect.top > 0:
self.rect.top -= self.speed
else:
self.live = False
elif self.direction == "D":
if self.rect.top < TankMain.Height:
self.rect.top += self.speed
else:
self.live = False
else:
pass
# 炮弹击中坦克:我击中敌法、敌方击中我
def hit_tank(self):
if self.good: # 如果是我方炮弹
hit_list = pygame.sprite.spritecollide(self, TankMain.enemy_list, True) # 返回发生碰撞的列表
for e in hit_list:
e.live = False
TankMain.enemy_list.remove(e)
self.live = False
explode = Explode(self.screem, e.rect)
TankMain.explode_list.append(explode) else: # 如果是敌方炮弹
pass class Explode(BaseItem):
def __init__(self, screem, rect):
super().__init__(screem)
self.live = True
self.screem = screem
self.images = [pygame.image.load('image/explode/0.png'), \
pygame.image.load('image/explode/1.png'), \
pygame.image.load('image/explode/2.png'), \
pygame.image.load('image/explode/3.png'), \
pygame.image.load('image/explode/4.png'), \
pygame.image.load('image/explode/5.png'), \
]
self.step = 0
self.rect = rect # 爆炸的位置和发送爆炸前坦克位置一样,所以传入坦克位置 # 循环调用
def display(self):
if self.live:
if self.step == len(self.images): # 最后一张爆炸图片已经显示
self.live = False
else:
self.image = self.images[self.step]
self.screem.blit(self.image, self.rect)
self.step += 1 else:
pass '''
墙:
能否被击毁:
能否穿透
是否存活
草皮:
能穿过、不能击毁、一直存活
砖墙:
不能闯过、能击毁、被击毁则不存活
铁墙:
不能穿透、不能击毁、一直存活
''' class SteelsWall(BaseItem):
def __init__(self, screem, left, top):
super().__init__(screem)
self.live = True # 存活指标
self.via = False # 穿透指标
self.quality = True # 能否被炮弹击毁,但后来没用到
self.image = pygame.image.load('image/barrier/steels.png')
self.rect = self.image.get_rect()
self.rect.left = left # randint(10,500)
self.rect.top = top # randint(10,400)
def display(self):
if self.live:
self.screem.blit(self.image, self.rect)
else:
pass
def hit_tank(self):
if TankMain.my_tank and (not self.via) and self.live:
hit_list1 = pygame.sprite.collide_circle(self, TankMain.my_tank)
if hit_list1:
TankMain.my_tank.stop = True
TankMain.my_tank.stay() # 我方坦克,调用该函数有点小毛病,穿越?
else:
pass
if TankMain.enemy_list and (not self.via) and self.live:
hit_list2 = pygame.sprite.spritecollide(self, TankMain.enemy_list, False)
for e in hit_list2:
e.stop = True
e.stay() # 略有问题但不明显
def hit_missile(self):
missile_list = pygame.sprite.Group()
for i in TankMain.enemy_missile_list:
missile_list.add(i)
for j in (TankMain.my_tank_missile):
missile_list.add(j)
if missile_list and (not self.via) and self.live:
hit_list=pygame.sprite.spritecollide(self,missile_list,False)
for missile in hit_list:
missile.stop=True
missile.speed=0 class GrassWall(SteelsWall):
def __init__(self, screem, left, top):
super().__init__(screem, left, top)
self.image = pygame.image.load('image/barrier/grasss.png')
self.via = True class BlockWall(SteelsWall):
def __init__(self, screem, left, top):
super().__init__(screem, left, top)
self.image = pygame.image.load('image/barrier/walls.png')
self.quality = False
self.live = True
self.via = False
def hit_missile(self):
missile_group=pygame.sprite.Group()
for i in TankMain.enemy_missile_list:
missile_group.add(i)
for j in TankMain.my_tank_missile:
missile_group.add(j)
if missile_group:
hit_list=pygame.sprite.spritecollide(self,missile_group,False)
if hit_list:
self.live=False
for i in hit_list:
i.speed=0
i.stop=True
i.live=False
##提取码:f9lv if __name__ == '__main__':
game = TankMain()
game.startGame()
game.stopGame() ##完整素材代码
##链接:https://pan.baidu.com/s/1ux3lzD4y9MXSJJH049RCQg
简易坦克大战python版的更多相关文章
- Unity3D_(游戏)2D坦克大战 像素版
2D坦克大战 像素版 游戏规则: 玩家通过上.下.左.右移动坦克,空格键发射子弹 敌人AI出身时朝向己方大本营(未防止游戏快速结束,心脏上方三个单位障碍物设为刚体) 当玩家被击杀次数>=3 ...
- 坦克大战java版
吃了可以加血的血块类 import java.awt.*; public class Blood { //血块移动的路径 int[][] pos = { {450,250},{450,252},{45 ...
- Python版飞机大战
前面学了java用java写了飞机大战这次学完python基础后写了个python版的飞机大战,有兴趣的可以看下. 父类是飞行物类是所有对象的父类,setting里面是需要加载的图片,你可以换称自己的 ...
- 坦克大战-C语言-详注版
代码地址如下:http://www.demodashi.com/demo/14259.html 坦克大战-C语言-详注版 概述 本文详述了C语言版坦克大战游戏的原理以及实现方法,对游戏代码进行了详细的 ...
- Java坦克大战 (七) 之图片版
本文来自:小易博客专栏.转载请注明出处:http://blog.csdn.net/oldinaction 在此小易将坦克大战这个项目分为几个版本,以此对J2SE的知识进行回顾和总结,希望这样也能给刚学 ...
- Python开发坦克大战
Python不仅能开发网站,爬虫数据分析等,他其实也可以写游戏,接下来就给大家分享下坦克大战的代码: PS:很多人在学习Python的过程中,往往因为遇问题解决不了或者没好的教程从而导致自己放弃,为此 ...
- 手把手教你用Python实现“坦克大战”,附详细代码!
小时候玩的“坦克大战”,你还记得吗? 满满的回忆 ! 今天,我们使用Python以及强大的第三方库来实现一个简单的坦克大战游戏. 整体效果 环境依赖 python3.7 pygame1.9.6 ...
- 用 Python 写个坦克大战
坦克大战是一款策略类的平面射击游戏,于 1985 年由 Namco 游戏公司发布,尽管时至今日已经有了很多衍生类的游戏,但这款游戏仍然受到了相当一部分人的欢迎,本文我们看一下如何使用 Python 来 ...
- 【java版坦克大战---准备篇】 java 绘图
要写坦克大战当然要先画出坦克.java画图是基础. package com.game; import java.awt.*; import javax.swing.*; public class Pr ...
随机推荐
- 鼠标移动事件(跟随鼠标移动的div)
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...
- 准备Activiti开发环境
1.添加jar包 在activiti-5.13 -> wars 目录下 解压 activiti-rest.war ,导入WEB-INF\lib下所有包添加到classpath中. 由于使用的是O ...
- 139.00.004 Git学习-远程仓库之Github
参考Github官方HelloWorld入门教程 "有了远程仓库,妈妈再也不用担心我的硬盘了."--Git点读机 本章开始介绍Git的杀手级功能之一(注意是之一,也就是后面还有之二 ...
- android 实现类似微信缓存和即时更新好友头像
引言 使用微信时我们会发现,首次进入微信的好友列表时,会加载好友头像,但是再次进入时,就不用重新加载了,而且其他页面都不用重新加载,说明微信的好友头像是缓存在本地的,然后好友修改头像后,又会及时的更新 ...
- HTML5时代的纯前端上传图片预览及严格图片格式验证函数(转载)
原文地址:http://www.2cto.com/kf/201401/274752.html 一.要解决什么样的问题? 在写这个函数之前,有们童鞋在群里问如何纯前端严格验证图片格式.这在html5时代 ...
- 使用js时,如何获取系统当前时间并且得到格式为"yyyy年MM月"的日期
1.使用js时,如何获取系统当前时间并且得到格式为"yyyy年MM月"的日期: 1 var newdate = new Date(); 2 var nowyear = newdat ...
- 上传附件(图片base64)封装方法
上传附件(图片base64)封装方法 php 上传附件,base64 项目中封装的接口: public function error($msg){ header("Content-type: ...
- Zabbix监控mysql主从状态并实现报警
一.环境需求 主机A: zabbix-server 主机B: zabbix-agent/mysql从 二.主机B操作 1.添加监控脚本 vim /data/zabbix/mysql_slave_che ...
- July 21st 2017 Week 29th Friday
If you want to fly too high in relation to the horizon forget. 要想飞得高,就该把地平线忘掉. Always keep our eyes ...
- July 07th 2017 Week 27th Friday
Learn wisdom by the follies of others. 要从别人的愚行中学到智慧. How to become smart or what characters should a ...