用 Python 把經典的俄羅斯方塊從頭寫了一遍,下落、堆疊、消行的那一刻,童年的樂趣又回來了。於是索性起了一個念頭:把那些既經典又真正好玩的小程式,用 Python 一個個重做出來,做成一個系列。正經寫程式的同時,也給自己留一點玩心,換個角度去寫程式。
原本打算寫一篇長文,把演算法思路與各個函式模組逐一說明;整理程式時才發現,我在程式碼裡寫的註解已經相當細緻,程式以外的文字反而顯得多餘。大道至簡,乾脆把程式碼直接貼上來,對照著註解讀,理解起來並不難。
方塊造型寫在設定檔 elsfk.cfg 中,只描述單一朝向的原始形狀組合,格式規則請見 getConf 的註解。
;1,1,1,1;; 1,1,1,0;1,0,0,0;; 1,1,1,0;0,0,1,0;; 0,1,0,0;1,1,1,0;; 1,1,0,0;1,1,0,0;; 1,1,0,0;0,1,1,0;; 0,1,1,0;1,1,0,0;;
完整程式碼:
# -*- coding:utf-8 -*-
'''
經典俄羅斯方塊
游戲基於python2.7、pygame1.9.2b8編寫。
游戲注解中出現的術語解釋:
舞台:整個游戲界面,包括堆疊區、成績等顯示區,下個出現方塊預告區。
堆疊區:游戲方塊和活動方塊形狀堆放區域,游戲中主要互動區。
方塊(基礎方塊):這裡的方塊是對基礎的小四方形統稱,每個方塊就是一個正方形。
方塊形狀:指一組以特定方式組合在一起的方塊,也就是大家常說的下落方塊形狀,比如長條,方形,L形等。
固實方塊:特指堆疊區中不能再進行移動,可被消除的基礎方塊集合。
version:1.0
author:lykyl
createdate:2016.9.29
'''
import random,copy
import pygame as pg
from pygame.locals import *
''' 常量聲明 '''
EMPTY_CELL=0 #空區標識,表示沒有方塊
FALLING_BLOCK=1 #下落中的方塊標識,也就是活動方塊。
STATIC_BLOCK=2 #固實方塊標識
''' 全局變量聲明 變量值以sysInit函數中初始化後的結果為准 '''
defaultFont=None #默認字體
screen=None #屏幕輸出對象
backSurface=None #圖像輸出緩沖畫板
score=0 #玩家得分記錄
clearLineScore=0 #玩家清除的方塊行數
level=1 #關卡等級
clock=None #游戲時鐘
nowBlock=None #當前下落中的方塊
nextBlock=None #下一個將出現的方塊
fallSpeed=10 #當前方塊下落速度
beginFallSpeed=fallSpeed #游戲初始時方塊下落速度
speedBuff=0 #下落速度緩沖變量
keyBuff=None #上一次按鍵記錄
maxBlockWidth=10 #舞台堆疊區X軸最大可容納基礎方塊數
maxBlockHeight=18 #舞台堆疊區Y軸最大可容納基礎方塊數
blockWidth=30 #以像素為單位的基礎方塊寬度
blockHeight=30 #以像素為單位的基礎方塊高度
blocks=[] #方塊形狀矩陣四維列表
stage=[] #舞台堆疊區矩陣二維列表
gameOver=False #游戲結束標志
pause=False #游戲暫停標志
def printTxt(content,x,y,font,screen,color=(255,255,255)):
'''顯示文本'''
imgTxt=font.render(content,True,color)
screen.blit(imgTxt,(x,y))
class point(object):
'''平面坐標點類'''
def __init__(self,x,y):
self.__x=x
self.__y=y
def getx(self):
return self.__x
def setx(self,x):
self.__x=x
x=property(getx,setx)
def gety(self):
return self.__y
def sety(self,y):
self.__y=y
y=property(gety,sety)
def __str__(self):
return "{x:"+"{:.0f}".format(self.__x)+",y:"+"{:.0f}".format(self.__y)+"}"
class blockSprite(object):
'''方塊形狀精靈類 下落方塊的定義全靠它了。'''
def __init__(self,shape,direction,xy):
self.shape=shape
self.direction=direction
self.xy=xy
def chgDirection(self,direction):
'''改變方塊的方向 args: direction:1為向右轉,0為向左轉。'''
dirNumb=len(blocks[self.shape])-1
if direction==1:
self.direction+=1
if self.direction>dirNumb:
self.direction=0
else:
self.direction-=1
if self.direction<0:
self.direction=dirNumb
def clone(self):
'''克隆本體'''
return blockSprite(self.shape,self.direction,point(self.xy.x,self.xy.y))
def _getBlock(self):
return blocks[self.shape][self.direction]
block = property(_getBlock)
def getConf(fileName):
'''從配置文件中讀取方塊形狀數據
每個方塊以4*4矩陣表示形狀,配置文件每行代表一個方塊,用分號分隔矩陣行,用逗號分隔矩陣列,
0表示沒有方塊,1表示有方塊。'''
global blocks
with open(fileName,'rt') as fp:
for temp in fp.readlines():
blocks.append([])
blocksNumb=len(blocks)-1
blocks[blocksNumb]=[]
blocks[blocksNumb].append([])
row=temp.split(";")
for r in range(len(row)):
col=[]
ct=row[r].split(",")
for c in range(len(ct)):
if ct[c]!="1":
col.append(0)
else:
col.append(1)
for c in range(len(ct)-1,3):
col.append(0)
blocks[blocksNumb][0].append(col)
for r in range(len(row)-1,3):
blocks[blocksNumb][0].append([0,0,0,0])
blocks[blocksNumb][0]=formatBlock(blocks[blocksNumb][0])
def sysInit():
'''系統初始化:pygame環境、全局變量、以及每個方塊形狀的四個方向矩陣。'''
global defaultFont,screen,backSurface,clock,blocks,stage,gameOver
global fallSpeed,beginFallSpeed,nowBlock,nextBlock,score,level,clearLineScore,pause
pg.init()
screen=pg.display.set_mode((500,550))
backSurface=pg.Surface((screen.get_rect().width,screen.get_rect().height))
pg.display.set_caption("block")
clock=pg.time.Clock()
pg.mouse.set_visible(False)
defaultFont=pg.font.Font("res/font/yh.ttf",16)
nowBlock=None
nextBlock=None
gameOver=False
pause=False
score=0
level=1
clearLineScore=0
beginFallSpeed=20
fallSpeed=beginFallSpeed-level*2
stage=[]
for y in range(maxBlockHeight):
stage.append([])
for x in range(maxBlockWidth):
stage[y].append(EMPTY_CELL)
for x in range(len(blocks)):
if len(blocks[x])<2:
t=blocks[x][0]
for i in range(3):
t=transform(t,1)
blocks[x].append(formatBlock(t))
def transform(block,direction=0):
'''生成指定方塊形狀轉換方向後的矩陣數據'''
result=[]
for y in range(4):
result.append([])
for x in range(4):
if direction==0:
result[y].append(block[x][3-y])
else:
result[y].append(block[3-x][y])
return result
def removeTopBlank(block):
'''清除方塊矩陣頂部空行數據'''
result=copy.deepcopy(block)
blankNumb=0
while sum(result[0])<1 and blankNumb<4:
del result[0]
result.append([0,0,0,0])
blankNumb+=1
return result
def formatBlock(block):
'''整理方塊矩陣數據,使方塊在矩陣中處於左上角的位置'''
result=removeTopBlank(block)
result=transform(result, 1)
result=removeTopBlank(result)
result=transform(result,0)
return result
def checkDeany(sprite):
'''檢查下落方塊是否與堆疊區固實方塊發生碰撞'''
topX=sprite.xy.x
topY=sprite.xy.y
for y in range(len(sprite.block)):
for x in range(len(sprite.block[y])):
if sprite.block[y][x]==1:
yInStage=topY+y
xInStage=topX+x
if yInStage>maxBlockHeight-1 or yInStage<0:
return True
if xInStage>maxBlockWidth-1 or xInStage<0:
return True
if stage[yInStage][xInStage]==STATIC_BLOCK:
return True
return False
def checkLine():
'''檢測堆疊區是否有可消除的整行固實方塊'''
global stage
clearCount=0
tmpStage=[]
for y in stage:
if sum(y)>=maxBlockWidth*2:
tmpStage.insert(0,maxBlockWidth*[0])
clearCount+=1
else:
tmpStage.append(y)
if clearCount>0:
stage=tmpStage
updateScore(clearCount)
return clearCount
def updateStage(sprite,updateType=1):
'''將下落方塊坐標數據更新到堆疊區數據中。
updateType:0清除,1動態加入,2固實加入。'''
global stage
topX=sprite.xy.x
topY=sprite.xy.y
for y in range(len(sprite.block)):
for x in range(len(sprite.block[y])):
if sprite.block[y][x]==1:
if updateType==0:
if stage[topY+y][topX+x]==FALLING_BLOCK:
stage[topY+y][topX+x]=EMPTY_CELL
elif updateType==1:
if stage[topY+y][topX+x]==EMPTY_CELL:
stage[topY+y][topX+x]=FALLING_BLOCK
else:
stage[topY+y][topX+x]=STATIC_BLOCK
def updateScore(clearCount):
'''更新玩家游戲記錄,並根據關卡數更新方塊下落速度'''
global score,fallSpeed,level,clearLineScore
prizePoint=0
if clearCount>1:
if clearCount<4:
prizePoint=clearCount**clearCount
else:
prizePoint=clearCount*5
score+=(clearCount+prizePoint)*level
if score>99999999:
score=0
clearLineScore+=clearCount
if clearLineScore>100:
clearLineScore=0
level+=1
if level>(beginFallSpeed/2):
level=1
fallSpeed=beginFallSpeed
fallSpeed=beginFallSpeed-level*2
return score
def drawStage(drawScreen):
'''在給定的畫布上繪制舞台'''
staticColor=30,102,76
activeColor=255,239,0
fontColor=200,10,120
baseRect=0,0,blockWidth*maxBlockWidth+1,blockHeight*maxBlockHeight+1
drawScreen.fill((180,200,170))
pg.draw.rect(drawScreen, staticColor, baseRect,1)
for y in range(len(stage)):
for x in range(len(stage[y])):
baseRect=x*blockWidth,y*blockHeight,blockWidth,blockHeight
if stage[y][x]==2:
pg.draw.rect(drawScreen, staticColor, baseRect)
elif stage[y][x]==1:
pg.draw.rect(drawScreen, activeColor, baseRect)
printTxt("Next:",320,350,defaultFont,backSurface,fontColor)
if nextBlock!=None:
for y in range(len(nextBlock.block)):
for x in range(len(nextBlock.block[y])):
baseRect=320+x*blockWidth,380+y*blockHeight,blockWidth,blockHeight
if nextBlock.block[y][x]==1:
pg.draw.rect(drawScreen, activeColor, baseRect)
printTxt("Level:%d" % level,320,40,defaultFont,backSurface,fontColor)
printTxt("Score:%d" % score,320,70,defaultFont,backSurface,fontColor)
printTxt("Clear:%d" % clearLineScore,320,100,defaultFont,backSurface,fontColor)
if gameOver:
printTxt("GAME OVER",230,200,defaultFont,backSurface,fontColor)
printTxt("<PRESS RETURN TO REPLAY>",200,260,defaultFont,backSurface,fontColor)
if pause:
printTxt("Game pausing",230,200,defaultFont,backSurface,fontColor)
printTxt("<PRESS RETURN TO CONTINUE>",200,260,defaultFont,backSurface,fontColor)
def process():
'''游戲控制及邏輯處理'''
global gameOver,nowBlock,nextBlock,speedBuff,backSurface,keyBuff,pause
if nextBlock is None:
nextBlock=blockSprite(random.randint(0,len(blocks)-1),random.randint(0,3),point(maxBlockWidth+4,maxBlockHeight))
if nowBlock is None:
nowBlock=nextBlock.clone()
nowBlock.xy=point(maxBlockWidth//2,0)
nextBlock=blockSprite(random.randint(0,len(blocks)-1),random.randint(0,3),point(maxBlockWidth+4,maxBlockHeight))
gameOver=checkDeany(nowBlock)
if gameOver:
updateStage(nowBlock,2)
tmpBlock=nowBlock.clone() #影子方塊形狀
for event in pg.event.get():
if event.type== pg.QUIT:
sys.exit()
pg.quit()
elif event.type==pg.KEYDOWN:
if event.key==pg.K_ESCAPE:
sys.exit()
pg.quit()
elif event.key==pg.K_RETURN:
if gameOver:
sysInit()
return
elif pause:
pause=False
else:
pause=True
return
elif not gameOver and not pause:
if event.key==pg.K_SPACE:
tmpBlock.chgDirection(1)
elif event.key==pg.K_UP:
tmpBlock.chgDirection(0)
if not gameOver and not pause:
keys=pg.key.get_pressed()
if keys[K_DOWN]:
tmpBlock.xy=point(tmpBlock.xy.x,tmpBlock.xy.y+1)
keyBuff=None
elif keys[K_LEFT]:
if keyBuff!=pg.K_LEFT:
tmpBlock.xy=point(tmpBlock.xy.x-1,tmpBlock.xy.y)
keyBuff=pg.K_LEFT
elif keys[K_RIGHT]:
if keyBuff!=pg.K_RIGHT:
tmpBlock.xy=point(tmpBlock.xy.x+1,tmpBlock.xy.y)
keyBuff=pg.K_RIGHT
else:
keyBuff=None
if not checkDeany(tmpBlock):
updateStage(nowBlock,0)
nowBlock=tmpBlock.clone()
speedBuff+=1
if speedBuff>=fallSpeed:
speedBuff=0
tmpBlock=nowBlock.clone()
tmpBlock.xy=point(nowBlock.xy.x,nowBlock.xy.y+1)
if not checkDeany(tmpBlock):
updateStage(nowBlock,0)
nowBlock=tmpBlock.clone()
updateStage(nowBlock,1)
else:
updateStage(nowBlock,2)
checkLine()
nowBlock=None
else:
updateStage(nowBlock,1)
drawStage(backSurface)
screen.blit(backSurface,(0,0))
pg.display.update()
clock.tick(40)
def main():
'''主程序'''
getConf("elsfk.cfg")
sysInit()
while True:
process()
if __name__ == "__main__":
main()
程式執行畫面: