(1) Every time the snake takes a step, BFS is used to calculate the shortest path length to the food for each position in the game interface (except the snake body);
(2) The safety of a snake is defined as whether the snake can follow the snake's tail, that is, whether there is a path between the snake's head and its tail;
(3) The snake uses the virtual snake to explore the path before each action. If the virtual snake is safe after eating the food, the real snake will act;
(4) If there is no path between the snake and the food or it is not safe after eating the food, follow the snake tail;
(5) If there is no path between the snake and the food, between the snake and the snake's tail, just pick a feasible step and walk;
(6) Ensure that the target is the shortest path when the snake takes food, and the longest path when the target is the tail.
Since the food appears randomly, if the virtual snake runs and finds that it is not safe to eat the food, the real snake will not eat the food, but will choose to chase the snake's tail. If it continues to do so, it will fall into an endless loop. Chasing the snake's tail has been running around. . .
Until you terminate the game. . .
The pygame module and some modules that come with Python.
Install Python and add it to the environment variable, pip installs the required related modules.
Run the AI_snake.py
file in the cmd window.
The upload of GIFs has been failed. . .
So just cut a few pictures~
(1) In order to ensure that the code is simple and easy to understand, the provided code has high redundancy (for example, unnecessary repeated calculations), and those who are interested can optimize the code;
(2) The normal version of the snake game (Normal_snake.py) is also provided in the related files.
Recommended Posts