手把手教你用Python實現貪吃蛇遊戲

首先我們看下游戲運行的效果圖

手把手教你用Python實現貪吃蛇遊戲

遊戲啟動界面

手把手教你用Python實現貪吃蛇遊戲

遊戲運行界面

手把手教你用Python實現貪吃蛇遊戲

遊戲結束界面

首先程序需要導入的Package:

<code>import pygame
import sys
import time
import random
from pygame.locals import */<code>

關於package pygame的問題(Windows系統):

  1. 在cmd窗口輸入pip list查看python是否正確安裝pygame,若沒有安裝,則進行下一步操作。
  2. 在cmd窗口中輸入如下命令
<code>pip install -i http://pypi.douban.com/simple --trusted-host pypi.douban.com paygame/<code>

pip會自動下載並安裝pygame。如果以上操作未成功,通常可通過檢查升級pip解決,輸入命令

<code>pip install -i http://e.pypi.python.org --trusted-host e.pypi.python.org --upgrade pip # 升級pip/<code>

3.pygame安裝完成後,確保py編譯器所配置的環境變量為安裝pygame的python版本。(pygame安裝後編譯器無法導入多數原因是py編譯器Python環境變量配置不正確)

初始化pygame

<code>pygame.init()
fpsClock = pygame.time.Clock()/<code>

創建pygame顯示層

<code>playSurface = pygame.display.set_mode((640,480))/<code>

定義標題

<code>pygame.display.set_caption('Snake')/<code>

加載資源圖片,game.ico放在當前.py文件同目錄下

<code>image = pygame.image.load('game.ico')/<code>

設置圖標(遊戲框左上角目標)

<code>pygame.display.set_icon(image)/<code>

定義顏色變量

<code>redColour = pygame.Color(255,0,0) 

blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)
LightGrey = pygame.Color(220,220,220)/<code>

定義gameOver函數,遊玩過程中觸發遊戲結束事件

<code>def gameOver(playSurface,score):
# 顯示GAME OVER 並定義字體以及大小
gameOverFont = pygame.font.Font('arial.ttf', 60)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 125)
playSurface.blit(gameOverSurf, gameOverRect)
# 顯示分數並定義字體和大小
scoreFont = pygame.font.Font('arial.ttf', 30)
scoreSurf = scoreFont.render('SCORE: ' + str(score), True, greyColour)
scoreRect = scoreSurf.get_rect()
scoreRect.midtop = (320, 225)

#顯示是否繼續
playSurface.blit(scoreSurf, scoreRect)
isFont = pygame.font.Font('arial.ttf', 25)
isSurf = isFont.render('按d繼續,按Esc退出,請在5秒內執行操作', True, redColour)
isRect = scoreSurf.get_rect()
isRect.midtop = (150, 325)
playSurface.blit(isSurf, isRect)
pygame.display.flip() # 刷新顯示界面
time.sleep(5)
for event in pygame.event.get() :
if event.type == QUIT:
break;
elif event.type == KEYDOWN :
if event.key == ord('d') or event.key == ord('D') or event.key == K_RIGHT:
initPosition()
return;
pygame.quit()
sys.exit()/<code>
<code>snakePosition = [100,100] #蛇頭位置
snakeSegments = [[100,100],[80,100],[60,100]] #初始長度為3個單位
raspberrySpawned = 1 #樹莓個數

raspberryPosition = [300,300] #樹莓位置
direction = 'right' #初始方向
changeDirection = direction
score = 0 #初始分數
isbegin = True/<code>

定義初始值函數,每次遊戲開始初始化遊戲相關參數,如樹莓的初始位置

<code>def initPosition():
#定義初始位置
global snakePosition,snakeSegments,raspberryPosition,raspberrySpawned,changeDirection,score,isbegin
snakePosition = [100,100] #蛇頭位置
snakeSegments = [[100,100],[80,100],[60,100]] #初始長度為3個單位
raspberrySpawned = 1 #樹莓個數
raspberryPosition = [300,300] #樹莓位置
direction = 'right' #初始方向
changeDirection = direction
score = 0 #初始分數
isbegin = True/<code>

遊戲開始畫面顯示

<code>while True:
if isbegin:
gameOverFont = pygame.font.Font('arial.ttf', 40)
gameOverSurf = gameOverFont.render('LOADING......', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop = (320, 50)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(3)
isbegin = False/<code>

檢測例如按鍵等pygame事件

<code> for event in pygame.event.get() :
if event.type == QUIT :
pygame.quit()
sys.exit()
elif event.type == KEYDOWN :
#判斷鍵盤事件

if event.key == K_RIGHT or event.key == ord('d'):
changeDirection = 'right'
if event.key == K_LEFT or event.key == ord('a'):
changeDirection = 'left'
if event.key == K_UP or event.key == ord('w'):
changeDirection = 'up'
if event.key == K_DOWN or event.key == ord('s'):
changeDirection = 'down'
if event.key == K_ESCAPE: #按esc退出遊戲
pygame.event.post(pygame.event.Event(QUIT))

#判斷是否輸入了反方向
if changeDirection == 'right' and not direction == 'left' :
direction = changeDirection
if changeDirection == 'left' and not direction == 'right' :
direction = changeDirection
if changeDirection == 'up' and not direction == 'down' :
direction = changeDirection
if changeDirection == 'down' and not direction == 'up' :
direction = changeDirection/<code>

根據方向移動蛇頭座標,並將蛇頭位置列入列表中

<code>    if direction == 'right':
snakePosition[0] += 20
if direction == 'left':
snakePosition[0] -= 20
if direction == 'up':
snakePosition[1] -= 20
if direction == 'down':
snakePosition[1] += 20
#將蛇頭位置列入列表中
snakeSegments.insert(0,list(snakePosition))/<code>

判斷是否吃到樹莓,如果吃到,則重新生成樹莓

<code>#判斷是否吃到樹莓
if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
raspberrySpawned = 0
else:
snakeSegments.pop() #每次將最後一單位蛇身踢出列表


#如果吃掉樹莓,則重新生成樹莓
if raspberrySpawned == 0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition = [int(x*20),int(y*20)]
raspberrySpawned = 1
score += 1/<code>

繪製並刷新pygame顯示層

<code>#繪製pygame顯示層
playSurface.fill(blackColour)
for position in snakeSegments[1:]: #蛇身為白色
pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
pygame.draw.rect(playSurface,LightGrey,Rect(snakePosition[0],snakePosition[1],20,20)) #蛇頭為灰色
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0],raspberryPosition[1],20,20)) #樹莓為紅色
#刷新pygame顯示層
pygame.display.flip()/<code>

判斷是否死亡(超出左右邊界,超出上下邊界,碰到自己身體)

<code>    if snakePosition[0] > 620 or snakePosition[0] < 0: #超出左右邊界
gameOver(playSurface,score)
if snakePosition[1] >460 or snakePosition[1] < 0 : #超出上下邊界
gameOver(playSurface,score)
for snakeBody in snakeSegments[1:]:
if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
gameOver(playSurface,score)/<code>

控制小蛇移動速度,蛇身越長,移動速度越快

<code>    if len(snakeSegments) < 40:
speed = 6 + len(snakeSegments)//4
else:
speed = 16
fpsClock.tick(speed)/<code>

有興趣的小夥伴可以自己試試,童年的回憶哈,一不小心暴露年齡了,哈哈。

謝謝各位的閱讀,喜歡點贊關注,不迷路。


分享到:


相關文章: