前言
本文代碼基于 python3.6 和 pygame1.9.4。
俄羅斯方塊是兒時(shí)最經(jīng)典的游戲之一,剛開始接觸 pygame 的時(shí)候就想寫一個(gè)俄羅斯方塊。但是想到旋轉(zhuǎn),??浚炔僮?,感覺(jué)好像很難啊,等真正寫完了發(fā)現(xiàn),一共也就 300 行代碼,并沒(méi)有什么難的。
先來(lái)看一個(gè)游戲截圖,有點(diǎn)丑,好吧,我沒(méi)啥美術(shù)細(xì)胞,但是主體功能都實(shí)現(xiàn)了,可以玩起來(lái)。

現(xiàn)在來(lái)看一下實(shí)現(xiàn)的過(guò)程。
外形
俄羅斯方塊整個(gè)界面分為兩部分,一部分是左邊的游戲區(qū)域,另一部分是右邊的顯示區(qū)域,顯示得分、速度、下一個(gè)方塊樣式等。這里就不放截圖了,看上圖就可以。
游戲區(qū)域跟貪吃蛇一樣,是由一個(gè)個(gè)小方格組成的,為了看得直觀,我特意畫了網(wǎng)格線。
import sysimport pygamefrom pygame.locals import *SIZE = 30 # 每個(gè)小方格大小BLOCK_HEIGHT = 20 # 游戲區(qū)高度BLOCK_WIDTH = 10 # 游戲區(qū)寬度BORDER_WIDTH = 4 # 游戲區(qū)邊框?qū)挾菳ORDER_COLOR = (40, 40, 200) # 游戲區(qū)邊框顏色SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5) # 游戲屏幕的寬SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT # 游戲屏幕的高BG_COLOR = (40, 40, 60) # 背景色BLACK = (0, 0, 0)def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)): imgText = font.render(text, True, fcolor) screen.blit(imgText, (x, y))def main(): pygame.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('俄羅斯方塊') font1 = pygame.font.SysFont('SimHei', 24) # 黑體24 font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10 # 右側(cè)信息顯示區(qū)域字體位置的X坐標(biāo) font1_height = int(font1.size('得分')[1]) score = 0 # 得分 while True: for event in pygame.event.get(): if event.type == QUIT: sys.exit() # 填充背景色 screen.fill(BG_COLOR) # 畫游戲區(qū)域分隔線 pygame.draw.line(screen, BORDER_COLOR, (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0), (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH) # 畫網(wǎng)格線 豎線 for x in range(BLOCK_WIDTH): pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1) # 畫網(wǎng)格線 橫線 for y in range(BLOCK_HEIGHT): pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1) print_text(screen, font1, font_pos_x, 10, f'得分: ') print_text(screen, font1, font_pos_x, 10 + font1_height + 6, f'{score}') print_text(screen, font1, font_pos_x, 20 + (font1_height + 6) * 2, f'速度: ') print_text(screen, font1, font_pos_x, 20 + (font1_height + 6) * 3, f'{score // 10000}') print_text(screen, font1, font_pos_x, 30 + (font1_height + 6) * 4, f'下一個(gè):') pygame.display.flip()if __name__ == '__main__': main()方塊
接下來(lái)就是要定義方塊,方塊的形狀一共有以下 7 種:
新聞熱點(diǎn)
疑難解答
圖片精選