跳至正文
View Categories

1 min read

主要内容 #

    1. 得分展示模块
    2. 主函数模块

1.得分展示模块 #

该模块实现的功能为:根据要求,在方格上方展示2048和总分。
该部分代码如下:

def write(msg="Winning!!!", color=(255, 255, 0), height=14):
    myfont = pygame.font.SysFont("arial", height)
    mytext = myfont.render(msg, True, color)
    mytext = mytext.convert_alpha()
    return mytext

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

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

    # 在main()中找到如下这部分代码
	draw_box() # 初始化方格

    # 并且在下一行增加如下这段代码
    screen.blit(write("2048", height=60, color=(60, 179, 113)), (left_of_screen, left_of_screen // 2))
    screen.blit(write("score:", height=30, color=(0, 191, 255)), (left_of_screen + 150, left_of_screen // 2 + 5))

2.主函数模块 #

程序的主函数部分代码如下,之前添加的部分比如draw_box()函数在这部分也清晰展示:

def main():
    global score # 全局变量score
    screen.blit(background, (0, 0)) # 展示背景图
    init_board() # 初始化方格
    newboard = deepcopy(board) # copy
    gameover = is_over() # 判断是否结束
    draw_box() # 画出方格
    screen.blit(write("2048", height=60, color=(60, 179, 113)), (left_of_screen, left_of_screen // 2)) # 显示2048游戏名
    screen.blit(write("score:", height=30, color=(0, 191, 255)), (left_of_screen + 150, left_of_screen // 2 + 5)) # 显示得分
    while True:  # 循环按键
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
                pygame.quit()
                exit()
            elif not gameover:
                if event.type == KEYUP and event.key == K_UP:
                    up() #键盘按下“↑”调用up()函数
                elif event.type == KEYUP and event.key == K_DOWN:
                    down() #键盘按下“↓”调用down()函数
                elif event.type == KEYUP and event.key == K_LEFT:
                    left() #键盘按下“←”调用left()函数
                elif event.type == KEYUP and event.key == K_RIGHT:
                    right() #键盘按下“→”调用right()函数
                if newboard != board:  # 刷新
                    set_random_number()
                    newboard = deepcopy(board)
                    draw_box()
                gameover = is_over()
            else:
                screen.blit(write("Game Over!", height=40, color=(0, 0, 0)), (left_of_screen + 140, screen_height // 2))#显示game over

        pygame.display.update() # 这部分就是每次循环都要更新屏幕,这样能保持一直状态最新

        rect1 = pygame.draw.rect(screen, (60, 179, 113), (left_of_screen + 230, left_of_screen // 2 + 30, 60, 20)) # 画出矩形框
        text1 = write(str(score), height=20, color=(255, 255, 0)) # 写入得分
        text_rect = text1.get_rect()
        text_rect.center = (left_of_screen + 100 + 160, left_of_screen // 2 + 40) # 设置得分文本的位置
        screen.blit(text1, text_rect)

将以上所有代码加入到上一课创建的项目文件中(该代码请覆盖原来的main()函数),运行,即为最终的2048游戏。

至此完成了2048游戏所有的代码部分,后面还请大家尝试将方格扩展为8*8方格或者通关得分从2048提高到4096等更新操作来理解该游戏代码。

小结 #

  • 本节主要介绍了2048游戏所需的显示得分和主函数部分设计思想和代码介绍,至此2048游戏开发完成。