溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用Python制作貪吃蛇及AI版貪吃蛇的案例分析

發(fā)布時(shí)間:2020-08-25 10:02:46 來源:億速云 閱讀:191 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹利用Python制作貪吃蛇及AI版貪吃蛇的案例分析,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

用python制作普通貪吃蛇

哈嘍,大家不知道是上午好還是中午好還是下午好還是晚上好!

貪吃蛇,應(yīng)該是90后小時(shí)候的記憶(連我這個(gè)00后也不例外),今天,我們就用python這款編程語(yǔ)言來實(shí)現(xiàn)貪吃蛇

系統(tǒng):所有都可以

需導(dǎo)入模塊:

  • random
  • pygame
  • pygame.locals
  • sys
     

下載以上模塊指令:

random和sys是Python自帶的,我們只需要下載pygame即可

下載pygame:

在開始菜單輸入“cmd”回車打開,輸入``指令:pip install pygame

蘋果電腦需要改成:pip3 install pygame

下載好后,打開python的shell界面,輸入import pygame,回車,如果沒報(bào)錯(cuò),及代表安裝完成。

接下來什么都不說,直接奉上代碼(恕我沒寫注釋):

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版貪吃蛇,即讓系統(tǒng)自己玩貪吃蛇,一句話:自己玩自己。下面開始:

系統(tǒng):什么都可以

需導(dǎo)入的模塊:

  • pygame
  • sys
  • time
  • random
     

如果你已經(jīng)下載好了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輸出偏差,必須取除數(shù)(//)而不是單純除法(/)

# 蛇運(yùn)動(dòng)的場(chǎng)地長(zhǎng)寬,因?yàn)榈?行,HEIGHT行,第0列,WIDTH列為圍墻,所以實(shí)際是13*13
HEIGHT = 15
WIDTH = 15
FIELD_SIZE = HEIGHT * WIDTH
# 蛇頭位于snake數(shù)組的第一個(gè)元素
HEAD = 0

# 用數(shù)字代表不同的對(duì)象,由于運(yùn)動(dòng)時(shí)矩陣上每個(gè)格子會(huì)處理成到達(dá)食物的路徑長(zhǎng)度,
# 因此這三個(gè)變量間需要有足夠大的間隔(>HEIGHT*WIDTH)來互相區(qū)分
# 小寫一般是坐標(biāo),大寫代表常量
FOOD = 0
UNDEFINED = (HEIGHT + 1) * (WIDTH + 1)
SNAKE = 2 * UNDEFINED

# 由于snake是一維數(shù)組,所以對(duì)應(yīng)元素直接加上以下值就表示向四個(gè)方向移動(dòng)
LEFT = -1
RIGHT = 1
UP = -WIDTH#一維數(shù)組,所以需要整個(gè)寬度都加上才能表示上下移動(dòng)
DOWN = WIDTH 

# 錯(cuò)誤碼
ERR = -2333

# 用一維數(shù)組來表示二維的東西
# board表示蛇運(yùn)動(dòng)的矩形場(chǎng)地
# 初始化蛇頭在(1,1)的地方
# 初始蛇長(zhǎng)度為1
board = [0] * FIELD_SIZE #[0,0,0,……]
snake = [0] * (FIELD_SIZE+1)
snake[HEAD] = 1*WIDTH+1
snake_size = 1
# 與上面變量對(duì)應(yīng)的臨時(shí)變量,蛇試探性地移動(dòng)時(shí)使用
tmpboard = [0] * FIELD_SIZE
tmpsnake = [0] * (FIELD_SIZE+1)
tmpsnake[HEAD] = 1*WIDTH+1
tmpsnake_size = 1

# food:食物位置初始在(4, 7)
# best_move: 運(yùn)動(dòng)方向
food = 4 * WIDTH + 7
best_move = ERR

# 運(yùn)動(dòng)方向數(shù)組,游戲分?jǐn)?shù)(蛇長(zhǎng))
mov = [LEFT, RIGHT, UP, DOWN]           
score = 1 

# 檢查一個(gè)cell有沒有被蛇身覆蓋,沒有覆蓋則為free,返回true
def is_cell_free(idx, psize, psnake):
 return not (idx in psnake[:psize]) 

# 檢查某個(gè)位置idx是否可向move方向運(yùn)動(dòng)
def is_move_possible(idx, move):
 flag = False
 if move == LEFT:
  #因?yàn)閷?shí)際范圍是13*13,[1,13]*[1,13],所以idx為1時(shí)不能往左跑,此時(shí)取余為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:
  #這里向上的判斷畫圖很好理解,因?yàn)樵赱1,13]*[1,13]的實(shí)際運(yùn)動(dòng)范圍外,還有個(gè)
  #大框是圍墻,就是之前說的那幾個(gè)行列,下面判斷向下運(yùn)動(dòng)的條件也是類似的
  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值都變?yōu)榱说竭_(dá)食物的路徑長(zhǎng)度
# 如需要還原,則要重置它
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
 
# 廣度優(yōu)先搜索遍歷整個(gè)board,
# 計(jì)算出board中每個(gè)非SNAKE元素到達(dá)食物的路徑長(zhǎng)度
def board_BFS(pfood, psnake, pboard):
 queue = []
 queue.append(pfood)
 inqueue = [0] * FIELD_SIZE
 found = False
 # while循環(huán)結(jié)束后,除了蛇的身體,
 # 其它每個(gè)方格中的數(shù)字為從它到食物的曼哈頓間距
 while len(queue)!=0: 
  idx = queue.pop(0)#初始時(shí)idx是食物的坐標(biāo) 
  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: # 如果該點(diǎn)不是蛇的身體
     if pboard[idx+mov[i]] > pboard[idx]+1:#小于的時(shí)候不管,不然會(huì)覆蓋已有的路徑數(shù)據(jù)
      pboard[idx+mov[i]] = pboard[idx] + 1
     if inqueue[idx+mov[i]] == 0:
      queue.append(idx+mov[i])
 return found

# 從蛇頭開始,根據(jù)board中元素值,
# 從蛇頭周圍4個(gè)領(lǐng)域點(diǎn)中選擇最短路徑
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:
   #這里判斷最小和下面的函數(shù)判斷最大,都是先賦值,再循環(huán)互相比較
   min = pboard[psnake[HEAD]+mov[i]]
   best_move = mov[i]
 return best_move

# 從蛇頭開始,根據(jù)board中元素值,
# 從蛇頭周圍4個(gè)領(lǐng)域點(diǎn)中選擇最遠(yuǎn)路徑
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

# 檢查是否可以追著蛇尾運(yùn)動(dòng),即蛇頭和蛇尾間是有路徑的
# 為的是避免蛇頭陷入死路
# 虛擬操作,在tmpboard,tmpsnake中進(jìn)行
def is_tail_inside():
 global tmpboard, tmpsnake, food, tmpsnake_size
 tmpboard[tmpsnake[tmpsnake_size-1]] = 0 # 虛擬地將蛇尾變?yōu)槭澄?因?yàn)槭翘摂M的,所以在tmpsnake,tmpboard中進(jìn)行)
 tmpboard[food] = SNAKE # 放置食物的地方,看成蛇身
 result = board_BFS(tmpsnake[tmpsnake_size-1], tmpsnake, tmpboard) # 求得每個(gè)位置到蛇尾的路徑長(zhǎng)度
 for i in range(4): # 如果蛇頭和蛇尾緊挨著,則返回False。即不能follow_tail,追著蛇尾運(yùn)動(dòng)了
  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

# 讓蛇頭朝著蛇尾運(yùn)行一步
# 不管蛇身阻擋,朝蛇尾方向運(yùn)行
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) # 求得各個(gè)位置到達(dá)蛇尾的路徑長(zhǎng)度
 tmpboard[tmpsnake[tmpsnake_size-1]] = SNAKE # 還原蛇尾
 return choose_longest_safe_move(tmpsnake, tmpboard) # 返回運(yùn)行方向(讓蛇頭運(yùn)動(dòng)1步)

# 在各種方案都不行時(shí),隨便找一個(gè)可行的方向來走(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
 
#轉(zhuǎn)換數(shù)組函數(shù)
def shift_array(arr, size):
 for i in range(size, 0, -1):
  arr[i] = arr[i-1]

def new_food():#隨機(jī)函數(shù)生成新的食物
 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))

