当前位置:网站首页>【Pygame小游戏】不怕你走不过系列:极致AI走迷宫,学习完带你打开新世界大门~(附游戏源码)
【Pygame小游戏】不怕你走不过系列:极致AI走迷宫,学习完带你打开新世界大门~(附游戏源码)
2022-06-10 22:42:00 【程序员梨子】
前言
作者 :“程序员梨子”
**文章简介 **:本篇文章主要是写了pygame实现AI版五子棋的小游戏!
**文章源码免费获取 : 为了感谢每一个关注我的小可爱每篇文章的项目源码都是无
偿分享滴
点这里蓝色这行字体自取,需要什么源码记得说标题名字哈!私信我也可!
欢迎小伙伴们 点赞、收藏、留言
正文
哈喽!哈喽我是梨子,每日更新来啦——
大家有玩过迷宫小游戏嘛?一般在还是小孩子的时候,家里的长辈都会跟家里的小孩儿一起玩儿一
些亲子游戏、比如大家最熟悉的一款《走迷宫小游戏》啦~锻炼脑力特别棒!
今天,让我们发挥想象力,一起用代码做一款AI版本的迷宫吧!

一、游戏思路
本文小程序用递归的方法解决迷宫问题,加入了可以自动生成迷宫,但有些问题还不是很明白生成
迷宫用了很笨的方法,在生成20行、列以上的迷宫时会很慢啦~
就简单的研究一下,之后有更好的会继续学了给大家更新滴!
1)效果展示


2)主程序
代码共主要有三块,太多了所以这里只展示主程序的代码,完整的见文末公众号哈!
import random
import pygame
FPS = 60
ROW = 10
COL = 10
BLOCK = 20
BORDER = 20
SCREEN_WIDTH = COL * BLOCK + BORDER * 2
SCREEN_HEIGHT = ROW * BLOCK + BORDER * 2
IMPOSSIBLE_COLOR = (128, 128, 128)
POSSIBLE_COLOR = (76, 141, 174)
ROUTE_COLOR = (12, 137, 24)
# noinspection PyPep8Naming
class DrawMaze(object):
def __init__(self):
self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # 创建屏幕对象
pygame.display.set_caption('{}*{} Maze'.format(ROW, COL)) # 窗口标题
self.clock = pygame.time.Clock()
self.color = POSSIBLE_COLOR # 首先设置路径块与可能块的颜色相同
self.maze = MakeMaze().create(ROW, COL)
self.no_route = True
def display(self):
""" 在窗口中显示迷宫,按任意键显示路径 """
while True:
self.screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
if event.type == pygame.MOUSEBUTTONDOWN: # 按鼠标显示路径,再按取消显示
if self.no_route:
self.color = ROUTE_COLOR
self.no_route = False
else:
self.color = POSSIBLE_COLOR
self.no_route = True
if event.type == pygame.KEYDOWN: # 按任意键重新生成迷宫
self.maze = MakeMaze().create(ROW, COL)
self.drawBlock(self.color)
self.clock.tick(FPS)
pygame.display.update()
def drawBlock(self, color):
""" 用遍历取出迷宫数据并在窗口中画颜色块 """
for i, line in enumerate(self.maze):
for j, value in enumerate(line):
rect = (j * BLOCK + BORDER, i * BLOCK + BORDER, BLOCK, BLOCK)
if value == 0:
pygame.draw.rect(self.screen, IMPOSSIBLE_COLOR, rect, 0)
elif value == 1:
pygame.draw.rect(self.screen, POSSIBLE_COLOR, rect, 0)
else:
pygame.draw.rect(self.screen, color, rect, 0)
# noinspection PyPep8Naming
class MakeMaze(object):
def __init__(self):
self.route_list = [] # 初始化路线列表
# noinspection PyUnusedLocal
def create(self, x, y):
""" 生成迷宫 """
route_list = [] # 初始化路线列表
while True:
maze = [[random.choice([0, 1]) for j in range(y)] for i in range(x)]
maze[0][0] = 1
if self.walk(maze, 0, 0):
return maze
def walk(self, maze, x, y):
"""
如果位置是迷宫的出口,说明成功走出迷宫
依次向下、右、左、上进行探测,走的通就返回True,然后继续探测,走不通就返回False
"""
if x == len(maze) - 1 and y == len(maze[0]) - 1:
maze[x][y] = 2 # 将出口位置做标记
return True
if self.validPos(maze, x, y): # 递归主体实现
self.route_list.append((x, y)) # 将位置加入路线列表中
maze[x][y] = 2 # 做标记,防止折回
if self.walk(maze, x + 1, y) or self.walk(maze, x, y + 1) \
or self.walk(maze, x, y - 1) or self.walk(maze, x - 1, y):
return True
else:
maze[x][y] = 1 # 没走通把上一步位置标记取消,以便能够退回
self.route_list.pop() # 在位置列表中删除位置,即最后一个元素
return False
return False
@staticmethod
def pprint(maze):
""" 打印迷宫 """
[print(n) for n in maze]
@staticmethod
def validPos(maze, x, y):
""" 判断坐标的有效性,如果超出数组边界或是不满足值为1的条件,说明该点无效返回False,否则返回True """
if len(maze) > x >= 0 and len(maze[0]) > y >= 0 and maze[x][y] == 1:
return True
else:
return False
def main():
drawer = DrawMaze() # 用迷宫生成画图对象
drawer.display() # 显示迷宫
if __name__ == '__main__':
main()总结
安啦!文章就写到这里,你们的支持是我最大的动力,记得三连哦~
关注小编获取更多精彩内容!记得点击传送门哈
记得三连哦! 如需打包好的完整源码+素材免费分享滴!传送门

