今天给大家演示哈密顿环自动玩贪吃蛇小游戏呀~

开发工具

Python版本:3.6.4

相关模块:

pygame模块;

以及一些python自带的模块。

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

原理简介

这里我们主要讲如何设计算法来自动玩贪吃蛇小游戏。先来简单介绍一下哈密顿环的定义(引自维基百科):

  1. 哈密顿图是一个无向图,由哈密顿爵士提出,
  2. 由指定的起点前往指定的终点,途中经过所有其他节点且只经过一次。
  3. 在图论中是指含有哈密顿回路的图,
  4. 闭合的哈密顿路径称作哈密顿回路(Hamiltonian cycle),
  5. 含有图中所有顶点的路径称作哈密顿路径
  6. (英语:Hamiltonian path,或Traceable path)。
  7. 哈密尔顿图的定义:G=(V,E)是一个图,
  8. 若G中一条通路通过且仅通过每一个顶点一次,
  9. 称这条通路为哈密尔顿通路。
  10. 若G中一个圈通过且仅通过每一个顶点一次,称这个圈为哈密尔顿圈。
  11. 若一个图存在哈密尔顿圈,就称为哈密尔顿图。

举个例子,有一个4*4的地图:


image.png

那么哈密顿环就可以是(不唯一):


image.png

通过构造哈密顿环,我们就可以很轻松地保证蛇在运动的过程中不会因为撞到自己而死掉。举个例子,假设格子0,1,2是我们的贪吃蛇,其中2为蛇头,0为蛇尾,其余为蛇身,则我们可以通过以下算法来构造哈密顿环(图源参考文献[1]):


image.png

注意,该算法并不是用来找哈密顿环的通用算法,因此存在找不到哈密顿环的情况(为了提高算法找到哈密顿环的概率,我们把原版游戏地图里的4025个方格改成了2020个方格)。

具体而言,该算法的代码实现如下:

'''check boundary'''
def checkboundary(self, pos):
  if pos[0] < 0 or pos[1] < 0 or pos[0] >= self.num_cols or pos[1] >= self.num_rows:
    return False
  return True
'''the shortest'''
def shortest(self, wall, head, food):
  wait = OrderedDict()
  node, pre = head, (-1, -1)
  wait[node] = pre
  path = {}
  while wait:
    node, pre = wait.popitem(last=False)
    path[node] = pre
    if node == food:
      break
    if pre in path:
      prepre = path[pre]
      direction = (pre[0]-prepre[0], pre[1]-prepre[1])
      if (direction in self.directions) and (direction != self.directions[0]):
        self.directions.remove(direction)
        self.directions.insert(0, direction)
    for direction in self.directions:
      to = (node[0] + direction[0], node[1] + direction[1])
      if not self.checkboundary(to):
        continue
      if to in path or to in wait or to in wall:
        continue
      wait[to] = node
  if node != food:
    return None
  return self.reverse(path, head, food)
'''reverse path'''
def reverse(self, path, head, food):
  if not path: return path
  path_new = {}
  node = food
  while node != head:
    path_new[path[node]] = node
    node = path[node]
  return path_new
'''the longest'''
def longest(self, wall, head, food):
  path = self.shortest(wall, head, food)
  if path is None:
    return None
  node = head
  while node != food:
    if self.extendpath(path, node, wall+[food]):
      node = head
      continue
    node = path[node]
  return path
'''extend path'''
def extendpath(self, path, node, wall):
  next_ = path[node]
  direction_1 = (next_[0]-node[0], next_[1]-node[1])
  if direction_1 in [(0, -1), (0, 1)]:
    directions = [(-1, 0), (1, 0)]
  else:
    directions = [(0, -1), (0, 1)]
  for d in directions:
    src = (node[0]+d[0], node[1]+d[1])
    to = (next_[0]+d[0], next_[1]+d[1])
    if (src == to) or not (self.checkboundary(src) and self.checkboundary(to)):
      continue
    if src in path or src in wall or to in path or to in wall:
      continue
    direction_2 = (to[0]-src[0], to[1]-src[1])
    if direction_1 == direction_2:
      path[node] = src
      path[src] = to
      path[to] = next_
      return True
  return False
'''build a Hamiltonian cycle'''
def buildcircle(self, snake):
  path = self.longest(snake.coords[1: -1], snake.coords[0], snake.coords[-1])
  if (not path) or (len(path) - 1 != self.num_rows * self.num_cols - len(snake.coords)):
    return None
  for i in range(1, len(snake.coords)):
    path[snake.coords[i]] = snake.coords[i-1]
  return path

即先找到蛇头到蛇尾的最短路径,然后再通过不断扩展路径来构造我们所需要的哈密顿环。(可能有小伙伴会问啦,最短路径都找到了,干嘛还扩成哈密顿环啊,注意,我们这里是在玩贪吃蛇,目标是吃到地图上的食物,而不是不停地跟着自己的尾巴运动。)

因为始终遵循固定的环路既繁琐又费时,看起来十分愚蠢,比如按照上面设计的算法,贪吃蛇会像下图这个样子运动:


image

为了解决这个问题,我们可以通过以下规则来让蛇走一些捷径(图源参考文献[1]):


image.png

翻译过来就是先新建一个和游戏网格矩阵一样大的空矩阵:

world = [[0 for i in range(self.num_cols)] for j in range(self.num_rows)]

然后根据之前计算的哈密顿环,利用有序数字来顺序地填充这个空矩阵:

num = 1
node = snake.coords[-1]
world[node[1]][node[0]] = num
node = self.path[node]
while node != snake.coords[-1]:
  num += 1
  world[node[1]][node[0]] = num
  node = self.path[node]

利用这些有序数字,我们就可以轻松地寻找贪吃蛇的运动捷径啦(其实就是在不撞到自己的前提下,尽可能快地接近地图上随机生成的食物,即下一步里的网格数字尽可能接近食物所在网格的数字):

# obtain shortcut_path
wall = snake.coords
food = food.coord
food_number = world[food[1]][food[0]]
node, pre = wall[0], (-1, -1)
wait = OrderedDict()
wait[node] = pre
path = {}
while wait:
  node, pre = wait.popitem(last=False)
  path[node] = pre
  if node == food:
    break
  node_number = world[node[1]][node[0]]
  neigh = {}
  for direction in self.directions:
    to = (node[0]+direction[0], node[1]+direction[1])
    if not self.checkboundary(to):
      continue
    if to in wait or to in wall or to in path:
      continue
    to_number = world[to[1]][to[0]]
    if to_number > node_number and to_number <= food_number:
      neigh[node_number] = to
  neigh = sorted(neigh.items(), key=itemgetter(0), reverse=True)
  for item in neigh:
    wait[item[1]] = node
if node != food:
  return {}
return self.reverse(path, snake.coords[0], food)

大功告成,完整源代码详见相关文件呗~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容