1. 程式人生 > >如何用python做一個貪吃蛇小遊戲並給遊戲加上背景音樂(pygame的應用)

如何用python做一個貪吃蛇小遊戲並給遊戲加上背景音樂(pygame的應用)

匯入模組

import pygame
import sys
import time
import random
from pygame.locals import *

定義顏色變數

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)

定義gameOver函式,遊戲結束時的介面

def gameOver(playSurface, score):
    # 顯示GAME OVER並定義字型以及大小
    gameOverFont = pygame.font.Font('arial.ttf', 72)
    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', 48)
    scoreSurf = scoreFont.render('SCORE: ' + str(score), True, greyColour)
    scoreRect = scoreSurf.get_rect()
    scoreRect.midtop = (320, 225)
    playSurface.blit(scoreSurf, scoreRect)
    pygame.display.flip()  # 重新整理顯示介面
    # 休眠5秒後自動關閉
    time.sleep(5)
    pygame.quit()
    sys.exit()

定義main函式

def main():
    # 初始化pygame
    pygame.init()
    pygame.mixer.init()
    fpsClock = pygame.time.Clock()

    # 建立pygame顯示層
    playSurface = pygame.display.set_mode((640, 480))
    # 定義標題
    pygame.display.set_caption('Snake Go!')
    # 載入資源圖片,game.ico包含在最後的檔案中
    image = pygame.image.load('game.ico')
    # 設定圖示
    pygame.display.set_icon(image)
    # 載入音樂,MP3音樂檔案放在程式碼檔案所在資料夾中
    pygame.mixer.music.load("天地孤影任我行.mp3")

    # 初始化變數
    snakePosition = [100, 100]  # 蛇頭位置
    snakeSegments = [[100, 100], [80, 100], [60, 100]]  # 初始長度為3個單位
    raspberryPosition = [300, 300]  # 樹莓位置
    raspberrySpawned = 1  # 樹莓個數
    direction = 'right'  # 初始方向
    changeDirection = direction
    score = 0  # 初始分數
    while True:
         # 播放音樂天地孤影任我行,本人喜歡
        if pygame.mixer.music.get_busy()==False:
            pygame.mixer.music.play()
        # 檢測例如按鍵等pygame事件
        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

        # 根據方向移動蛇頭的座標
        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))

        # 判斷是否吃掉了樹莓
        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

        # 繪製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()

        # 判斷是否死亡
        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)

        # 控制遊戲速度,長度越長速度越快
        if len(snakeSegments) < 40:
            speed = 6 + len(snakeSegments) // 4
        else:
            speed = 16
        fpsClock.tick(speed)
if __name__ == "__main__":
    main()