# 真正的蛇在這個(gè)函數(shù)中,朝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))
 #下面一行是把初始情況會(huì)出現(xiàn)的第一個(gè)白塊bug填掉
 pygame.draw.rect(playSurface,(255,255,0),Rect(0,0,18,18))
 # 刷新pygame顯示層
 pygame.display.flip() 
 
 # 如果新加入的蛇頭就是食物的位置
 # 蛇長(zhǎng)加1,產(chǎn)生新的食物,重置board(因?yàn)樵瓉砟切┞窂介L(zhǎng)度已經(jīng)用不上了)
 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 # 蛇尾變?yōu)閁NDEFINED,黑色
  pygame.draw.rect(playSurface,blackColour,Rect(18*(snake[snake_size]//WIDTH),18*(snake[snake_size]%WIDTH),18,18))
  # 刷新pygame顯示層
  pygame.display.flip() 

# 虛擬地運(yùn)行一次,然后在調(diào)用處檢查這次運(yùn)行可否可行
# 可行才真實(shí)運(yùn)行。
# 虛擬運(yùn)行吃到食物后,得到虛擬下蛇在board的位置
def virtual_shortest_move():
 global snake, board, snake_size, tmpsnake, tmpboard, tmpsnake_size, food
 tmpsnake_size = snake_size
 tmpsnake = snake[:] # 如果直接tmpsnake=snake,則兩者指向同一處內(nèi)存
 tmpboard = board[:] # board中已經(jīng)是各位置到達(dá)食物的路徑長(zhǎng)度了,不用再計(jì)算
 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 # 在蛇頭前加入一個(gè)新的位置
  # 如果新加入的蛇頭的位置正好是食物的位置
  # 則長(zhǎng)度加1,重置board,食物那個(gè)位置變?yōu)樯叩囊徊糠?SNAKE)
  if tmpsnake[HEAD] == food:
   tmpsnake_size += 1
   board_reset(tmpsnake, tmpsnake_size, tmpboard) # 虛擬運(yùn)行后,蛇在board的位置
   tmpboard[food] = SNAKE
   food_eated = True
  else: # 如果蛇頭不是食物的位置,則新加入的位置為蛇頭,最后一個(gè)變?yōu)榭崭?
   tmpboard[tmpsnake[HEAD]] = SNAKE
   tmpboard[tmpsnake[tmpsnake_size]] = UNDEFINED

# 如果蛇與食物間有路徑,則調(diào)用本函數(shù)
def find_safe_way():
 global snake, board
 safe_move = ERR
 # 虛擬地運(yùn)行一次,因?yàn)橐呀?jīng)確保蛇與食物間有路徑,所以執(zhí)行有效
 # 運(yùn)行后得到虛擬下蛇在board中的位置,即tmpboard
 virtual_shortest_move() # 該函數(shù)唯一調(diào)用處
 if is_tail_inside(): # 如果虛擬運(yùn)行后,蛇頭蛇尾間有通路,則選最短路運(yùn)行(1步)
  return choose_shortest_safe_move(snake, board)
 safe_move = follow_tail() # 否則虛擬地follow_tail 1步,如果可以做到,返回true
 return safe_move


#初始化pygame
pygame.init()
#定義一個(gè)變量用來控制游戲速度
fpsClock = pygame.time.Clock()
# 創(chuàng)建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():#循環(huán)監(jiān)聽鍵盤和退出事件
  if event.type == QUIT:#如果點(diǎn)了關(guān)閉
   print(score)#游戲結(jié)束后打印分?jǐn)?shù)
   pygame.quit()
   sys.exit()
  elif event.type == KEYDOWN:#如果esc鍵被按下
   if event.key==K_ESCAPE:
    print(score)#游戲結(jié)束后打印分?jǐn)?shù)
    pygame.quit()
    sys.exit()
 # 刷新pygame顯示層
 pygame.display.flip() 
 #畫圍墻,255,255,0是黃色,邊框是36是因?yàn)?,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),其它的元素值表示從該點(diǎn)運(yùn)動(dòng)到食物的最短路徑長(zhǎng)
 if board_BFS(food, snake, board):
  best_move = find_safe_way() # find_safe_way的唯一調(diào)用處
 else:
  best_move = follow_tail()
 if best_move == ERR:
  best_move = any_possible_move()
 # 上面一次思考,只得出一個(gè)方向,運(yùn)行一步
 if best_move != ERR: make_move(best_move)
 else:
  print(score)#游戲結(jié)束后打印分?jǐn)?shù)
  break
 # 控制游戲速度
 fpsClock.tick(20)#20看上去速度正好

以上是利用Python制作貪吃蛇及AI版貪吃蛇的案例分析的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI