当前位置: 移动技术网 > IT编程>脚本编程>Python > 利用Python如何制作贪吃蛇及AI版贪吃蛇详解

利用Python如何制作贪吃蛇及AI版贪吃蛇详解

2020年08月25日  | 移动技术网IT编程  | 我要评论
用python制作普通贪吃蛇哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好!贪吃蛇,应该是90后小时候的记忆(连我这个00后也不例外),今天,我们就用python这款编程语言来实现贪吃蛇系统:

用python制作普通贪吃蛇

哈喽,大家不知道是上午好还是中午好还是下午好还是晚上好!

贪吃蛇,应该是90后小时候的记忆(连我这个00后也不例外),今天,我们就用python这款编程语言来实现贪吃蛇

系统:所有都可以

需导入模块:

  • random
  • pygame
  • pygame.locals
  • sys

下载以上模块指令:

random和sys是python自带的,我们只需要下载pygame即可

下载pygame:

在开始菜单输入“cmd”回车打开,输入``指令:pip install pygame

苹果电脑需要改成:pip3 install pygame

下载好后,打开python的shell界面,输入import pygame,回车,如果没报错,及代表安装完成。

接下来什么都不说,直接奉上代码(恕我没写注释):

import random
import pygame
import sys
from pygame.locals import *
 
snakespeed = 17
window_width = 800
window_height = 500
cell_size = 20 # width and height of the cells
# ensuring that the cells fit perfectly in the window. eg if cell size was
# 10 and window width or windowheight were 15 only 1.5 cells would
# fit.
assert window_width % cell_size == 0, "window width must be a multiple of cell size."
# ensuring that only whole integer number of cells fit perfectly in the window.
assert window_height % cell_size == 0, "window height must be a multiple of cell size."
cell_w = int(window_width / cell_size) # cell width
cell_h = int(window_height / cell_size) # cellc height
 
 
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0) # defining element colors for the program.
green = (0, 255, 0)
darkgreen = (0, 155, 0)
darkgray = (40, 40, 40)
yellow = (255, 255, 0)
red_dark = (150, 0, 0)
blue = (0, 0, 255)
blue_dark = (0, 0, 150)
 
 
bgcolor = black # background color
 
 
up = 'up'
down = 'down' # defining keyboard keys.
left = 'left'
right = 'right'
 
head = 0 # syntactic sugar: index of the snake's head
 
 
def main():
 global snakespeedclock, displaysurf, basicfont
 
 pygame.init()
 snakespeedclock = pygame.time.clock()
 displaysurf = pygame.display.set_mode((window_width, window_height))
 basicfont = pygame.font.font('freesansbold.ttf', 18)
 pygame.display.set_caption('snake')
 
 showstartscreen()
 while true:
 rungame()
 showgameoverscreen()
 
 
def rungame():
 # set a random start point.
 startx = random.randint(5, cell_w - 6)
 starty = random.randint(5, cell_h - 6)
 wormcoords = [{'x': startx, 'y': starty},
   {'x': startx - 1, 'y': starty},
   {'x': startx - 2, 'y': starty}]
 direction = right
 
 # start the apple in a random place.
 apple = getrandomlocation()
 
 while true: # main game loop
 for event in pygame.event.get(): # event handling loop
  if event.type == quit:
  terminate()
  elif event.type == keydown:
  if (event.key == k_left) and direction != right:
   direction = left
  elif (event.key == k_right) and direction != left:
   direction = right
  elif (event.key == k_up) and direction != down:
   direction = up
  elif (event.key == k_down) and direction != up:
   direction = down
  elif event.key == k_escape:
   terminate()
 
 # check if the snake has hit itself or the edge
 if wormcoords[head]['x'] == -1 or wormcoords[head]['x'] == cell_w or wormcoords[head]['y'] == -1 or wormcoords[head]['y'] == cell_h:
  return # game over
 for wormbody in wormcoords[1:]:
  if wormbody['x'] == wormcoords[head]['x'] and wormbody['y'] == wormcoords[head]['y']:
  return # game over
 
 # check if snake has eaten an apply
 if wormcoords[head]['x'] == apple['x'] and wormcoords[head]['y'] == apple['y']:
  # don't remove worm's tail segment
  apple = getrandomlocation() # set a new apple somewhere
 else:
  del wormcoords[-1] # remove worm's tail segment
 
 # move the worm by adding a segment in the direction it is moving
 if direction == up:
  newhead = {'x': wormcoords[head]['x'],
   'y': wormcoords[head]['y'] - 1}
 elif direction == down:
  newhead = {'x': wormcoords[head]['x'],
   'y': wormcoords[head]['y'] + 1}
 elif direction == left:
  newhead = {'x': wormcoords[head][
  'x'] - 1, 'y': wormcoords[head]['y']}
 elif direction == right:
  newhead = {'x': wormcoords[head][
  'x'] + 1, 'y': wormcoords[head]['y']}
 wormcoords.insert(0, newhead)
 displaysurf.fill(bgcolor)
 drawgrid()
 drawworm(wormcoords)
 drawapple(apple)
 drawscore(len(wormcoords) - 3)
 pygame.display.update()
 snakespeedclock.tick(snakespeed)
 
 
def drawpresskeymsg():
 presskeysurf = basicfont.render('press a key to play.', true, white)
 presskeyrect = presskeysurf.get_rect()
 presskeyrect.topleft = (window_width - 200, window_height - 30)
 displaysurf.blit(presskeysurf, presskeyrect)
 
 
def checkforkeypress():
 if len(pygame.event.get(quit)) > 0:
 terminate()
 keyupevents = pygame.event.get(keyup)
 if len(keyupevents) == 0:
 return none
 if keyupevents[0].key == k_escape:
 terminate()
 return keyupevents[0].key
 
 
def showstartscreen():
 titlefont = pygame.font.font('freesansbold.ttf', 100)
 titlesurf1 = titlefont.render('snake!', true, white, darkgreen)
 degrees1 = 0
 degrees2 = 0
 while true:
 displaysurf.fill(bgcolor)
 rotatedsurf1 = pygame.transform.rotate(titlesurf1, degrees1)
 rotatedrect1 = rotatedsurf1.get_rect()
 rotatedrect1.center = (window_width / 2, window_height / 2)
 displaysurf.blit(rotatedsurf1, rotatedrect1)
 
 drawpresskeymsg()
 
 if checkforkeypress():
  pygame.event.get() # clear event queue
  return
 pygame.display.update()
 snakespeedclock.tick(snakespeed)
 degrees1 += 3 # rotate by 3 degrees each frame
 degrees2 += 7 # rotate by 7 degrees each frame
 
 
def terminate():
 pygame.quit()
 sys.exit()
 
 
def getrandomlocation():
 return {'x': random.randint(0, cell_w - 1), 'y': random.randint(0, cell_h - 1)}
 
 
def showgameoverscreen():
 gameoverfont = pygame.font.font('freesansbold.ttf', 100)
 gamesurf = gameoverfont.render('game', true, white)
 oversurf = gameoverfont.render('over', true, white)
 gamerect = gamesurf.get_rect()
 overrect = oversurf.get_rect()
 gamerect.midtop = (window_width / 2, 10)
 overrect.midtop = (window_width / 2, gamerect.height + 10 + 25)
 
 displaysurf.blit(gamesurf, gamerect)
 displaysurf.blit(oversurf, overrect)
 drawpresskeymsg()
 pygame.display.update()
 pygame.time.wait(500)
 checkforkeypress() # clear out any key presses in the event queue
 
 while true:
 if checkforkeypress():
  pygame.event.get() # clear event queue
  return
 
 
def drawscore(score):
 scoresurf = basicfont.render('score: %s' % (score), true, white)
 scorerect = scoresurf.get_rect()
 scorerect.topleft = (window_width - 120, 10)
 displaysurf.blit(scoresurf, scorerect)
 
 
def drawworm(wormcoords):
 for coord in wormcoords:
 x = coord['x'] * cell_size
 y = coord['y'] * cell_size
 wormsegmentrect = pygame.rect(x, y, cell_size, cell_size)
 pygame.draw.rect(displaysurf, darkgreen, wormsegmentrect)
 worminnersegmentrect = pygame.rect(
  x + 4, y + 4, cell_size - 8, cell_size - 8)
 pygame.draw.rect(displaysurf, green, worminnersegmentrect)
 
 
def drawapple(coord):
 x = coord['x'] * cell_size
 y = coord['y'] * cell_size
 applerect = pygame.rect(x, y, cell_size, cell_size)
 pygame.draw.rect(displaysurf, red, applerect)
 
 
def drawgrid():
 for x in range(0, window_width, cell_size): # draw vertical lines
 pygame.draw.line(displaysurf, darkgray, (x, 0), (x, window_height))
 for y in range(0, window_height, cell_size): # draw horizontal lines
 pygame.draw.line(displaysurf, darkgray, (0, y), (window_width, y))
 
 
if __name__ == '__main__':
 try:
 main()
 except systemexit:
 pass

以上是贪吃蛇的全部代码,接下来,我们来制作ai版贪吃蛇。

用python制作ai版贪吃蛇

ai版贪吃蛇,即让系统自己玩贪吃蛇,一句话:自己玩自己。下面开始:

系统:什么都可以

需导入的模块:

  • pygame
  • sys
  • time
  • random

如果你已经下载好了pygame,即可直接开始。

还是什么都不说,直接奉上代码(这次有注释)

#coding: utf-8
import pygame,sys,time,random
from pygame.locals import *
# 定义颜色变量
redcolour = pygame.color(255,0,0)
blackcolour = pygame.color(0,0,0)
whitecolour = pygame.color(255,255,255)
greencolour = pygame.color(0,255,0)
headcolour = pygame.color(0,119,255)

#注意:在下面所有的除法中,为了防止pygame输出偏差,必须取除数(//)而不是单纯除法(/)

# 蛇运动的场地长宽,因为第0行,height行,第0列,width列为围墙,所以实际是13*13
height = 15
width = 15
field_size = height * width
# 蛇头位于snake数组的第一个元素
head = 0

# 用数字代表不同的对象,由于运动时矩阵上每个格子会处理成到达食物的路径长度,
# 因此这三个变量间需要有足够大的间隔(>height*width)来互相区分
# 小写一般是坐标,大写代表常量
food = 0
undefined = (height + 1) * (width + 1)
snake = 2 * undefined

# 由于snake是一维数组,所以对应元素直接加上以下值就表示向四个方向移动
left = -1
right = 1
up = -width#一维数组,所以需要整个宽度都加上才能表示上下移动
down = width 

# 错误码
err = -2333

# 用一维数组来表示二维的东西
# board表示蛇运动的矩形场地
# 初始化蛇头在(1,1)的地方
# 初始蛇长度为1
board = [0] * field_size #[0,0,0,……]
snake = [0] * (field_size+1)
snake[head] = 1*width+1
snake_size = 1
# 与上面变量对应的临时变量,蛇试探性地移动时使用
tmpboard = [0] * field_size
tmpsnake = [0] * (field_size+1)
tmpsnake[head] = 1*width+1
tmpsnake_size = 1

# food:食物位置初始在(4, 7)
# best_move: 运动方向
food = 4 * width + 7
best_move = err

# 运动方向数组,游戏分数(蛇长)
mov = [left, right, up, down]           
score = 1 

# 检查一个cell有没有被蛇身覆盖,没有覆盖则为free,返回true
def is_cell_free(idx, psize, psnake):
 return not (idx in psnake[:psize]) 

# 检查某个位置idx是否可向move方向运动
def is_move_possible(idx, move):
 flag = false
 if move == left:
  #因为实际范围是13*13,[1,13]*[1,13],所以idx为1时不能往左跑,此时取余为1所以>1
  flag = true if idx%width > 1 else false
 elif move == right:
  #这里的<width-2跟上面是一样的道理
  flag = true if idx%width < (width-2) else false
 elif move == up:
  #这里向上的判断画图很好理解,因为在[1,13]*[1,13]的实际运动范围外,还有个
  #大框是围墙,就是之前说的那几个行列,下面判断向下运动的条件也是类似的
  flag = true if idx > (2*width-1) else false
 elif move == down:
  flag = true if idx < (field_size-2*width) else false
 return flag
# 重置board
# board_bfs后,undefined值都变为了到达食物的路径长度
# 如需要还原,则要重置它
def board_reset(psnake, psize, pboard):
 for i in range(field_size):
  if i == food:
   pboard[i] = food
  elif is_cell_free(i, psize, psnake): # 该位置为空
   pboard[i] = undefined
  else: # 该位置为蛇身
   pboard[i] = snake
 
# 广度优先搜索遍历整个board,
# 计算出board中每个非snake元素到达食物的路径长度
def board_bfs(pfood, psnake, pboard):
 queue = []
 queue.append(pfood)
 inqueue = [0] * field_size
 found = false
 # while循环结束后,除了蛇的身体,
 # 其它每个方格中的数字为从它到食物的曼哈顿间距
 while len(queue)!=0: 
  idx = queue.pop(0)#初始时idx是食物的坐标 
  if inqueue[idx] == 1: continue
  inqueue[idx] = 1
  for i in range(4):#左右上下
   if is_move_possible(idx, mov[i]):
    if idx + mov[i] == psnake[head]:
     found = true
    if pboard[idx+mov[i]] < snake: # 如果该点不是蛇的身体
     if pboard[idx+mov[i]] > pboard[idx]+1:#小于的时候不管,不然会覆盖已有的路径数据
      pboard[idx+mov[i]] = pboard[idx] + 1
     if inqueue[idx+mov[i]] == 0:
      queue.append(idx+mov[i])
 return found

# 从蛇头开始,根据board中元素值,
# 从蛇头周围4个领域点中选择最短路径
def choose_shortest_safe_move(psnake, pboard):
 best_move = err
 min = snake
 for i in range(4):
  if is_move_possible(psnake[head], mov[i]) and pboard[psnake[head]+mov[i]]<min:
   #这里判断最小和下面的函数判断最大,都是先赋值,再循环互相比较
   min = pboard[psnake[head]+mov[i]]
   best_move = mov[i]
 return best_move

# 从蛇头开始,根据board中元素值,
# 从蛇头周围4个领域点中选择最远路径
def choose_longest_safe_move(psnake, pboard):
 best_move = err
 max = -1
 for i in range(4):
  if is_move_possible(psnake[head], mov[i]) and pboard[psnake[head]+mov[i]]<undefined and pboard[psnake[head]+mov[i]]>max:
   max = pboard[psnake[head]+mov[i]]
   best_move = mov[i]
 return best_move

# 检查是否可以追着蛇尾运动,即蛇头和蛇尾间是有路径的
# 为的是避免蛇头陷入死路
# 虚拟操作,在tmpboard,tmpsnake中进行
def is_tail_inside():
 global tmpboard, tmpsnake, food, tmpsnake_size
 tmpboard[tmpsnake[tmpsnake_size-1]] = 0 # 虚拟地将蛇尾变为食物(因为是虚拟的,所以在tmpsnake,tmpboard中进行)
 tmpboard[food] = snake # 放置食物的地方,看成蛇身
 result = board_bfs(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) # 求得每个位置到蛇尾的路径长度
 for i in range(4): # 如果蛇头和蛇尾紧挨着,则返回false。即不能follow_tail,追着蛇尾运动了
  if is_move_possible(tmpsnake[head], mov[i]) and tmpsnake[head]+mov[i]==tmpsnake[tmpsnake_size-1] and tmpsnake_size>3:
   result = false
 return result

# 让蛇头朝着蛇尾运行一步
# 不管蛇身阻挡,朝蛇尾方向运行
def follow_tail():
 global tmpboard, tmpsnake, food, tmpsnake_size
 tmpsnake_size = snake_size
 tmpsnake = snake[:]
 board_reset(tmpsnake, tmpsnake_size, tmpboard) # 重置虚拟board
 tmpboard[tmpsnake[tmpsnake_size-1]] = food # 让蛇尾成为食物
 tmpboard[food] = snake # 让食物的地方变成蛇身
 board_bfs(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) # 求得各个位置到达蛇尾的路径长度
 tmpboard[tmpsnake[tmpsnake_size-1]] = snake # 还原蛇尾
 return choose_longest_safe_move(tmpsnake, tmpboard) # 返回运行方向(让蛇头运动1步)

# 在各种方案都不行时,随便找一个可行的方向来走(1步),
def any_possible_move():
 global food , snake, snake_size, board
 best_move = err
 board_reset(snake, snake_size, board)
 board_bfs(food, snake, board)
 min = snake

 for i in range(4):
  if is_move_possible(snake[head], mov[i]) and board[snake[head]+mov[i]]<min:
   min = board[snake[head]+mov[i]]
   best_move = mov[i]
 return best_move
 
#转换数组函数
def shift_array(arr, size):
 for i in range(size, 0, -1):
  arr[i] = arr[i-1]

