跳至正文
View Categories

1 min read

主要内容 #

    1. 定义方格类
    2. 定义画方格的函数

1.定义方格类 #

首先我们来定义一个方格类来存储方格的各种属性,也是整个游戏里唯一的一个类。

class Box:
    def __init__(self, topleft, text, color):
        self.topleft = topleft
        self.text = text
        self.color = color

    def render(self, surface):
        x, y = self.topleft
        pygame.draw.rect(surface, self.color, (x, y, box_size, box_size), 0)  # 画方格
        text_height = 35
        font_obj = pygame.font.SysFont("arial", text_height)
        text_surface = font_obj.render(self.text, True, (0, 0, 0))  # 写数字
        text_rect = text_surface.get_rect()
        text_rect.center = (x + 50, y + 50)
        surface.blit(text_surface, text_rect)

将以上所有代码加入到上一课创建的项目文件中(该代码请置放在main()函数上面),运行,发现无任何变化,因为该部分只是定义了方格类,还未将方格画出。

2.定义画方格的函数 #

然后我们利用方格类来定义一个画方格的函数,这里我们简单用4*4的方格来演示,其实大家可以自定义方格个数:

def draw_box():  # 画游戏的方格
    colors = {0: (192, 192, 192), 2: (255, 255, 240), 4: (255, 250, 205), 8: (255, 165, 79),16: (250, 128, 114), 32: (255, 69, 0), 64: (238, 0, 0), 128: (238, 230, 133), 256: (255, 245, 0), 512: (238, 238, 0), 1024: (255, 255, 0), 2048: (255, 106, 106)} #定义不同数字对应不同的颜色
    x, y = left_of_screen, top_of_screen
    size = 425
    pygame.draw.rect(screen, (0, 0, 0), (x, y, size, size))
    x, y = x + box_gap, y + box_gap
    for i in range(4): # 这里的i,j就是4*4的方格,其实大家可以修改为其他大小的,前提是board也要增加对应的行列
        for j in range(4):
            idx = board[i][j]
            if idx == 0:# 如果是0则不显示数字
                text = ""
            else:
                text = str(idx)
            if idx > 2048:
                idx = 2048
            color = colors[idx]  # 颜色随数字变化,如果是其他数字则根据数字判断底色。
            box = Box((x, y), text, color) # 创建方格实体
            box.render(screen) # 显示到屏幕上
            x += box_size + box_gap
        x = left_of_screen + box_gap
        y += top_of_screen + box_gap

将以上所有代码加入到上一课创建的项目文件中(该代码请置放在main()函数和box类中间),运行,发现无任何变化,因为该部分只是定义了画方格的方法,并未调用该方法。

接下来需要在main()函数中添加如下代码,再次运行,即可在界面中查看画出方格的效果。

    # 在main()中找到如下这部分代码
	screen.blit(background, (0, 0)) # 背景展示

    # 并且在下一行增加如下这段代码
	draw_box()  # 初始化方格

小结 #

  • 本节主要介绍了2048游戏所需的方格以及如何画方格的方法。