Python implements AI automatic version greedy snake

Main idea#

(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.

Disadvantages#

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. . .

development tools#

Python version: 3.5.4

**Related modules: **

The pygame module and some modules that come with Python.

Environment setup#

Install Python and add it to the environment variable, pip installs the required related modules.

Operation mode#

Run the AI_snake.py file in the cmd window.

Result display#

The upload of GIFs has been failed. . .

So just cut a few pictures~

More#

(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

Python implements AI automatic version greedy snake
Python implements text version minesweeper
Python implements AI face change function
Python realizes the greedy snake double battle
Python implementation of AI automatic matting example analysis
Ubuntu18.04 switch Python version
Python implements Super Mario
Python implements tic-tac-toe game
Ubuntu16.04 switch python version
Python implements man-machine gobang
Python implements Tetris game
Python implements image stitching
Python implements minesweeper game
Python implements scanning tools
python tic-tac-toe-text version (part 2)
PyCharm set Python version
Python implements threshold regression
Python implements minesweeper games
python Tic-Tac-Toe-text version (on)
Python implements guessing game