「程序源代碼」python像素貪吃蛇

關鍵字:python 遊戲 貪吃蛇

「程序源代碼」python像素貪吃蛇

正文 | 內容

介紹

python像素貪吃蛇小遊戲,可以通過上下左右鍵控制蛇頭轉向,點擊回車鍵開始遊戲。簡單好玩

軟件架構

基於python3.0以上版本 基於pygame模塊開發

安裝教程

  1. 基於python3.0以上版本開發.開發時使用的是python3.7版本。

使用說明

  1. 基於python3.0以上版本開發,開發時使用的是python3.7版本。建議開發前本地安裝pygame/random/sys模塊
  2. 用pycharm打開源文件(一般pycharm會自動提示需要安裝的插件或者模塊)
  3. 點擊retroSnaker.py,直接運行即可

遊戲截圖

  1. 遊戲開始
  2. 遊戲中
  3. 遊戲結束
「程序源代碼」python像素貪吃蛇

"""

功能:python像素貪吃蛇

作者:程序源代碼

時間:2020-07-15

"""


# 導入相關模塊與函數

import random

import pygame

import sys

from pygame.locals import *


# 初始化pygame

pygame.init()

# 表明四個全局變量

global Speed

global Trackingtime

global Displayobject

global WindowTypeface

Speed = 8

Trackingtime = pygame.time.Clock() # 創建跟蹤時間對象

Displayobject = pygame.display.set_mode((640, 480)) # 設置窗口高寬640*480

WindowTypeface = pygame.font.SysFont('Calibri.ttf', 25) # 創建Typeface對象並設置字體和字號

pygame.display.set_caption('像素貪吃蛇') # 設置窗口標題

backgroundcolor = (255, 255, 255) # 設置窗口底色為純白色


# 偵測鍵盤操作

def CheckKeyboardPress():

if len(pygame.event.get(QUIT)) > 0:

pygame.quit()

sys.exit()

keyUpEvents = pygame.event.get(KEYUP)

if len(keyUpEvents) == 0:

return None

return keyUpEvents[0].key


# 遊戲開始界面設計

def DesignStartScreen():

global Speed

titleTypeface1 = pygame.font.SysFont('Calibri.ttf', 200)

titleTypeface2 = pygame.font.SysFont('Calibri.ttf', 60)

titleContent1 = titleTypeface1.render('RETRO SNAKER', True, (0, 0, 0), (0, 0, 0)) # 設置主界面文字和大小

titleContent2 = titleTypeface2.render('RETRO SNAKER', True, (255, 0, 0))

KeyboardContent = WindowTypeface.render('Press any key to start', True, (0, 0, 0))

Displayobject.fill(backgroundcolor)

revolveContent1 = pygame.transform.rotate(titleContent1, 0)

revolveRect1 = revolveContent1.get_rect()

revolveRect1.center = (640 / 2, 480 / 2)

Displayobject.blit(revolveContent1, revolveRect1)

revolveContent2 = pygame.transform.rotate(titleContent2, 0)

revolveRect2 = revolveContent2.get_rect()

revolveRect2.center = (640 / 2, 480 / 2)

Displayobject.blit(revolveContent2, revolveRect2)


# 獲得一個對象的rect,以便於設置其座標位置

KeyboardRect = KeyboardContent.get_rect()

KeyboardRect.topleft = (640 - 200, 480 - 30)

Displayobject.blit(KeyboardContent, KeyboardRect.topleft)

pygame.display.update()

Trackingtime.tick(Speed)

while True:

if CheckKeyboardPress():

pygame.event.get() # 清除事件隊列

return


# 遊戲結束界面設計

def DesignGameOverScreen():

gameOverTypeface = pygame.font.SysFont('Calibri.ttf', 100)

gameoverContent = gameOverTypeface.render('Game Over', True, (0, 0, 0))

KeyboardContent = WindowTypeface.render('Press any key to restart', True, (0, 0, 0))

gameoverRect = gameoverContent.get_rect()

gameoverRect.center = (640 / 2, 480 / 2)

Displayobject.blit(gameoverContent, gameoverRect)


# 獲得一個對象的rect,以便於設置其座標位置

KeyboardRect = KeyboardContent.get_rect()

KeyboardRect.topleft = (640 - 220, 480 - 30)

Displayobject.blit(KeyboardContent, KeyboardRect.topleft)

pygame.display.update()

pygame.time.wait(600)

while True:

if CheckKeyboardPress():

pygame.event.get() # 清除事件隊列

return


# 貪吃蛇蛇身設計

def DesignRetroSnaker(RetroSnakerCoords):

for coord in RetroSnakerCoords:

x = coord['x'] * 20 # 規定每行單元格的大小為20

y = coord['y'] * 20

RetroSnakerSegmentRect = pygame.Rect(x, y, 20, 20)

pygame.draw.rect(Displayobject, (0, 0, 255), RetroSnakerSegmentRect)

RetroSnakerInnerSegmentRect = pygame.Rect(x + 4, y + 4, 20 - 8, 20 - 8)

pygame.draw.rect(Displayobject, (173, 216, 230), RetroSnakerInnerSegmentRect)


# 蘋果設計

def DesignApple(coord):

x = coord['x'] * 20 # 規定單元格的大小為20

y = coord['y'] * 20

appleRect = pygame.Rect(x, y, 20, 20)

pygame.draw.rect(Displayobject, (255, 0, 0), appleRect)


# 得分分數設計

def DesignScore(score):

scoreContent = WindowTypeface.render('Score: %s' % (score), True, (0, 0, 0))

scoreRect = scoreContent.get_rect()

scoreRect.topleft = (640 - 100, 10)

Displayobject.blit(scoreContent, scoreRect)


# 邊框線設計

def DesignBorderline():

for x in range(0, 640, 640 - 1): # 繪製垂直線

pygame.draw.line(Displayobject, (0, 0, 0), (x, 0), (x, 480), 5)

for y in range(0, 480, 480 - 1): # 繪製平行線

pygame.draw.line(Displayobject, (0, 0, 0), (0, y), (640, y), 5)


# 設置遊戲主要運行機制

def GameRunning():

global Speed

# 設置隨機起點

startx = random.randint(5, 26) # 初始單元格位置橫向在(5, 26)範圍中選一個隨機數

starty = random.randint(5, 18) # 初始單元格位置縱向在(5, 18)範圍中選一個隨機數

RetroSnakerCoords = [{'x': startx, 'y': starty},

{'x': startx - 1, 'y': starty},

{'x': startx - 2, 'y': starty}] # RetroSnakerCoords:列表,貪吃蛇座標位置

direction = 'right' # 初始方向朝右

# 設置蘋果在一個隨機位置

apple = {'x': random.randint(0, 31), 'y': random.randint(0, 23)}


while True: # 遊戲主循環

# 判斷鍵盤事件

for event in pygame.event.get(): # 事件處理循環

if 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'


# 根據方向改變蛇頭的座標

if direction == 'up':

m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] - 1}

elif direction == 'down':

m = {'x': RetroSnakerCoords[0]['x'], 'y': RetroSnakerCoords[0]['y'] + 1}

elif direction == 'left':

m = {'x': RetroSnakerCoords[0]['x'] - 1, 'y': RetroSnakerCoords[0]['y']}

elif direction == 'right':

m = {'x': RetroSnakerCoords[0]['x'] + 1, 'y': RetroSnakerCoords[0]['y']}


# 通過向貪吃蛇移動的方向添加一個單元格來加長貪吃蛇

RetroSnakerCoords.insert(0, m)


# 偵測貪吃蛇是否吃到蘋果

if RetroSnakerCoords[0]['x'] == apple['x'] and RetroSnakerCoords[0]['y'] == apple['y']:

apple = {'x': random.randint(0, 31), 'y': random.randint(0, 23)} # 在隨機位置放置一個蘋果

Speed = Speed + 0.2

else:

del RetroSnakerCoords[-1] # 去除貪吃蛇的尾段


# 偵測貪吃蛇是否觸碰到窗口邊緣或自身

if RetroSnakerCoords[0]['x'] == -1 or RetroSnakerCoords[0]['x'] == 32 or RetroSnakerCoords[0]['y'] == -1 or \

RetroSnakerCoords[0]['y'] == 24:

return # 遊戲結束

for RetroSnakerBody in RetroSnakerCoords[1:]:

if RetroSnakerCoords[0]['x'] == RetroSnakerBody['x'] and RetroSnakerCoords[0]['y'] == RetroSnakerBody['y']:

return # 遊戲結束


# 繪製相關角色在窗口中

Displayobject.fill(backgroundcolor)

DesignRetroSnaker(RetroSnakerCoords)

DesignApple(apple)

DesignScore(len(RetroSnakerCoords) - 3)

DesignBorderline()

pygame.display.update() # 讓繪製的東西顯示在屏幕上

Trackingtime.tick(Speed)


# 主函數

if __name__ == '__main__':

DesignStartScreen() # 初始化遊戲開始界面

while True:

GameRunning() # 遊戲開始

DesignGameOverScreen() # 遊戲結束


分享到:


相關文章: