前言
本文代码基于 python3.6 和 pygame1.9.4。
俄罗斯方块是儿时最经典的游戏之一,刚开始接触 pygame 的时候就想写一个俄罗斯方块。但是想到旋转,停靠,消除等操作,感觉好像很难啊,等真正写完了发现,一共也就 300 行代码,并没有什么难的。
先来看一个游戏截图,有点丑,好吧,我没啥美术细胞,但是主体功能都实现了,可以玩起来。
现在来看一下实现的过程。
外形
俄罗斯方块整个界面分为两部分,一部分是左边的游戏区域,另一部分是右边的显示区域,显示得分、速度、下一个方块样式等。这里就不放截图了,看上图就可以。
游戏区域跟贪吃蛇一样,是由一个个小方格组成的,为了看得直观,我特意画了网格线。
import sysimport pygamefrom pygame.locals import *SIZE = 30 # 每个小方格大小BLOCK_HEIGHT = 20 # 游戏区高度BLOCK_WIDTH = 10 # 游戏区宽度BORDER_WIDTH = 4 # 游戏区边框宽度BORDER_COLOR = (40, 40, 200) # 游戏区边框颜色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 # 右侧信息显示区域字体位置的X坐标 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) # 画游戏区域分隔线 pygame.draw.line(screen, BORDER_COLOR, (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0), (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH) # 画网格线 竖线 for x in range(BLOCK_WIDTH): pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1) # 画网格线 横线 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'下一个:') pygame.display.flip()if __name__ == '__main__': main()
方块
接下来就是要定义方块,方块的形状一共有以下 7 种:
新闻热点
疑难解答