前言 
利用Python简单地实现AI版的贪吃蛇  
效果展示 
   
开发工具 
Python版本: 3.5.4  
相关模块:  
pygame模块以及一些Python自带的模块。  
环境搭建 
安装Python并添加到环境变量,pip安装需要的相关模块即可。  
主要思路 
(1)蛇每走一步,就使用BFS计算游戏界面中每个位置(蛇身除外)到达食物的最短路径长;  
(2)将蛇的安全定义为蛇是否可以跟着蛇尾运动,即蛇头和蛇尾间是否存在路径;  
(3)蛇每次行动前先利用虚拟的蛇进行探路,若虚拟的蛇吃完食物后是安全的,真蛇才行动;  
(4)若蛇和食物之间不存在路径或者吃完食物后并不安全,就跟着蛇尾走;  
(5)若蛇和食物之间、蛇和蛇尾之间均不存在路径,就随便挑一步可行的来走;  
(6)保证目标是食物时蛇走最短路径,目标是蛇尾时蛇走最长路径。  
源码 
🛰?号:
	ilove-python
'''
import cfg
import pygame
from modules.food import *
from modules.snake import *
from modules.utils import *
from modules.agent import *
from modules.endInterface import *
'''main function'''
def main(cfg):
	# initialize the game
	pygame.init()
	screen = pygame.display.set_mode(cfg.SCREENSIZE)
	pygame.display.set_caption('AI Snake —— 卫星号:ilove-python')
	clock = pygame.time.Clock()
	# play the background music
	pygame.mixer.music.load(cfg.BGMPATH)
	pygame.mixer.music.play(-1)
	# the game main loop
	snake = Snake(cfg)
	ai = Agent(cfg, snake)
	apple = Apple(cfg, snake.coords)
	score = 0
	while True:
		screen.fill(cfg.BLACK)
		# --check the keyboard
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
		# --make decision by agent
		infos = ai.act(snake, apple)
		# --update the food and score
		if infos and infos['eaten']:
			apple = infos['food']
			assert apple, 'bugs may exist'
			score += 1
		# --judge whether the game is over
		if snake.isgameover: break
		# --draw the necessary elements in the game
		drawGameGrid(cfg, screen)
		snake.draw(screen)
		apple.draw(screen)
		showScore(cfg, score, screen)
		# --update the screen
		pygame.display.update()
		clock.tick(cfg.FPS)
	return endInterface(screen, cfg)
'''run'''
if __name__ == '__main__':
	while True:
		try:
			if not main(cfg):
				break
		except:
			continue
  
不足之处 
由于食物是随机出现的,若虚拟的蛇跑一遍发现去吃食物是不安全的,真蛇就不会去吃食物,而是选择追着蛇尾跑,若一直如此,就陷入了死循环,蛇一直追着蛇尾跑跑跑。  直到你终止游戏为止。     
往期回顾 
Python实现贪吃蛇小游戏  
Python自动玩“别再踩白块了“小游戏 
                
                
                
        
    
 
 |