当前位置:网站首页>【Pygame小游戏】这款经典的炸弹人超能游戏上线,你爱了嘛?(附源码)
【Pygame小游戏】这款经典的炸弹人超能游戏上线,你爱了嘛?(附源码)
2022-06-10 22:42:00 【程序员梨子】
前言
作者 :“程序员梨子”
**文章简介 **:本篇文章主要是写了pygame实现炸弹人的小游戏!
**文章源码免费获取 : 为了感谢每一个关注我的小可爱每篇文章的项目源码都是无
偿分享滴
点这里蓝色这行字体自取,需要什么源码记得说标题名字哈!私信我也可!
欢迎小伙伴们 点赞、收藏、留言
正文
在现在这个浮躁的年代:小编每次登陆王者荣耀,还有每次登陆刺激战场Z!
看着里面的聊天界面,各种代打、各种的找cp。小小编觉得,我们已经失去了玩游戏的初心。
接下来,小编将带领你们走回童年时光,一起领略我们当初玩4399的单纯与天真!

那今天就带大家回忆一下童年也做一款经典的炸弹人的小游戏!
1)素材
游戏规则还清楚哈, 我就不多做介绍了不清楚玩法的可以百度下下!
首先准备好相应的素材:【部分如下】

炸弹人主程序:
开始的界面如下:

定义地图类:
class mapParser():
def __init__(self, mapfilepath, bg_paths, wall_paths, blocksize, **kwargs):
self.instances_list = self.__parse(mapfilepath)
self.bg_paths = bg_paths
self.wall_paths = wall_paths
self.blocksize = blocksize
self.height = len(self.instances_list)
self.width = len(self.instances_list[0])
self.screen_size = (blocksize * self.width, blocksize * self.height)
'''地图画到屏幕上'''
def draw(self, screen):
for j in range(self.height):
for i in range(self.width):
instance = self.instances_list[j][i]
if instance == 'w':
elem = Wall(self.wall_paths[0], [i, j], self.blocksize)
elif instance == 'x':
elem = Wall(self.wall_paths[1], [i, j], self.blocksize)
elif instance == 'z':
elem = Wall(self.wall_paths[2], [i, j], self.blocksize)
elif instance == '0':
elem = Background(self.bg_paths[0], [i, j], self.blocksize)
elif instance == '1':
elem = Background(self.bg_paths[1], [i, j], self.blocksize)
elif instance == '2':
elem = Background(self.bg_paths[2], [i, j], self.blocksize)
else:
raise ValueError('instance parse error in mapParser.draw...')
elem.draw(screen)
'''随机获取一个空地'''
def randomGetSpace(self, used_spaces=None):
while True:
i = random.randint(0, self.width-1)
j = random.randint(0, self.height-1)
coordinate = [i, j]
if used_spaces and coordinate in used_spaces:
continue
instance = self.instances_list[j][i]
if instance in ['0', '1', '2']:
break
return coordinate
'''根据坐标获取元素类型'''
def getElemByCoordinate(self, coordinate):
return self.instances_list[coordinate[1]][coordinate[0]]
'''解析.map文件'''
def __parse(self, mapfilepath):
instances_list = []
with open(mapfilepath) as f:
for line in f.readlines():
instances_line_list = []
for c in line:
if c in ['w', 'x', 'z', '0', '1', '2']:
instances_line_list.append(c)
instances_list.append(instances_line_list)
return instances_list定义必要的一些精灵类:角色,水果等等。
'''墙类'''
class Wall(pygame.sprite.Sprite):
def __init__(self, imagepath, coordinate, blocksize, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(imagepath)
self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
self.coordinate = coordinate
self.blocksize = blocksize
'''画到屏幕上'''
def draw(self, screen):
screen.blit(self.image, self.rect)
return True
'''背景类'''
class Background(pygame.sprite.Sprite):
def __init__(self, imagepath, coordinate, blocksize, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(imagepath)
self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
self.coordinate = coordinate
self.blocksize = blocksize
'''画到屏幕上'''
def draw(self, screen):
screen.blit(self.image, self.rect)
return True
'''水果类'''
class Fruit(pygame.sprite.Sprite):
def __init__(self, imagepath, coordinate, blocksize, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.kind = imagepath.split('/')[-1].split('.')[0]
if self.kind == 'banana':
self.value = 5
elif self.kind == 'cherry':
self.value = 10
else:
raise ValueError('Unknow fruit %s...' % self.kind)
self.image = pygame.image.load(imagepath)
self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
self.coordinate = coordinate
self.blocksize = blocksize
'''画到屏幕上'''
def draw(self, screen):
screen.blit(self.image, self.rect)
return True
'''炸弹类'''
class Bomb(pygame.sprite.Sprite):
def __init__(self, imagepath, coordinate, blocksize, digitalcolor, explode_imagepath, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(imagepath)
self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
self.explode_imagepath = explode_imagepath
self.rect = self.image.get_rect()
# 像素位置
self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
# 坐标(元素块为单位长度)
self.coordinate = coordinate
self.blocksize = blocksize
# 爆炸倒计时
self.explode_millisecond = 6000 * 1 - 1
self.explode_second = int(self.explode_millisecond / 1000)
self.start_explode = False
# 爆炸持续时间
self.exploding_count = 1000 * 1
# 炸弹伤害能力
self.harm_value = 1
# 该炸弹是否还存在
self.is_being = True
self.font = pygame.font.SysFont('Consolas', 20)
self.digitalcolor = digitalcolor
'''画到屏幕上'''
def draw(self, screen, dt, map_parser):
if not self.start_explode:
# 爆炸倒计时
self.explode_millisecond -= dt
self.explode_second = int(self.explode_millisecond / 1000)
if self.explode_millisecond < 0:
self.start_explode = True
screen.blit(self.image, self.rect)
text = self.font.render(str(self.explode_second), True, self.digitalcolor)
rect = text.get_rect(center=(self.rect.centerx-5, self.rect.centery+5))
screen.blit(text, rect)
return False
else:
# 爆炸持续倒计时
self.exploding_count -= dt
if self.exploding_count > 0:
return self.__explode(screen, map_parser)
else:
self.is_being = False
return False
'''爆炸效果'''
def __explode(self, screen, map_parser):
explode_area = self.__calcExplodeArea(map_parser.instances_list)
for each in explode_area:
image = pygame.image.load(self.explode_imagepath)
image = pygame.transform.scale(image, (self.blocksize, self.blocksize))
rect = image.get_rect()
rect.left, rect.top = each[0] * self.blocksize, each[1] * self.blocksize
screen.blit(image, rect)
return explode_area
'''计算爆炸区域'''
def __calcExplodeArea(self, instances_list):
explode_area = []
# 区域计算规则为墙可以阻止爆炸扩散, 且爆炸范围仅在游戏地图范围内
for ymin in range(self.coordinate[1], self.coordinate[1]-5, -1):
if ymin < 0 or instances_list[ymin][self.coordinate[0]] in ['w', 'x', 'z']:
break
explode_area.append([self.coordinate[0], ymin])
for ymax in range(self.coordinate[1]+1, self.coordinate[1]+5):
if ymax >= len(instances_list) or instances_list[ymax][self.coordinate[0]] in ['w', 'x', 'z']:
break
explode_area.append([self.coordinate[0], ymax])
for xmin in range(self.coordinate[0], self.coordinate[0]-5, -1):
if xmin < 0 or instances_list[self.coordinate[1]][xmin] in ['w', 'x', 'z']:
break
explode_area.append([xmin, self.coordinate[1]])
for xmax in range(self.coordinate[0]+1, self.coordinate[0]+5):
if xmax >= len(instances_list[0]) or instances_list[self.coordinate[1]][xmax] in ['w', 'x', 'z']:
break
explode_area.append([xmax, self.coordinate[1]])
return explode_area
'''角色类'''
class Hero(pygame.sprite.Sprite):
def __init__(self, imagepaths, coordinate, blocksize, map_parser, **kwargs):
pygame.sprite.Sprite.__init__(self)
self.imagepaths = imagepaths
self.image = pygame.image.load(imagepaths[-1])
self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
self.coordinate = coordinate
self.blocksize = blocksize
self.map_parser = map_parser
self.hero_name = kwargs.get('hero_name')
# 生命值
self.health_value = 50
# 炸弹冷却时间
self.bomb_cooling_time = 5000
self.bomb_cooling_count = 0
# 随机移动冷却时间(仅AI电脑用)
self.randommove_cooling_time = 100
self.randommove_cooling_count = 0
'''角色移动'''
def move(self, direction):
self.__updateImage(direction)
if direction == 'left':
if self.coordinate[0]-1 < 0 or self.map_parser.getElemByCoordinate([self.coordinate[0]-1, self.coordinate[1]]) in ['w', 'x', 'z']:
return False
self.coordinate[0] = self.coordinate[0] - 1
elif direction == 'right':
if self.coordinate[0]+1 >= self.map_parser.width or self.map_parser.getElemByCoordinate([self.coordinate[0]+1, self.coordinate[1]]) in ['w', 'x', 'z']:
return False
self.coordinate[0] = self.coordinate[0] + 1
elif direction == 'up':
if self.coordinate[1]-1 < 0 or self.map_parser.getElemByCoordinate([self.coordinate[0], self.coordinate[1]-1]) in ['w', 'x', 'z']:
return False
self.coordinate[1] = self.coordinate[1] - 1
elif direction == 'down':
if self.coordinate[1]+1 >= self.map_parser.height or self.map_parser.getElemByCoordinate([self.coordinate[0], self.coordinate[1]+1]) in ['w', 'x', 'z']:
return False
self.coordinate[1] = self.coordinate[1] + 1
else:
raise ValueError('Unknow direction %s...' % direction)
self.rect.left, self.rect.top = self.coordinate[0] * self.blocksize, self.coordinate[1] * self.blocksize
return True
'''随机行动(AI电脑用)'''
def randomAction(self, dt):
# 冷却倒计时
if self.randommove_cooling_count > 0:
self.randommove_cooling_count -= dt
action = random.choice(['left', 'left', 'right', 'right', 'up', 'up', 'down', 'down', 'dropbomb'])
flag = False
if action in ['left', 'right', 'up', 'down']:
if self.randommove_cooling_count <= 0:
flag = True
self.move(action)
self.randommove_cooling_count = self.randommove_cooling_time
elif action in ['dropbomb']:
if self.bomb_cooling_count <= 0:
flag = True
self.bomb_cooling_count = self.bomb_cooling_time
return action, flag
'''生成炸弹'''
def generateBomb(self, imagepath, digitalcolor, explode_imagepath):
return Bomb(imagepath=imagepath, coordinate=copy.deepcopy(self.coordinate), blocksize=self.blocksize, digitalcolor=digitalcolor, explode_imagepath=explode_imagepath)
'''画到屏幕上'''
def draw(self, screen, dt):
# 冷却倒计时
if self.bomb_cooling_count > 0:
self.bomb_cooling_count -= dt
screen.blit(self.image, self.rect)
return True
'''吃水果'''
def eatFruit(self, fruit_sprite_group):
eaten_fruit = pygame.sprite.spritecollide(self, fruit_sprite_group, True, None)
for fruit in eaten_fruit:
self.health_value += fruit.value
'''更新角色朝向'''
def __updateImage(self, direction):
directions = ['left', 'right', 'up', 'down']
idx = directions.index(direction)
self.image = pygame.image.load(self.imagepaths[idx])
self.image = pygame.transform.scale(self.image, (self.blocksize, self.blocksize))
效果如下:


这精致的画面还可以吧~哈哈哈啊 快夸我快夸我~
总结
安啦!文章就写到这里,你们的支持是我最大的动力,记得三连哦~
关注小编获取更多精彩内容!记得点击传送门哈
记得三连哦! 如需打包好的源码+素材免费分享滴!!传送门
边栏推荐
- LabVIEW中创建毫秒时间标识
- Simple impedance matching circuit and formula
- LabVIEW和VDM提取色彩和生成灰度图像
- Classic sentences in Yi Shu's works
- 【Pygame小游戏】别找了,休闲游戏专题来了丨泡泡龙小程序——休闲游戏研发推荐
- Build TAR model using beersales data set in TSA package
- IGBT and third generation semiconductor SiC double pulse test scheme
- BGP - route map extension (explanation + configuration)
- 怎么生成自动参考文献(简单 有图)
- Is it safe for changtou school to open an account? Is it reliable?
猜你喜欢

LeetCode 501 :二叉搜索树中的众数

示波器刷新率怎么测量

LabVIEW确定控件在显示器坐标系中的位置

【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦

The time (in minutes) required for a group of workers to cooperate to complete the assembly process of a part are as follows:

LabVIEW determines the position of the control in the display coordinate system

LabVIEW用VISA Read函数来读取USB中断数据

LabVIEW在波形图或波形图表上显示时间和日期

LabVIEW获取IMAQ Get Last Event坐标

黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
随机推荐
2022 college entrance examination quantitative paper | please answer the questions for quantitative candidates
LabVIEW open other exe programs
Fiddler simulates low-speed network environment
MySQL table mechanism
LeetCode 501 :二叉搜索樹中的眾數
1. open the R program, and use the apply function to calculate the sum of 1 to 12 in the sequence of every 3 numbers. That is, calculate 1+4+7+10=? 2+5+8+11=?, 3+6+9+12=?
Binary tree pruning
[paper sharing] pata: fuzzing with path aware Taint Analysis
Data and information resource sharing platform (V)
Difference between oscilloscope and spectrum analyzer
Usage of C tryparse
LabVIEW error "memory full - Application stopped on node"
PHP implementation of iframe cross site text replacement / iframe website text replacement
LabVIEW使用MathScript Node或MATLAB脚本时出现错误1046
归并排序
Two debugging techniques in embedded software development
Easyrecovery15 simple and convenient data recovery tool
Exception 0xc00000005 code occurred when LabVIEW called DLL
Classic sentences in Yi Shu's works
R language to draw two-dimensional normal distribution density surface;
