python小游戏——俄罗斯方块

最近研究pygame游戏制作板块,本次对于简单的俄罗斯方块进行介绍。

1.首先引入我们需要用到的pygame库和random库(pygame库基础知识请移步首页)

import pygame
import random

2.对pygame库进行初始化(一般来说,使用pygame库时先进行初始化,保证pygame的代码块可以正常运行)

pygame.init()

 3.设置一些初始数据(比如俄罗斯方块的每一个正方形边长box_size、行列数、rgb颜色块)

box_size = 30                       #小方格
box_width = 15                      #小方格列数
box_height = 20                     #小方格行数
width = box_size * box_width        #游戏区域宽度
height =  box_size * box_height     #游戏区域高度
side_width = 200                    #旁白区域宽度       
screen_width = width + side_width   #屏幕总宽度
white = (245,245,245)               #rgb表白色
black = (0, 0, 0)                   #黑色
line_color= (139,125,107)           #边线颜色  暗灰色
cube_colors = [(255,245,40),(175,175,20),(185,185,185),(155,0,0),(175,20,20),(0, 155,0),(20,175,20),(0,0,155),(20,20,175)]  #俄罗斯方块颜色组,在后续随机生成俄罗斯方块时会进行调用

4.设置屏幕(此处我们规定的屏幕为(650,600),规定标题栏,屏幕刷新频率)

pygame.display.set_mode()   创建窗口

pygame.display.set_caption()  标题栏

screen = pygame.display.set_mode((screen_width, height))    #屏幕(650,600)
pygame.display.set_caption("俄罗斯方块")      #标题栏
clock = pygame.time.Clock()        #创建时钟对象 (可以控制游戏循环频率)
FPS = 30      #设置屏幕刷新率

5.下面进行窗口主页面的绘画,先来一个例图。

 

 ①先绘制游戏区域横竖线,以及游戏区域最右侧分割线

pygame.draw.line(a,b,(c,d),(e,f))   画线,a为画线的范围(即screen屏幕),b为颜色(本程序游戏区域内部线为暗灰色,饱和度较低),(c,d)为所画线的起点坐标,(e,f)为所画线的终点坐标,线就是(c,d)和(e,f)所连成的线。

def draw_grids():                    #游戏区方格线
    for i in range(box_width):
        pygame.draw.line(screen, line_color,(i * box_size, 0), (i * box_size, height))     #横线

    for i in range(box_height):            
        pygame.draw.line(screen, line_color,(0, i * box_size), (width, i * box_size))   #竖线

    pygame.draw.line(screen, white,(box_size * box_width, 0),(box_size * box_width, box_size * box_height))   #最右侧竖线

②设置类show_text用于展示后续的文本

def show_text(surf, text, size, x, y, color=white):    #图像 文本 字体大小 位置 颜色 
    font = pygame.font.SysFont("方正粗黑宋简体", size)  #字体字号
    text_surface = font.render(text, True, color)      #文本 光滑 颜色
    text_rect = text_surface.get_rect()                #get_rect获取text_surface所在区域块
    text_rect.midtop = (x, y)                          #获取顶部的中间坐标
    surf.blit(text_surface, text_rect)                 #刷新surf本身的(text_surface\text_rect)字、区域

③对show_text进行调用,显示汉字部分

score = 0         #初始分数0
high_score = 0    #初始最高分0
historyscore = 0  #历史最高分
level = 1         #初始层数1
def draw_score():                    #得分
    show_text(screen, u'得分:{}'.format(score), 20, width + side_width // 2,200)    #得分,,20是size字号
 
def draw_maxscore():                   #得分
    show_text(screen, u'历史最高得分:{}'.format(high_score), 20, width + side_width // 2,100)    #最高得分

def draw_historyscore():                   #历史记录
    show_text(screen, u'历史记录:{}'.format(historyscore) ,13, width + side_width // 4,300)    

def show_gameover(screen):          #开局界面展示
    show_text(screen, '俄罗斯方块', 30, 225,250 )
    show_text(screen, '按任意键开始游戏', 20,225, 300)

6.规定全局屏幕矩阵为0(表示屏幕上此时没有任何俄罗斯方块在)

screen_color_matrix = []          #屏幕颜色矩阵 将整个屏幕的每一个小方格规定为0
for i in range(box_height):     
    screen_color_matrix.append([0 ]*box_width)

 

到此,我们简单的前期构造界面已经完成,下面我们进行俄罗斯方块类的构建。

7.俄罗斯方块类

①对每一个俄罗斯方块的形状进行定义,并归于元组

class CubeShape(object):                               #创建一个俄罗斯方块形状类(基类object)
    shapes = ['I', 'J', 'L', 'O', 'S', 'T', 'Z']       #其中形状,坐标,旋转,下落
    I = [[(0, -1), (0, 0), (0, 1), (0, 2)],
         [(-1, 0), (0, 0), (1, 0), (2, 0)]]
    J = [[(-2, 0), (-1, 0), (0, 0), (0, -1)],
         [(-1, 0), (0, 0), (0, 1), (0, 2)],
         [(0, 1), (0, 0), (1, 0), (2, 0)],
         [(0, -2), (0, -1), (0, 0), (1, 0)]]
    L = [[(-2, 0), (-1, 0), (0, 0), (0, 1)],
         [(1, 0), (0, 0), (0, 1), (0, 2)],
         [(0, -1), (0, 0), (1, 0), (2, 0)],
         [(0, -2), (0, -1), (0, 0), (-1, 0)]]
    O = [[(0, 0), (0, 1), (1, 0), (1, 1)]]
    S = [[(-1, 0), (0, 0), (0, 1), (1, 1)],
         [(1, -1), (1, 0), (0, 0), (0, 1)]]
    T = [[(0, -1), (0, 0), (0, 1), (-1, 0)],
         [(-1, 0), (0, 0), (1, 0), (0, 1)],
         [(0, -1), (0, 0), (0, 1), (1, 0)],
         [(-1, 0), (0, 0), (1, 0), (0, -1)]]
    Z = [[(0, -1), (0, 0), (1, 0), (1, 1)],
         [(-1, 0), (0, 0), (0, -1), (1, -1)]]
    shapes_with_dir = {                                           #存储形状的字典
        'I': I, 'J': J, 'L': L, 'O': O, 'S': S, 'T': T, 'Z': Z
    }

②在class类中,设置初始化类(随机生成一种颜色,确定俄罗斯方块的随机形状)

    def __init__(self):        #创建类,初始化类
        self.shape = self.shapes[random.randint(0, len(self.shapes) - 1)]    #随机生成任意一种形状
        self.center = (2, box_width // 2)     #俄罗斯方块(0,0)在屏幕上(2,8)
        self.dir = random.randint(0, len(self.shapes_with_dir[self.shape]) - 1)  #任意方块的任意一种例如I[0]或I[1]中的0、1
        self.color = cube_colors[random.randint(0, len(cube_colors) - 1)]    #随机生成任意一种颜色

 ③确定旋转后的每一个小方格放到游戏区域中间的绝对坐标位置

    def get_all_gridpos(self, center=None):      #将俄罗斯方块的相对位置转换为屏幕中的绝对位置
        curr_shape = self.shapes_with_dir[self.shape][self.dir]       #确定旋转后的形状
        if center is None:
            center = [self.center[0], self.center[1]]   #中心点[2,8]

        return [(cube[0] + center[0], cube[1] + center[1])          #旋转后的相对坐标的位置+中心点位置 ,即确定每一个小方格的位置
                for cube in curr_shape]

④设置冲突(碰壁无法旋转,下一个位置上有方块无法移动)

    def conflict(self, center):                                #设置冲突   
        for cube in self.get_all_gridpos(center):               #从确定中心的俄罗斯方块中选择一个小方格
            if cube[0] < 0 or cube[1] < 0 or cube[0] >= box_height or cube[1] >= box_width:  #超出屏幕之外,不合法
                return True
            if screen_color_matrix[cube[0]][cube[1]] is not 0:         # 不为0,说明之前已经有小方块存在了,也不合法,即不能旋转
                return True
        return False

⑤设置旋转、向下、向左、向右、p键规则

    def rotate(self):                  #旋转          
        new_dir = self.dir + 1        #下一个图像
        new_dir %= len(self.shapes_with_dir[self.shape])  #任意一种形状有几种旋转,例如I有两种,new_dir=2 =2/2余0,即new=0即第一个形状
        old_dir = self.dir     #old为初始形状   #因为不知道转动是否合法,需要先保存原先的方向
        self.dir = new_dir     #self现在为新形状
        if self.conflict(self.center):   #设置冲突,新老一样针对0形状
            self.dir = old_dir
            return False

    def down(self):       #向下
        # import pdb; pdb.set_trace()
        center = (self.center[0] + 1, self.center[1])  #中心点变化
        if self.conflict(center):    #如果冲突,返回f 
            return False
        self.center = center       #确定新的中心
        return True

    def left(self):      #向左
        center = (self.center[0], self.center[1] - 1)
        if self.conflict(center):
            return False
        self.center = center
        return True

    def right(self):    #向右
        center = (self.center[0], self.center[1] + 1)
        if self.conflict(center):
            return False
        self.center = center
        return True
    def pause(self):   #p暂停 p继续
        is_pause = True
        while is_pause:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_p:
                        is_pause =False
                    elif event.key == pygame.K_p:
                        is_pause =True
            pygame.display.update()

⑥对于俄罗斯方块的下降“过程”中的颜色以及边框进行绘画

    def draw(self):       #对于下落过程中的每一个小方块进行填色和边框线绘画
        for cube in self.get_all_gridpos():  #俄罗斯方块的每一个小方格
            pygame.draw.rect(screen, self.color,
                             (cube[1] * box_size, cube[0] * box_size,      #内部颜色
                              box_size, box_size))
            pygame.draw.rect(screen, white,
                             (cube[1] * box_size, cube[0] * box_size,     #线条框颜色
                              box_size, box_size),
                             1)
    

8.绘制静止后的颜色以及边框线

def draw_matrix():  #静止固定后的颜色及边框线
    for i, row in zip(range(box_height), screen_color_matrix):  #i=第几个小方格 row=屏幕颜色矩阵
        for j, color in zip(range(box_width), row):        #j=小方格宽度随机   color=row颜色
            if color is not 0:
                pygame.draw.rect(screen, color,            #落到底部固定后
                                 (j * box_size, i * box_size,    #俄罗斯方块内部颜色填充
                                  box_size, box_size))
                pygame.draw.rect(screen, white,
                                 (j * box_size, i * box_size,    #外部线条填充
                                  box_size, box_size), 2)

9.设置消除满行规则

def remove_full_line():        #消除满行
    global screen_color_matrix  #全局方块(判断是否为0)
    global score       #分数
 
    new_matrix = [[0] * box_width for i in range(box_height)]
    index = box_height - 1  #剩余行数
    n_full_line = 0   #满行数
    for i in range(box_height - 1, -1, -1):  #(24,-1)步进值为-1,输出0,1,2,3,4,5,6,7,8,9...24
        is_full = True
        for j in range(box_width):
            if screen_color_matrix[i][j] is 0:     #判断第i行的每一个j是否为0
                is_full = False
                continue
        if not is_full:
            new_matrix[index] = screen_color_matrix[i]
            index -= 1     #行数减一
        else:
            n_full_line += 1   #满行数+1
    score += n_full_line     #分数
    screen_color_matrix = new_matrix    #全局0更新

10.对于事件进行定义,并且获取运行事件(包括移动旋转p暂停o重新开始space空格功能)

running = True
stop = False
gameover = True
counter = 0  #计数器
live_cube = 0  #当前方块


while running:     #获取事件
    clock.tick(FPS)   #帧率
    for event in pygame.event.get():  #结束事件触发结束操作
        if event.type == pygame.QUIT:
            running = False    #如果鼠标点关闭,运行结束
        elif event.type == pygame.KEYDOWN:   #如果点击键盘
            if gameover:
                gameover = False  #游戏没有结束
                live_cube = CubeShape()
                break
            if event.key == pygame.K_LEFT:   #左  左移
                live_cube.left()
            elif event.key == pygame.K_RIGHT:   #右  右移
                live_cube.right()
            elif event.key == pygame.K_DOWN:  #下  下移
                live_cube.down()
            elif event.key == pygame.K_UP:  #上  旋转
                live_cube.rotate()
            elif event.key ==pygame.K_p:  #p暂停游戏
                live_cube.pause()
            elif event.key == pygame.K_SPACE:  #空格  加速下降
                while live_cube.down() == True:
                    pass
            elif event.key == pygame.K_o:    #o重新开始游戏
                gameover = True
                score = 0
                live_cube = 0
                screen_color_matrix = [[0] * box_width for i in range(box_height)]  #游戏矩阵为0
            remove_full_line()

    if gameover is False and counter % (FPS // level) == 0:
        if live_cube.down() == False:               #如果当前物块不能下降
            for cube in live_cube.get_all_gridpos():   #从当前俄罗斯方块选择一个小方格
                screen_color_matrix[cube[0]][cube[1]] = live_cube.color  #屏幕颜色矩阵、确定静止颜色
            live_cube = CubeShape()
            if live_cube.conflict(live_cube.center):  #冲突
                gameover = True   #游戏结束
                historyscore = score
                score = 0
                live_cube = 0
                screen_color_matrix = [[0] * box_width for i in range(box_height)]  #游戏矩阵为0
                
                # 消除满行
        remove_full_line()

    

11.最后对前期所有的绘画即其他函数进行调用,对历史分数和历史最高分记录进行规定。

    counter += 1
    # 更新屏幕
    screen.fill(black)
    draw_grids()  #调用画出游戏区域方格线
    draw_matrix()   #画出静止后的俄罗斯方块
    draw_score()   #分数
    draw_historyscore()
    draw_maxscore()  #最高分数
    if high_score <= score:
        high_score = score    
    else:
        high_score =high_score
    if live_cube is not 0:  #最后显示游戏结束界面
        live_cube.draw()
    if gameover:
        show_gameover(screen)
    pygame.display.update()  #刷新屏幕

到此,本次俄罗斯方块的完整代码已经分块讲述完毕。

程序bug:

①只有俄罗斯方块到(2,8)点,就是在(2,8)点产生物块时,无法再次进行移动,游戏结束。

②下落速度变化过慢。

③无法继续上次游戏(需要用到file存储),但是此次代码只要放到一个py中就可以应用。

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
青葱年少的头像青葱年少普通用户
上一篇 2023年5月28日
下一篇 2023年5月28日

相关推荐