当前位置:网站首页>[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)
[pyGame games] I'm not afraid you can't walk the maze series: the ultimate AI walks the maze. After learning, it will take you to open the door to a new world ~ (with game source code)
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article is mainly about pygame Realization AI Gobang version of the game !
** article Source code Free access : To thank every project that pays attention to my little cute article Source code It's all nothing
Compensation sharing drop
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Text
hello ! Hello, I'm a pear , Here comes the daily update ——
Have you ever played maze games ? Usually when I was a child , The elders of the family will play with the children of the family
Some parent-child games 、 For example, the most familiar one 《 Maze games 》 La ~ It's great to exercise your brain !
today , Let's use our imagination , Together with the code to make a AI Version of the maze !

One 、 Game ideas
This small program solves the maze problem with recursive method , Added a maze that can be automatically generated , But some problems are not very clear
The maze used a stupid method , It's generating 20 That's ok 、 It will be slow to list the mazes above ~
Just a simple study , After that, there will be better ones to continue to learn and update them for you !
1) Effect display


2) The main program
There are three main codes , There are too many, so only the code of the main program is shown here , Official account at the end of the article. !
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)) # Create screen object
pygame.display.set_caption('{}*{} Maze'.format(ROW, COL)) # Window title
self.clock = pygame.time.Clock()
self.color = POSSIBLE_COLOR # First, set the color of the path block to be the same as that of the possible block
self.maze = MakeMaze().create(ROW, COL)
self.no_route = True
def display(self):
""" Show maze in window , Press any key to display the path """
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: # Press the mouse to display the path , Press again to cancel the display
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: # Press any key to regenerate the maze
self.maze = MakeMaze().create(ROW, COL)
self.drawBlock(self.color)
self.clock.tick(FPS)
pygame.display.update()
def drawBlock(self, color):
""" Take out the maze data with traversal and draw color blocks in the window """
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 = [] # Initialize route list
# noinspection PyUnusedLocal
def create(self, x, y):
""" Create mazes """
route_list = [] # Initialize 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):
"""
If the location is the exit of the maze , It shows that you have successfully walked out of the maze
Down in turn 、 Right 、 Left 、 Detect on , Go through and return True, Then continue the detection , Go back if you can't get through False
"""
if x == len(maze) - 1 and y == len(maze[0]) - 1:
maze[x][y] = 2 # Mark the exit position
return True
if self.validPos(maze, x, y): # Recursive principal implementation
self.route_list.append((x, y)) # Add location to route list
maze[x][y] = 2 # Make a mark , Prevent folding back
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 # If you fail to get through, cancel the position mark of the previous step , So that it can be returned
self.route_list.pop() # Deletes a location from the location list , The last element
return False
return False
@staticmethod
def pprint(maze):
""" Print maze """
[print(n) for n in maze]
@staticmethod
def validPos(maze, x, y):
""" Judge the validity of coordinates , If it exceeds the array boundary or does not meet the requirements, the value is 1 Conditions , Description this point is invalid. Return False, Otherwise return to 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() # Generating drawing objects with maze
drawer.display() # Show maze
if __name__ == '__main__':
main()summary
An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~
Follow Xiaobian for more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need to package the complete source code + Free sharing of materials ! Portal

边栏推荐
猜你喜欢

30 | how to reset the consumer group displacement?

LabVIEW获取IMAQ Get Last Event坐标

【无标题】

Difference between oscilloscope and spectrum analyzer

LabVIEW中创建毫秒时间标识

【AI出牌器】第一次见这么“刺激”的斗地主,胜率高的关键因素竟是......

Redis installation and common problem solving based on centeros7 (explanation with pictures)

LabVIEW error "memory full - Application stopped on node"

LabVIEW获取Clamp函数找到的所有点的信息

Fiddler creates an autoresponder
随机推荐
关于优化API接口响应速度
Serial port missing in Ni Max in LabVIEW
【数学】【连续介质力学】流体力学中的对称张量、应变张量和应力张量
【Pygame小游戏】来了来了它来了——这款五子棋小游戏超A的,分享给你的小伙伴儿一起pk吧~
LabVIEW打开其他EXE程序
Analysis of Genesis public chain
Why many new websites are not included by search engines
选择排序
About optimizing API interface response speed
How to measure the refresh rate of oscilloscope
【Pygame小遊戲】別找了,休閑遊戲專題來了丨泡泡龍小程序——休閑遊戲研發推薦
【Pygame小游戏】激荡大脑思维,一起来玩转奇思妙想“24点”叭~(超赞滴)
Vs tomato assistant add header comments and usage
LabVIEW uses the visa read function to read USB interrupt data
Shell Sort
Deepin20菜单启动选项后自检到iwlwifi停机
A simple understanding of B tree
LabVIEW displays the time and date on the waveform chart or waveform chart
LeetCode 501 :二叉搜索树中的众数
csdn每日一练——有序表的折半查找