边栏推荐
- Usage of C tryparse
- Ilruntime hotfix framework installation and breakpoint debugging
- Exception 0xc00000005 code occurred when LabVIEW called DLL
- Self made app connected to onenet --- realize data monitoring and distribution control (mqtt)
- Classic sentences in Yi Shu's works
- Data file nc6oa Txt consists of 6830 gene expression data from 33 cancer cell lines, each of which is a type of cancer cell. Please cluster the 33 cell lines according to the gene expression data (the
- Binary tree pruning
- 插入排序
- LabVIEW在波形图或波形图表上显示时间和日期
- OSS stores and exports related content
猜你喜欢

LabVIEW中NI MAX中缺少串口

Expandable to Max – MCU and MPU development, using the same license

基于CenterOS7安装Redis及常见问题解决(带图讲解)

Kubernetes 基本介绍及核心组件

Common settings for vs

黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......

【无标题】

LabVIEW get IMAQ get last event coordinates

IGBT与三代半导体SiC双脉冲测试方案
![The shell script of pagoda plan task regularly deletes all files under a directory [record]](/img/dc/cfd449bf14c4545cd2e52bda4ab31e.png)
The shell script of pagoda plan task regularly deletes all files under a directory [record]
随机推荐
MySQL学习之子查询
IGBT and third generation semiconductor SiC double pulse test scheme
Redis installation and common problem solving based on centeros7 (explanation with pictures)
HyperLeger Fabric安装
Is qiniu's securities account true? Is it safe?
Yuntu says that every successful business system cannot be separated from apig
关于优化API接口响应速度
LabVIEW phase locked loop (PLL)
LabVIEW改变Point ROI Overlay的形状或颜色
The data file insurance CSV contains 1338 observations, that is, the registered beneficiaries of the insurance plan and the characteristics that represent the characteristics of patients and the total
Data and information resource sharing platform (VII)
Is it safe to open an account for tongdaxin stock? How to open an account?
This article introduces you to j.u.c's futuretask, fork/join framework and BlockingQueue
High speed data stream disk for LabVIEW
Dark horse headlines - Tencent's salary system reform has caused controversy; Intel expanded the recruitment of female engineers nationwide; Black horse is 100% employed really
示波器和频谱分析仪的区别
LabVIEW锁相环(PLL)
Difference between oscilloscope and spectrum analyzer
LabVIEW错误“内存已满 - 应用程序停止在节点”
LabVIEW获取Clamp函数找到的所有点的信息
