今天手把手教你做一个Python版的迷宫小游戏

相关文件

想学Python的小伙伴可以关注小编的公众号【Python日志】
有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!!
需要源码的小伙伴在公众号里面回复:迷宫小游戏
Python学习交流群:773162165

开发环境

Python版本:3.7.8
相关模块:
requests模块;
tqdm模块;
pyfreeproxy模块;
pyecharts模块;
以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

代码实现

首先肯定少不了的就是记录我们的一个“战绩”的环节,那就是记录我们的关卡数还有通过了多少关!很简单的代码实现!

# 记录关卡数
num_levels = 0
# 记录最少用了多少步通关
best_scores = 'None'

然后就是我们的一个关卡循环切换的一个过程:
包含我们的地图随机生成、步数的统计,还有我们游戏中的人物移动的方向

# 关卡循环切换
	while True:
		num_levels += 1
		clock = pygame.time.Clock()
		screen = pygame.display.set_mode(cfg.SCREENSIZE)
		# --随机生成关卡地图
		maze_now = RandomMaze(cfg.MAZESIZE, cfg.BLOCKSIZE, cfg.BORDERSIZE)
		# --生成hero
		hero_now = Hero(cfg.HEROPICPATH, [0, 0], cfg.BLOCKSIZE, cfg.BORDERSIZE)
		# --统计步数
		num_steps = 0
		# --关卡内主循环
		while True:
			dt = clock.tick(cfg.FPS)
			screen.fill((255, 255, 255))
			is_move = False
			# ----↑↓←→控制hero
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					pygame.quit()
					sys.exit(-1)
				elif event.type == pygame.KEYDOWN:
					if event.key == pygame.K_UP:
						is_move = hero_now.move('up', maze_now)
					elif event.key == pygame.K_DOWN:
						is_move = hero_now.move('down', maze_now)
					elif event.key == pygame.K_LEFT:
						is_move = hero_now.move('left', maze_now)
					elif event.key == pygame.K_RIGHT:
						is_move = hero_now.move('right', maze_now)
			num_steps += int(is_move)
			hero_now.draw(screen)
			maze_now.draw(screen)

然后就是一些类的实现过程:

精灵类

'''定义hero'''
class Hero(pygame.sprite.Sprite):
	def __init__(self, imagepath, coordinate, block_size, border_size, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.image = pygame.image.load(imagepath)
		self.image = pygame.transform.scale(self.image, (block_size, block_size))
		self.rect = self.image.get_rect()
		self.rect.left, self.rect.top = coordinate[0] * block_size + border_size[0], coordinate[1] * block_size + border_size[1]
		self.coordinate = coordinate
		self.block_size = block_size
		self.border_size = border_size
	'''移动'''
	def move(self, direction, maze):
		blocks_list = maze.blocks_list
		if direction == 'up':
			if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[0]:
				return False
			else:
				self.coordinate[1] = self.coordinate[1] - 1
				return True
		elif direction == 'down':
			if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[1]:
				return False
			else:
				self.coordinate[1] = self.coordinate[1] + 1
				return True
		elif direction == 'left':
			if blocks_list[self.coordinate[1]][self.coordinate[0]].has_walls[2]:
				return False
			else:
				self.coordinate[0] = self.coordinate[0] - 1
				
  • 4
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值