def new_food():#随机函数生成新的食物
 global food, snake_size
 cell_free = false
 while not cell_free:
  w = random.randint(1, width-2)
  h = random.randint(1, height-2)
  food = width*h + w
  cell_free = is_cell_free(food, snake_size, snake)
 pygame.draw.rect(playsurface,redcolour,rect(18*(food//width), 18*(food%width),18,18))

# 真正的蛇在这个函数中,朝pbest_move走1步
def make_move(pbest_move):
 global snake, board, snake_size, score
 shift_array(snake, snake_size)
 snake[head] += pbest_move
 p = snake[head]
 for body in snake:#画蛇,身体,头,尾
  pygame.draw.rect(playsurface,whitecolour,rect(18*(body//width), 18*(body%width),18,18))
 pygame.draw.rect(playsurface,greencolour,rect(18*(snake[snake_size-1]//width),18*(snake[snake_size-1]%width),18,18))
 pygame.draw.rect(playsurface,headcolour,rect(18*(p//width), 18*(p%width),18,18))
 #下面一行是把初始情况会出现的第一个白块bug填掉
 pygame.draw.rect(playsurface,(255,255,0),rect(0,0,18,18))
 # 刷新pygame显示层
 pygame.display.flip() 
 
 # 如果新加入的蛇头就是食物的位置
 # 蛇长加1,产生新的食物,重置board(因为原来那些路径长度已经用不上了)
 if snake[head] == food:
  board[snake[head]] = snake # 新的蛇头
  snake_size += 1
  score += 1
  if snake_size < field_size: new_food()
 else: # 如果新加入的蛇头不是食物的位置
  board[snake[head]] = snake # 新的蛇头
  board[snake[snake_size]] = undefined # 蛇尾变为undefined,黑色
  pygame.draw.rect(playsurface,blackcolour,rect(18*(snake[snake_size]//width),18*(snake[snake_size]%width),18,18))
  # 刷新pygame显示层
  pygame.display.flip() 

# 虚拟地运行一次,然后在调用处检查这次运行可否可行
# 可行才真实运行。
# 虚拟运行吃到食物后,得到虚拟下蛇在board的位置
def virtual_shortest_move():
 global snake, board, snake_size, tmpsnake, tmpboard, tmpsnake_size, food
 tmpsnake_size = snake_size
 tmpsnake = snake[:] # 如果直接tmpsnake=snake,则两者指向同一处内存
 tmpboard = board[:] # board中已经是各位置到达食物的路径长度了,不用再计算
 board_reset(tmpsnake, tmpsnake_size, tmpboard)
 
 food_eated = false
 while not food_eated:
  board_bfs(food, tmpsnake, tmpboard) 
  move = choose_shortest_safe_move(tmpsnake, tmpboard)
  shift_array(tmpsnake, tmpsnake_size)
  tmpsnake[head] += move # 在蛇头前加入一个新的位置
  # 如果新加入的蛇头的位置正好是食物的位置
  # 则长度加1,重置board,食物那个位置变为蛇的一部分(snake)
  if tmpsnake[head] == food:
   tmpsnake_size += 1
   board_reset(tmpsnake, tmpsnake_size, tmpboard) # 虚拟运行后,蛇在board的位置
   tmpboard[food] = snake
   food_eated = true
  else: # 如果蛇头不是食物的位置,则新加入的位置为蛇头,最后一个变为空格
   tmpboard[tmpsnake[head]] = snake
   tmpboard[tmpsnake[tmpsnake_size]] = undefined

# 如果蛇与食物间有路径,则调用本函数
def find_safe_way():
 global snake, board
 safe_move = err
 # 虚拟地运行一次,因为已经确保蛇与食物间有路径,所以执行有效
 # 运行后得到虚拟下蛇在board中的位置,即tmpboard
 virtual_shortest_move() # 该函数唯一调用处
 if is_tail_inside(): # 如果虚拟运行后,蛇头蛇尾间有通路,则选最短路运行(1步)
  return choose_shortest_safe_move(snake, board)
 safe_move = follow_tail() # 否则虚拟地follow_tail 1步,如果可以做到,返回true
 return safe_move


#初始化pygame
pygame.init()
#定义一个变量用来控制游戏速度
fpsclock = pygame.time.clock()
# 创建pygame显示层
playsurface = pygame.display.set_mode((270,270))
pygame.display.set_caption('贪吃蛇')
# 绘制pygame显示层
playsurface.fill(blackcolour)
#初始化食物
pygame.draw.rect(playsurface,redcolour,rect(18*(food//width), 18*(food%width),18,18))

while true:
 for event in pygame.event.get():#循环监听键盘和退出事件
  if event.type == quit:#如果点了关闭
   print(score)#游戏结束后打印分数
   pygame.quit()
   sys.exit()
  elif event.type == keydown:#如果esc键被按下
   if event.key==k_escape:
    print(score)#游戏结束后打印分数
    pygame.quit()
    sys.exit()
 # 刷新pygame显示层
 pygame.display.flip() 
 #画围墙,255,255,0是黄色,边框是36是因为,pygame矩形是以边为初始,向四周填充边框
 pygame.draw.rect(playsurface,(255,255,0),rect(0,0,270,270),36)
 # 重置距离
 board_reset(snake, snake_size, board)
 # 如果蛇可以吃到食物,board_bfs返回true
 # 并且board中除了蛇身(=snake),其它的元素值表示从该点运动到食物的最短路径长
 if board_bfs(food, snake, board):
  best_move = find_safe_way() # find_safe_way的唯一调用处
 else:
  best_move = follow_tail()
 if best_move == err:
  best_move = any_possible_move()
 # 上面一次思考,只得出一个方向,运行一步
 if best_move != err: make_move(best_move)
 else:
  print(score)#游戏结束后打印分数
  break
 # 控制游戏速度
 fpsclock.tick(20)#20看上去速度正好


ok,这就是今天的全部内容866!

到此这篇关于利用python如何制作贪吃蛇及ai版贪吃蛇的文章就介绍到这了,更多相关python制作贪吃蛇及ai版贪吃蛇内容请搜索移动技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持移动技术网!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网