玩蛇系列之Pygame教程(十二)-- Tetromino俄羅斯方塊

失蹤人口回歸了!

失蹤人口回歸了!

失蹤人口回歸了!

實在是抱歉,這么久沒更新這個系列的文章了,(●'?'●),都是因為接了個坑爹的外包,改去干老本行擼android代碼了,感覺外包還是有點坑,錢沒賺到多少,人都累死了。

搞外包期間,一時勾起了我自己擼app的興趣,就沒時間寫文章了,順便給自己擼的應(yīng)用打個廣告
http://www.coolapk.com/apk/com.ckdroid.seachimg


有興趣可以下載下來玩玩,很好用的哦 (●'?'●)

好了,廢話不多說了,這次帶來的是俄羅斯方塊的實現(xiàn)。

先上個圖:

游戲主要是對各種形狀piece(S,Z,I,O,J,L,T)的處理,代碼注釋我寫得也比較清楚了,模塊都和上一篇 《玩蛇系列之Pygame教程(十一)-- Wormy貪吃蛇》 大同小異,甚至感覺比貪吃蛇還要好理解,主要還是python對數(shù)組的操作實在是太簡潔方便了,可能會有點不好理解,不過認(rèn)真多看一下,還是看的懂的。

友情提醒:
我已經(jīng)把代碼托管到github了,這樣對游戲用到的資源(圖片,字體,音效等)管理會方便些,你們也可以直接到github下載到所有的代碼和資源。
但是,對于代碼的學(xué)習(xí),我還是覺得不要簡單的復(fù)制粘貼,不然感覺還是領(lǐng)悟不到的

GitHub:https://github.com/ckdroid/PygameLearning

代碼:

# -*- coding: UTF-8 -*-
'''
Created on 2017年1月7日

@author: 小峰峰
'''

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



FPS = 25 #設(shè)置屏幕刷新率
WINDOWWIDTH = 640 # 設(shè)置窗口寬度
WINDOWHEIGHT = 480 # 設(shè)置窗口高度
BOXSIZE = 20 # 方格大小

# 放置俄羅斯方塊窗口的大小
BOARDWIDTH = 10 
BOARDHEIGHT = 20

BLANK = '.' # 代表空的形狀

MOVESIDEWAYSFREQ = 0.15 # ?
MOVEDOWNFREQ = 0.1 # 向下的頻率

# x方向的邊距
XMARGIN = int((WINDOWWIDTH - BOARDWIDTH * BOXSIZE) / 2)
# 距離窗口頂部的邊距
TOPMARGIN = WINDOWHEIGHT - (BOARDHEIGHT * BOXSIZE) - 5

# 定義幾個顏色
#               R    G    B
WHITE       = (255, 255, 255)
GRAY        = (185, 185, 185)
BLACK       = (  0,   0,   0)
RED         = (155,   0,   0)
LIGHTRED    = (175,  20,  20)
GREEN       = (  0, 155,   0)
LIGHTGREEN  = ( 20, 175,  20)
BLUE        = (  0,   0, 155)
LIGHTBLUE   = ( 20,  20, 175)
YELLOW      = (155, 155,   0)
LIGHTYELLOW = (175, 175,  20)




BORDERCOLOR = BLUE
BGCOLOR = BLACK
TEXTCOLOR = WHITE
TEXTSHADOWCOLOR = GRAY


COLORS      = (     BLUE,      GREEN,      RED,      YELLOW)
LIGHTCOLORS = (LIGHTBLUE, LIGHTGREEN, LIGHTRED, LIGHTYELLOW)

# 斷言 每一個顏色都應(yīng)該對應(yīng)有亮色
assert len(COLORS) == len(LIGHTCOLORS) # each color must have light color

# 模板的寬高
TEMPLATEWIDTH = 5
TEMPLATEHEIGHT = 5

# 形狀_S(S旋轉(zhuǎn)有2種)
S_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '..OO.',
                     '.OO..',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..OO.',
                     '...O.',
                     '.....']]

# 形狀_Z(Z旋轉(zhuǎn)有2種)
Z_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '.OO..',
                     '..OO.',
                     '.....'],
                    ['.....',
                     '..O..',
                     '.OO..',
                     '.O...',
                     '.....']]

# 形狀_I(I旋轉(zhuǎn)有2種)
I_SHAPE_TEMPLATE = [['..O..',
                     '..O..',
                     '..O..',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     'OOOO.',
                     '.....',
                     '.....']]

# 形狀_O(O旋轉(zhuǎn)只有一個)
O_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '.OO..',
                     '.OO..',
                     '.....']]

# 形狀_J(J旋轉(zhuǎn)有4種)
J_SHAPE_TEMPLATE = [['.....',
                     '.O...',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..OO.',
                     '..O..',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '...O.',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..O..',
                     '.OO..',
                     '.....']]

# 形狀_L(L旋轉(zhuǎn)有4種)
L_SHAPE_TEMPLATE = [['.....',
                     '...O.',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..O..',
                     '..OO.',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '.O...',
                     '.....'],
                    ['.....',
                     '.OO..',
                     '..O..',
                     '..O..',
                     '.....']]

# 形狀_T(T旋轉(zhuǎn)有4種)
T_SHAPE_TEMPLATE = [['.....',
                     '..O..',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..OO.',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '..O..',
                     '.....'],
                    ['.....',
                     '..O..',
                     '.OO..',
                     '..O..',
                     '.....']]

# 定義一個數(shù)據(jù)結(jié)構(gòu)存儲,對應(yīng)的形狀
PIECES = {'S': S_SHAPE_TEMPLATE,
          'Z': Z_SHAPE_TEMPLATE,
          'J': J_SHAPE_TEMPLATE,
          'L': L_SHAPE_TEMPLATE,
          'I': I_SHAPE_TEMPLATE,
          'O': O_SHAPE_TEMPLATE,
          'T': T_SHAPE_TEMPLATE}


def main():
    global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT # 定義全局變量
    
    pygame.init() # 初始化pygame
    
    FPSCLOCK = pygame.time.Clock() # 獲得pygame時鐘
    
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # 設(shè)置窗口
    
    BASICFONT = pygame.font.Font('resource/PAPYRUS.ttf', 18) # 設(shè)置基礎(chǔ)的字體
    
    BIGFONT = pygame.font.Font('resource/PAPYRUS.ttf', 100) # 設(shè)置大字體
    
    pygame.display.set_caption('Tetromino') # 窗口標(biāo)題

    showTextScreen('Tetromino') # 顯示開始畫面
    
    
    while True: # 游戲主循環(huán)
        
        # 二選一隨機播放背景音樂
        if random.randint(0, 1) == 0:
            pygame.mixer.music.load('resource/tetrisb.mid')
        else:
            pygame.mixer.music.load('resource/tetrisc.mid')
        pygame.mixer.music.play(-1, 0.0)
        
        # 運行游戲
        runGame()
        
        # 退出游戲后,結(jié)束播放音樂
        pygame.mixer.music.stop()
        
        # 顯示結(jié)束畫面
        showTextScreen('Game Over')


# 運行游戲
def runGame():
    
    # 在游戲開始前初始化變量
    
    board = getBlankBoard() # 獲得一個空的board
    
    lastMoveDownTime = time.time() # 最后向下移動的時刻
    
    lastMoveSidewaysTime = time.time() # 最后側(cè)向移動的時刻
    
    lastFallTime = time.time() # 最后的下降時間
    
    # 是否可以  向下,向左,向右
    # 注意:這里沒有向上可用
    movingDown = False 
    movingLeft = False
    movingRight = False
    
    # 分?jǐn)?shù)
    score = 0
    
    # 根據(jù)分?jǐn)?shù)計算等級和下降的頻率
    level, fallFreq = calculateLevelAndFallFreq(score)

    # 獲得新的形狀(當(dāng)前的形狀)
    fallingPiece = getNewPiece()
    
    # 獲得下一個形狀
    nextPiece = getNewPiece()

    while True: # 游戲循環(huán)體
        
        if fallingPiece == None: # 當(dāng)前沒有下降的形狀
            # 重新獲得新的形狀和下一個形狀
            fallingPiece = nextPiece
            nextPiece = getNewPiece()
            
            # 重置最后下降的時間
            lastFallTime = time.time()

            
            # 判斷界面上是否還有空位(方塊是否到頂),沒有則結(jié)束游戲
            if not isValidPosition(board, fallingPiece):
                return # can't fit a new piece on the board, so game over

        # 檢查是否有退出事件
        checkForQuit()
        
        for event in pygame.event.get(): # 事件處理loop
            
            if event.type == KEYUP: # KEYUP事件處理
                if (event.key == K_p): # 用戶按P鍵暫停
                    # Pausing the game
                    DISPLAYSURF.fill(BGCOLOR)
                    pygame.mixer.music.stop() #停止音樂
                    
                    showTextScreen('Paused') # 顯示暫停界面,until a key press
                    
                    pygame.mixer.music.play(-1, 0.0) # 繼續(xù)循環(huán)音樂
                    
                    # 重置各種時間
                    lastFallTime = time.time()
                    lastMoveDownTime = time.time()
                    lastMoveSidewaysTime = time.time()
                    
                elif (event.key == K_LEFT or event.key == K_a):
                    movingLeft = False
                elif (event.key == K_RIGHT or event.key == K_d):
                    movingRight = False
                elif (event.key == K_DOWN or event.key == K_s):
                    movingDown = False

            elif event.type == KEYDOWN: # KEYDOWN事件處理
                
                # 左右移動piece
                if (event.key == K_LEFT or event.key == K_a) and isValidPosition(board, fallingPiece, adjX=-1):
                    fallingPiece['x'] -= 1
                    movingLeft = True
                    movingRight = False
                    lastMoveSidewaysTime = time.time()

                elif (event.key == K_RIGHT or event.key == K_d) and isValidPosition(board, fallingPiece, adjX=1):
                    fallingPiece['x'] += 1
                    movingRight = True
                    movingLeft = False
                    lastMoveSidewaysTime = time.time()

                # UP或W鍵 旋轉(zhuǎn)piece (在有空間旋轉(zhuǎn)的前提下)
                elif (event.key == K_UP or event.key == K_w): # 正向旋轉(zhuǎn)
                    fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
                    if not isValidPosition(board, fallingPiece):
                        fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
                elif (event.key == K_q): # Q鍵,反向旋轉(zhuǎn)
                    fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
                    if not isValidPosition(board, fallingPiece):
                        fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])

                # DOWN或S鍵 使piece下降得更快
                elif (event.key == K_DOWN or event.key == K_s):
                    movingDown = True
                    if isValidPosition(board, fallingPiece, adjY=1):
                        fallingPiece['y'] += 1
                    lastMoveDownTime = time.time()

                # 空格鍵,直接下降到最下面且可用的地方
                elif event.key == K_SPACE:
                    movingDown = False
                    movingLeft = False
                    movingRight = False
                    for i in range(1, BOARDHEIGHT):
                        if not isValidPosition(board, fallingPiece, adjY=i):
                            break
                    fallingPiece['y'] += i - 1

        # 根據(jù)記錄的用戶輸入方向的變量來移動piece
        if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if movingLeft and isValidPosition(board, fallingPiece, adjX=-1):
                fallingPiece['x'] -= 1
            elif movingRight and isValidPosition(board, fallingPiece, adjX=1):
                fallingPiece['x'] += 1
            lastMoveSidewaysTime = time.time()

        if movingDown and time.time() - lastMoveDownTime > MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1):
            fallingPiece['y'] += 1
            lastMoveDownTime = time.time()

        # 自動下降piece
        if time.time() - lastFallTime > fallFreq:
            # see if the piece has landed
            if not isValidPosition(board, fallingPiece, adjY=1):
                # falling piece has landed, set it on the board
                addToBoard(board, fallingPiece)
                score += removeCompleteLines(board)
                level, fallFreq = calculateLevelAndFallFreq(score)
                fallingPiece = None
            else:
                # piece did not land, just move the piece down
                fallingPiece['y'] += 1
                lastFallTime = time.time()

        # 繪制屏幕上的所有東西
        DISPLAYSURF.fill(BGCOLOR)
        drawBoard(board)
        drawStatus(score, level)
        drawNextPiece(nextPiece)
        if fallingPiece != None:
            drawPiece(fallingPiece)

        pygame.display.update()
        FPSCLOCK.tick(FPS)


# 創(chuàng)建文本繪制對象
def makeTextObjs(text, font, color):
    surf = font.render(text, True, color)
    return surf, surf.get_rect()


# 退出
def terminate():
    pygame.quit()
    sys.exit()


# 檢查是否有按鍵被按下
def checkForKeyPress():
    # 通過事件隊列尋找KEYUP事件
    # 從事件隊列刪除KEYDOWN事件
    
    checkForQuit()

    for event in pygame.event.get([KEYDOWN, KEYUP]):
        if event.type == KEYDOWN:
            continue
        return event.key
    return None


# 顯示開始、暫停、結(jié)束畫面
def showTextScreen(text):
    # This function displays large text in the
    # center of the screen until a key is pressed.
    # Draw the text drop shadow
    titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTSHADOWCOLOR)
    titleRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2))
    DISPLAYSURF.blit(titleSurf, titleRect)

    # Draw the text
    titleSurf, titleRect = makeTextObjs(text, BIGFONT, TEXTCOLOR)
    titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
    DISPLAYSURF.blit(titleSurf, titleRect)

    # Draw the additional "Press a key to play." text.
    pressKeySurf, pressKeyRect = makeTextObjs('Press a key to play.', BASICFONT, TEXTCOLOR)
    pressKeyRect.center = (int(WINDOWWIDTH / 2), int(WINDOWHEIGHT / 2) + 100)
    DISPLAYSURF.blit(pressKeySurf, pressKeyRect)

    while checkForKeyPress() == None:
        pygame.display.update()
        FPSCLOCK.tick()


# 檢查是否有退出事件
def checkForQuit():
    for event in pygame.event.get(QUIT): # get all the QUIT events
        terminate() # terminate if any QUIT events are present
    for event in pygame.event.get(KEYUP): # get all the KEYUP events
        if event.key == K_ESCAPE:
            terminate() # terminate if the KEYUP event was for the Esc key
        pygame.event.post(event) # put the other KEYUP event objects back


# 根據(jù)分?jǐn)?shù)來計算等級和下落的頻率
def calculateLevelAndFallFreq(score):
    
    level = int(score / 10) + 1
    fallFreq = 0.27 - (level * 0.02)
    return level, fallFreq

# 隨機獲得一個新的形狀(形狀,方向,顏色)
def getNewPiece():
    # return a random new piece in a random rotation and color
    shape = random.choice(list(PIECES.keys()))
    newPiece = {'shape': shape,
                'rotation': random.randint(0, len(PIECES[shape]) - 1),
                'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2), # x居中
                'y': -2, # y在屏幕的上方,小于0
                'color': random.randint(0, len(COLORS)-1)}
    return newPiece


# 將一個piece添加到board中
def addToBoard(board, piece):
    # fill in the board based on piece's location, shape, and rotation
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:
                board[x + piece['x']][y + piece['y']] = piece['color']

# 清空board
def getBlankBoard():
    # create and return a new blank board data structure
    board = []
    for i in range(BOARDWIDTH):
        board.append([BLANK] * BOARDHEIGHT)
    return board

# board邊界
def isOnBoard(x, y):
    return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT

# piece在當(dāng)前的board里是否是一個合法可用的位置
def isValidPosition(board, piece, adjX=0, adjY=0):
    # Return True if the piece is within the board and not colliding
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            isAboveBoard = y + piece['y'] + adjY < 0
            if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK:
                continue
            if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):
                return False
            if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:
                return False
    return True

# 判斷當(dāng)前的這行是否被全部填滿
def isCompleteLine(board, y):
    # Return True if the line filled with boxes with no gaps.
    for x in range(BOARDWIDTH):
        if board[x][y] == BLANK:
            return False
    return True


# 檢查每一行,移除完成填滿的一行,將這一行上面的所有的都下降一行,返回完成填滿的總行數(shù)
def removeCompleteLines(board):
    numLinesRemoved = 0
    # 從-1開始從下往上檢查每一行
    y = BOARDHEIGHT - 1 
    while y >= 0:
        if isCompleteLine(board, y):
            # Remove the line and pull boxes down by one line.
            for pullDownY in range(y, 0, -1):
                for x in range(BOARDWIDTH):
                    board[x][pullDownY] = board[x][pullDownY-1]
            # Set very top line to blank.
            for x in range(BOARDWIDTH):
                board[x][0] = BLANK
            numLinesRemoved += 1
            # Note on the next iteration of the loop, y is the same.
            # This is so that if the line that was pulled down is also
            # complete, it will be removed.
        else:
            y -= 1 # move on to check next row up
    return numLinesRemoved

# 根據(jù)box的坐標(biāo)轉(zhuǎn)化成像素坐標(biāo)
def convertToPixelCoords(boxx, boxy):
    # Convert the given xy coordinates of the board to xy
    # coordinates of the location on the screen.
    return (XMARGIN + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))


# 繪制box
def drawBox(boxx, boxy, color, pixelx=None, pixely=None):
    # draw a single box (each tetromino piece has four boxes)
    # at xy coordinates on the board. Or, if pixelx & pixely
    # are specified, draw to the pixel coordinates stored in
    # pixelx & pixely (this is used for the "Next" piece).
    if color == BLANK:
        return
    if pixelx == None and pixely == None:
        pixelx, pixely = convertToPixelCoords(boxx, boxy)
    pygame.draw.rect(DISPLAYSURF, COLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 1, BOXSIZE - 1))
    pygame.draw.rect(DISPLAYSURF, LIGHTCOLORS[color], (pixelx + 1, pixely + 1, BOXSIZE - 4, BOXSIZE - 4))


# 繪制board
def drawBoard(board):
    # draw the border around the board
    pygame.draw.rect(DISPLAYSURF, BORDERCOLOR, (XMARGIN - 3, TOPMARGIN - 7, (BOARDWIDTH * BOXSIZE) + 8, (BOARDHEIGHT * BOXSIZE) + 8), 5)

    # fill the background of the board
    pygame.draw.rect(DISPLAYSURF, BGCOLOR, (XMARGIN, TOPMARGIN, BOXSIZE * BOARDWIDTH, BOXSIZE * BOARDHEIGHT))
    # draw the individual boxes on the board
    for x in range(BOARDWIDTH):
        for y in range(BOARDHEIGHT):
            drawBox(x, y, board[x][y])


# 繪制游戲分?jǐn)?shù)、等級信息
def drawStatus(score, level):
    # draw the score text
    scoreSurf = BASICFONT.render('Score: %s' % score, True, TEXTCOLOR)
    scoreRect = scoreSurf.get_rect()
    scoreRect.topleft = (WINDOWWIDTH - 150, 20)
    DISPLAYSURF.blit(scoreSurf, scoreRect)

    # draw the level text
    levelSurf = BASICFONT.render('Level: %s' % level, True, TEXTCOLOR)
    levelRect = levelSurf.get_rect()
    levelRect.topleft = (WINDOWWIDTH - 150, 50)
    DISPLAYSURF.blit(levelSurf, levelRect)


# 繪制各種形狀piece(S,Z,I,O,J,L,T)
def drawPiece(piece, pixelx=None, pixely=None):
    shapeToDraw = PIECES[piece['shape']][piece['rotation']]
    if pixelx == None and pixely == None:
        # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure
        pixelx, pixely = convertToPixelCoords(piece['x'], piece['y'])

    # draw each of the boxes that make up the piece
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            if shapeToDraw[y][x] != BLANK:
                drawBox(None, None, piece['color'], pixelx + (x * BOXSIZE), pixely + (y * BOXSIZE))


# 繪制提示信息,下一個現(xiàn)狀
def drawNextPiece(piece):
    # draw the "next" text
    nextSurf = BASICFONT.render('Next:', True, TEXTCOLOR)
    nextRect = nextSurf.get_rect()
    nextRect.topleft = (WINDOWWIDTH - 120, 80)
    DISPLAYSURF.blit(nextSurf, nextRect)
    # draw the "next" piece
    drawPiece(piece, pixelx=WINDOWWIDTH-120, pixely=100)


if __name__ == '__main__':
    main()

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容