python使用pygame模块编写俄罗斯方块游戏的代码实例

文章先介绍了关于俄罗斯方块游戏的几个术语。

边框——由10*20个空格组成,方块就落在这里面。
盒子——组成方块的其中小方块,是组成方块的基本单元。
方块——从边框顶掉下的东西,游戏者可以翻转和改变位置。每个方块由4个盒子组成。
形状——不同类型的方块。这里形状的名字被叫做t, s, z ,j, l, i , o。如下图所示:

2015128143118229.png (490×159)

模版——用一个列表存放形状被翻转后的所有可能样式。全部存放在变量里,变量名字如s_shape_template or j_shape_template
着陆——当一个方块到达边框的底部或接触到在其他的盒子话,我们就说这个方块着陆了。那样的话,另一个方块就会开始下落。
下面先把代码敲一遍,试着了解作者意图,体会俄罗斯方块游戏的制作过程。

import random, time, pygame, sys
from pygame.locals import *
fps = 25
windowwidth = 640
windowheight = 480
boxsize = 20
boardwidth = 10
boardheight = 20
blank = ‘.’
movesidewaysfreq = 0.15
movedownfreq = 0.1
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)
assert len(colors) == len(lightcolors) # each color must have light color
templatewidth = 5
templateheight = 5
s_shape_template = [[‘…..’,
‘…..’,
‘..oo.’,
‘.oo..’,
‘…..’],
[‘…..’,
‘..o..’,
‘..oo.’,
‘…o.’,
‘…..’]]
z_shape_template = [[‘…..’,
‘…..’,
‘.oo..’,
‘..oo.’,
‘…..’],
[‘…..’,
‘..o..’,
‘.oo..’,
‘.o…’,
‘…..’]]
i_shape_template = [[‘..o..’,
‘..o..’,
‘..o..’,
‘..o..’,
‘…..’],
[‘…..’,
‘…..’,
‘oooo.’,
‘…..’,
‘…..’]]
o_shape_template = [[‘…..’,
‘…..’,
‘.oo..’,
‘.oo..’,
‘…..’]]
j_shape_template = [[‘…..’,
‘.o…’,
‘.ooo.’,
‘…..’,
‘…..’],
[‘…..’,
‘..oo.’,
‘..o..’,
‘..o..’,
‘…..’],
[‘…..’,
‘…..’,
‘.ooo.’,
‘…o.’,
‘…..’],
[‘…..’,
‘..o..’,
‘..o..’,
‘.oo..’,
‘…..’]]
l_shape_template = [[‘…..’,
‘…o.’,
‘.ooo.’,
‘…..’,
‘…..’],
[‘…..’,
‘..o..’,
‘..o..’,
‘..oo.’,
‘…..’],
[‘…..’,
‘…..’,
‘.ooo.’,
‘.o…’,
‘…..’],
[‘…..’,
‘.oo..’,
‘..o..’,
‘..o..’,
‘…..’]]
t_shape_template = [[‘…..’,
‘..o..’,
‘.ooo.’,
‘…..’,
‘…..’],
[‘…..’,
‘..o..’,
‘..oo.’,
‘..o..’,
‘…..’],
[‘…..’,
‘…..’,
‘.ooo.’,
‘..o..’,
‘…..’],
[‘…..’,
‘..o..’,
‘.oo..’,
‘..o..’,
‘…..’]]
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()
fpsclock = pygame.time.clock()
displaysurf = pygame.display.set_mode((windowwidth, windowheight))
basicfont = pygame.font.font(‘freesansbold.ttf’, 18)
bigfont = pygame.font.font(‘freesansbold.ttf’, 100)
pygame.display.set_caption(‘tetromino’)
showtextscreen(‘tetromino’)
while true: # game loop
if random.randint(0, 1) == 0:
pygame.mixer.music.load(‘tetrisb.mid’)
else:
pygame.mixer.music.load(‘tetrisc.mid’)
pygame.mixer.music.play(-1, 0.0)
rungame()
pygame.mixer.music.stop()
showtextscreen(‘game over’)
def rungame():
# setup variables for the start of the game
board = getblankboard()
lastmovedowntime = time.time()
lastmovesidewaystime = time.time()
lastfalltime = time.time()
movingdown = false # note: there is no movingup variable
movingleft = false
movingright = false
score = 0
level, fallfreq = calculatelevelandfallfreq(score)
fallingpiece = getnewpiece()
nextpiece = getnewpiece()
while true: # game loop
if fallingpiece == none:
# no falling piece in play, so start a new piece at the top
fallingpiece = nextpiece
nextpiece = getnewpiece()
lastfalltime = time.time() # reset lastfalltime
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(): # event handling loop
if event.type == keyup:
if (event.key == k_p):
# pausing the game
displaysurf.fill(bgcolor)
pygame.mixer.music.stop()
showtextscreen(‘paused’) # pause until a key press
pygame.mixer.music.play(-1, 0.0)
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:
# moving the piece sideways
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()
# rotating the piece (if there is room to rotate)
elif (event.key == k_up or event.key == k_w):
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): # rotate the other direction
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] – 1) % len(pieces[fallingpiece[‘shape’]])
if not isvalidposition(board, fallingpiece):
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] + 1) % len(pieces[fallingpiece[‘shape’]])
# making the piece fall faster with the down key
elif (event.key == k_down or event.key == k_s):
movingdown = true
if isvalidposition(board, fallingpiece, adjy=1):
fallingpiece[‘y’] += 1
lastmovedowntime = time.time()
# move the current piece all the way down
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
# handle moving the piece because of user input
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()
# let the piece fall if it is time to fall
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()
# drawing everything on the screen
displaysurf.fill(bgcolor)
drawboard(board)
drawstatus(score, level)
drawnextpiece(nextpiece)
if fallingpiece != none:
drawpiece(fallingpiece)
pygame.display.update()
fpsclock.tick(fps)
def maketextobjs(text, font, color):
surf = font.render(text, true, color)
return surf, surf.get_rect()
def terminate():
pygame.quit()
sys.exit()
def checkforkeypress():
# go through event queue looking for a keyup event.
# grab keydown events to remove them from the event queue.
checkforquit()
for event in pygame.event.get([keydown, keyup]):
if event.type == keydown:
continue
return event.key
return none
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
def calculatelevelandfallfreq(score):
# based on the score, return the level the player is on and
# how many seconds pass until a falling piece falls one space.
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),
‘y’: -2, # start it above the board (i.e. less than 0)
‘color’: random.randint(0, len(colors)-1)}
return newpiece
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’]
def getblankboard():
# create and return a new blank board data structure
board = []
for i in range(boardwidth):
board.append([blank] * boardheight)
return board
def isonboard(x, y):
return x >= 0 and x < boardwidth and y < boardheight 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 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 def removecompletelines(board): # remove any completed lines on the board, move everything above them down, and return the number of complete lines. numlinesremoved = 0 y = boardheight - 1 # start y at the bottom of the board 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
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))
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))
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 inpidual boxes on the board
for x in range(boardwidth):
for y in range(boardheight):
drawbox(x, y, board[x][y])
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)
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))
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()

代码一开始仍是一些变量的初始化,我们这里还加载了time模块,后面会用到。boxsize, boardwidth, boardheight与前面贪吃蛇相关初始化类似,使其与屏幕像素点联系起来。

movesidewaysfreq = 0.15
movedownfreq = 0.1

这两个变量的作用是这样的,每当游戏者按下左键或右键,下降的方块相应的向左或右移一个格子。然而游戏者也可以一直按下方向左键或右键让方块保持移动。movesidewaysfreq这个固定值表示如果一直按下方向左键或右键那么每0.15秒方块才会继续移动。
movedownfreq 这个固定值与上面的是一样的除了它是告诉当游戏者一直按下方向下键时方块下落的频率。

xmargin = int((windowwidth – boardwidth * boxsize) / 2)
topmargin = windowheight – (boardheight * boxsize) – 5

这两句的意思就看下面这个图就明白了。

2015128143232882.png (477×389)

然后是一些颜色值的定义。其中要注意的是colors和lightcolors,colors是组成方块的小方块的颜色,而lightcolors是围绕在小方块周围的颜色,为了强调出轮廓而设计的。
接着是定义方块了。游戏必须知道每个类型的方块有多少种形状,在这里我们用在列表中嵌入含有字符串的列表来构成这个模版,一个方块类型的模版含有了这个方块可能变换的所有形状。比如i的模版如下:

i_shape_template = [[‘..o..’,
‘..o..’,
‘..o..’,
‘..o..’,
‘…..’],
[‘…..’,
‘…..’,
‘oooo.’,
‘…..’,
‘…..’]]

templatewidth = 5和templateheight = 5则表示组成形状的行和列,如下图所示:

2015128143252602.png (316×322)

在看这段定义。

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}

pieces这个变量是一个字典,里面储存了所有的不同模版。因为每个又有一个类型的方块的所有变换形状。那就意味着pieces变量包含了每个类型的方块和所有的的变换形状。这就是存放我们游戏中用到的形状的数据结构。(又加强了对字典的理解)
主函数main()
主函数的前部分主要是创建一些全局变量和在游戏开始之前显示一个开始画面。

while true: # game loop
if random.randint(0, 1) == 0:
pygame.mixer.music.load(‘tetrisb.mid’)
else:
pygame.mixer.music.load(‘tetrisc.mid’)
pygame.mixer.music.play(-1, 0.0)
rungame()
pygame.mixer.music.stop()
showtextscreen(‘game over’)

上面这段代码中rungame()是程序的核心部分。循环中首先简单的随机决定采用哪个背景音乐。然后调用rungame(),当游戏失败,rungame()就会返回到main()函数,这时会停止背景音乐和显示游戏失败的画面。
当游戏者按下一个键,showtextscreen()显示游戏失败的函数就会返回。游戏循环会再次开始然后继续下一次游戏。
rungame()

def rungame():
# setup variables for the start of the game
board = getblankboard()
lastmovedowntime = time.time()
lastmovesidewaystime = time.time()
lastfalltime = time.time()
movingdown = false # note: there is no movingup variable
movingleft = false
movingright = false
score = 0
level, fallfreq = calculatelevelandfallfreq(score)
fallingpiece = getnewpiece()
nextpiece = getnewpiece()

在游戏开始和方块掉落之前,我们需要初始化一些跟游戏开始相关的变量。fallingpiece变量被赋值成当前掉落的变量,nextpiece变量被赋值成游戏者可以在屏幕next区域看见的下一个方块。

while true: # game loop
if fallingpiece == none:
# no falling piece in play, so start a new piece at the top
fallingpiece = nextpiece
nextpiece = getnewpiece()
lastfalltime = time.time() # reset lastfalltime
if not isvalidposition(board, fallingpiece):
return # can’t fit a new piece on the board, so game over
checkforquit()

这部分包含了当方块往底部掉落时的的所有代码。fallingpiece变量在方块着陆后被设置成none。这意味着nextpiece变量中的下一个方块应该被赋值给fallingpiece变量,然后一个随机的方块又会被赋值给nextpiece变量。lastfalltime变量也被赋值成当前时间,这样我们就可以通过fallfreq变量控制方块下落的频率。
来自getnewpiece函数的方块只有一部分被放置在方框区域中。但是如果这是一个非法的位置,比如此时游戏方框已经被填满(isvaildpostion()函数返回false),那么我们就知道方框已经满了,游戏者输掉了游戏。当这些发生时,rungame()函数就会返回。
事件处理循环
事件循环主要处理当翻转方块,移动方块时或者暂停游戏时的一些事情。
暂停游戏

if (event.key == k_p):
# pausing the game
displaysurf.fill(bgcolor)
pygame.mixer.music.stop()
showtextscreen(‘paused’) # pause until a key press
pygame.mixer.music.play(-1, 0.0)
lastfalltime = time.time()
lastmovedowntime = time.time()
lastmovesidewaystime = time.time()

如果游戏者按下p键,游戏就会暂停。我们应该隐藏掉游戏界面以防止游戏者作弊(否则游戏者会看着画面思考怎么处理方块),用displaysurf.fill(bgcolor)就可以实现这个效果。注意的是我们还要保存一些时间变量值。

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

停止按下方向键或asd键会把moveleft,moveright,movingdown变量设置为false.,表明游戏者不再想要在此方向上移动方块。后面的代码会基于moving变量处理一些事情。注意的上方向键和w键是用来翻转方块的而不是移动方块。这就是为什么没有movingup变量.

elif event.type == keydown:
# moving the piece sideways
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()

当左方向键按下(而且往左移动是有效的,通过调用isvaildposition()函数知道的),那么我们应该改变一个方块的位置使其向左移动一个通过让rallingpiece[‘x’]减1.isvaildposition()函数有个参数选项是adjx和adjy.平常,isvaildpostion()函数检查方块的位置通过函数的第二个参数的传递。然而,有时我们不想检查方块当前的位置,而是偏离当前方向几个格子的位置。
比如adjx=-1,则表示向左移动一个格子后方块的位置,为+1则表示向右移动一个格子后的位置。adjy同理如此。
movingleft变量会被设置为true,确保方块不会向右移动,此时movingright变量设置为false。同时需要更新lastmovesidewaystime的值。
这个lastmovesidewaystime变量设置的原因是这样。因为游戏者有可能一直按着方向键让其方块移动。如果moveleft被设置为true,程序就会知道方向左键已经被按下。如果在lastmovesidewaystime变量储存的时间基础上,0.15秒(储存在movesideaysfreq变量中)过去后,那么此时程序就会将方块再次向左移动一个格子。

elif (event.key == k_up or event.key == k_w):
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] + 1) % len(pieces[fallingpiece[‘shape’]])
if not isvalidposition(board, fallingpiece):
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] – 1) % len(pieces[fallingpiece[‘shape’]])

如果方向键上或w键被按下,那么就会翻转方块。上面的代码做的就是将储存在fallingpiece字典中的‘rotation’键的键值加1.然而,当增加的’rotation’键值大于所有当前类型方块的形状的数目的话(此变量储存在len(shapes[fallingpiece[‘shape’]])变量中),那么它翻转到最初的形状。

if not isvalidposition(board, fallingpiece):
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] – 1) % len(pieces[fallingpiece[‘shape’]])

如果翻转后的形状无效因为其中的一些小方块已经超过边框的范围,那么我们就要把它变回原来的形状通过将fallingpiece[‘rotation’)减去1.

elif (event.key == k_q): # rotate the other direction
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] – 1) % len(pieces[fallingpiece[‘shape’]])
if not isvalidposition(board, fallingpiece):
fallingpiece[‘rotation’] = (fallingpiece[‘rotation’] + 1) % len(pieces[fallingpiece[‘shape’]])

这段代码与上面之前的那段代码是一个意思,不同的是这段代码是当游戏者按下q键时翻转方块朝相反的方向。这里我们减去1而不是加1.

elif (event.key == k_down or event.key == k_s):
movingdown = true
if isvalidposition(board, fallingpiece, adjy=1):
fallingpiece[‘y’] += 1
lastmovedowntime = time.time()

如果下键被按下,游戏者此时希望方块下降的比平常快。fallingpiece[‘y’] += 1使方块下落一个格子(前提是这是一个有效的下落)movedown被设置为true,lastmocedowntime变量也被设置为当前时间。这个变量以后将被检查当方向下键一直按下时从而保证方块以一个比平常快的速率下降。

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

当游戏者按下空格键,方块将会迅速的下落至着陆。程序首先需要找出到它着陆需要下降个多少个格子。其中有关moving的三个变量都要被设置为false(保证程序后面部分的代码知道游戏者已经停止了按下所有的方向键)。

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()

这段代码是处理一直按下某个方向键时的情况。
如果用户按住键超过0.15秒。那么表达式(movingleft or movingright) and time.time() – lastmovesidewaystime > movesidewaysfreq:返回true。这样的话我们就可以移动方块向左或向右移动一个格子。
这个做法是很用的,因为如果用户重复的按下方向键让方块移动多个格子是很烦人的。好的做法是,用户可以按住方向键让方块保持移动直到松开键为止。最后别忘了更新lastmovesidewaystime变量。

if movingdown and time.time() – lastmovedowntime > movedownfreq and isvalidposition(board, fallingpiece, adjy=1):
fallingpiece[‘y’] += 1
lastmovedowntime = time.time()

这段代码的意思跟上面的代码差不多。

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()

方块自然下落的速率由lastfalltime变量决定。如果自从上个方块掉落了一个格子后过去了足够的时间,那么上面代码就会再让方块移动一个格子。

发表评论