2025年3月30日 星期日 甲辰(龙)年 月廿九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

Python实例:小游戏2048

时间:03-29来源:作者:点击数:75

本节教程通过 2048 的小游戏快速、完整地呈现了使用 Python 语言编程的过程,将之前介绍的内容有机地结合在了一起 。2048是一款流行于手机、平板等终端设备上的益智小游戏,最早于 2014 年 3 月发行,主界面如图 1 所示。 

2048小游戏的主界面
图 1:2048 小游戏的主界面

其游戏规则是:每次可以选择上下左右其中一个方向去滑动,每滑动一次,所有的数字方块都会往滑动的方向靠拢,系统也会在空白的地方随机出现一个数字方块,相同数字的方块在靠拢、相撞时会相加。系统给予的数字方块不是 2 就是 4,玩家要想办法在这小小的 16 格范围中凑出“2048”这个数字方块。

网友总结的游戏技巧有:

  • 最大数尽可能放在角落;
  • 数字按顺序紧邻排列;
  • 首先满足最大数和次大数在的那一列/行是满的;
  • 时刻注意活动较大数(32以上)旁边要有相近的数;
  • 以大数所在的一行为主要移动方向;
  • 不要急于“清理桌面”;
  • 根据游戏规则,可以整理出游戏的流程,如图 2 所示。
2048小游戏的主要流程
图 2:2048 小游戏的主要流程

根据流程图,可以将整个游戏程序大致分为三个部分:

  1. 程序初始化;
  2. 判断用户输入;
  3. 进入游戏主循环。

其中第三部分可以继续细分为以下三个部分:

  1. 等待操作;
  2. 判断操作并处理;
  3. 重新开始或退出。

为了游戏界面效果美观,这里使用了 pygame 库。安装 pygame 库的命令如下:

  • pip install pygame

安装过程如图 3 所示。

pygame库安装过程
图 3:pygame 库安装过程

下面我们继续关注 2048 小游戏。首先来看程序初始化,这里主要完成以下工作:导入所需模块,初始化棋盘和窗口界面,初始化各种组件和变量。根据游戏规则,棋盘大小为 4×4 共 16 格的正方形棋盘,简便起见我们使用二维列表存储每个格子里的数字。

定义棋盘并初始化每个格子存储的数字的语句如下:

board = [[0, 0, 0, 0]
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]]

以下语句用于初始化窗口的相关属性:

  • #每个格子的边长,单位:像素(下同)
  • box_size = 50
  • #格子之间的间距
  • box_gap = 5
  • #中心棋盘区域上边缘离窗口顶部的距离
  • top_of_window = 100
  • #中心棋盘区域下边缘离窗口底部的距离
  • bottom_of_window = 30
  • #中心棋盘区域左边缘离窗口左边的距离
  • left_of_window = 2 0
  • #窗口宽度
  • window_width = box_size * 4 + box_gap * 5 + left_of_window * 2
  • #窗口高度
  • window_height = top_of_window + box_gap * 5 + box_size * 4 + left_of_window + bottom_of_window
  • #初始化窗口
  • window = pygame.display.set_mode((window_width, window_height), 0, 32)
  • #窗口标题
  • pygame.display.set_caption("2048")
  • #得分
  • score = 0
  • #使用 pygame 内置颜色值定义一些颜色常量
  • OLDLACE = pygame.color.THECOLORS["oldlacen"]
  • IVORY = pygame.color.THECOLORS["ivory3"]
  • BLACK = pygame.color.THECOLORS["black"]
  • RED = pygame.color.THECOLORS["red"]
  • RED2 = pygame.color.THECOLORS["red2"]
  • DARKGOLD = pygame.color.THECOLORS["darkgoldenrodl"]
  • GOLD = pygame.color.THECOLORS["gold"]
  • GRAY = pygame.color.THECOLORS["gray41"]
  • CHOCOLATE = pygame.color.THECOLORS["chocolate"]
  • CHOCOLATE1 = pygame.color.THECOLORS["chocolate1"]
  • CORAL = pygame.color.THECOLORS["coral"]
  • CORAL2 = pygame.color.THECOLORS["coral2"]
  • ORANGED = pygame.color.THECOLORS["orangered"]
  • ORANGED2 = pygame.color.THECOLORS["orangered2"]
  • DARKORANGE = pygame.color.THECOLORS["darkorange"]
  • DARKORANGE2 = pygame.color.THECOLORS["darkorange2"]
  • FORESTGREEN = pygame.color.THECOLORS["forestgreen"]
  • #界面字体
  • FONTNAME = "SimHei"

绘制棋盘格子主要由 Box 类和 draw_box( ) 函数完成:

  • 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, (xz y, box_size, box_ size))
  • #定义棋盘格中数字的高度
  • text_height = int(box_size * 0.35)
  • #设置棋盘格中数字使用的字体
  • font_obj = pygame.font.SysFont(FONTNAME, text_height)
  • text_surface = font_obj.render(self.text, True, BLACK)
  • text_rect = text_surface.get_rect()
  • text_rect.center = (x + box_size / 2, y + box_size / 2)
  • surface.blit(text_surface, text_rect)
  • def draw_box():
  • giobal board
  • #定义棋盘上每个格子中不同数字的颜色
  • colors = {0 : (192, 192, 192) , 2 : (176, 224, 230) , 4 : (127, 255, 212), 8 : (135, 206, 235) , 16 : (64, 224, 208),
  • 32 : (0, 255, 255), 64 : (0, 201, 87), 128: (50, 205, 50), 256 : (34, 139, 34),
  • 512 : (0, 255, 127) , 1024 : (61, 145, 64), 2048 : (48, 128, 20), 4096 : (65, 105, 255),
  • 8192 : (8, 46, 84) , 16384 : (11, 23, 70), 32 768: (25, 25, 112), 65536 : (0, 0, 255) }
  • x, y = left_of_window, top_of_window
  • size = box_size * 4 + box gap * 5
  • pygame.draw.rect(window, BLACK, (x, y, size, size))
  • x, y = x + box_gap, y + box_gap
  • #使用嵌套循环绘制棋盘上所有格子
  • for i in range(4):
  • for j in range(4):
  • idx = board. [ i ] [ j ]
  • if idx == 0:
  • text =""
  • else :
  • text = str(idx)
  • if idx > 65536: idx = 65536
  • color = colors[idx]
  • box = Box((x, y), text, color) box.render(window)
  • x += box_size + box_gap
  • x = left_of_window + box_gap
  • y += box_size + box_gap

接下来需要初始化棋盘上开局的数字,来看 set_random_number( ) 函数:

  • def set_random_number():
  • pool =[]
  • for i in range(4):
  • for j in range (4):
  • if board[i][j] == 0:
  • pool. append. ( (if j ))
  • m = random.choice(pool)
  • pool.remove(m)
  • value = random.uniform(0, 1)
  • if value < 0.1:
  • value = 4
  • else :
  • value = 2
  • board[m[0]][m[1]] = value

其作用是在棋盘上随机选取两个格子,将其值设置为 2 或 4。

以下代码将绘制游戏窗口其余的界面内容:

  • #显示游戏名称
  • window.blit(write ("2048", height = 45, color = GOLD), (left_of_ window, left_of_window // 2))
  • #显示当前得分
  • window.blit(write("得分", height=14, color=FORESTGREEN), (left_of_window+105, left_of_window//2 + 5))
  • rect1 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+100, left_of_window//2 + 30, 60, 20))
  • text1 = write(str(score), height=14, color=GOLD)
  • text1_rect = text1.get_rect()
  • text1_rect.center = (left_of_window+100+30, left_of_window//2 + 40)
  • window.blit(textlf textl_rect)
  • #显示历史最高分
  • window.blit(write("最高", height=14, color=FORESTGREEN), (left_of_window+175, left_of_window//2 + 5))
  • rect2 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+165, left_of_window//2 + 30, 60, 20))
  • #读取历史最高分
  • best = read_best()
  • if best < score:
  • best = score
  • text2 = write(str(best), height=14, color=GOLD)
  • text2_rect = text2.get_rect()
  • text2_rect.center = (left_of_window+165+30, left_of_window//2 + 40)
  • window.blit(text2, text2_rect)
  • #显示游戏操作提示
  • window.blit(write("使用上下左右方向键控制", height=16, color=GRAY), (left_of_window, window_height - bottom_of_Window))

判断用户操作并处理是通过无限循环完成的,代码如下:

  • while True:
  • #通过事件机制获取当前用户操作
  • for event in pygame.event.get():
  • #用户操作为退出窗口或按下ESC键时写入最高分,并退出游戏窗口
  • if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
  • write_best(best)
  • pygame.quit ()
  • exit ()
  • #游戏没有正常结束时监听用户的操作
  • elif not gameover:
  • #用户按下键盘上的向上方向键
  • if event.type == KEYUP and event.key == K_UP:
  • up()
  • #用户按下键盘上的向下方向键
  • elif event.type ==KEYUP and event.key == K DOWN:
  • down()
  • #用户按下键盘上的向左方向键
  • elif event.type ==KEYUP and event.key == K_LEFT:
  • left ()
  • # 用户按下键盘上的向右方向键
  • elif event.type ==KEYUP and event.key == K_ RHGHT:
  • right ()
  • #开始新游戏
  • if newboard != board:
  • set_random_number()
  • newboard = deepcopy(board) draw_box()
  • gameover = is_over()
  • rect1 = pygame.draw.rect(window, FORESTGREEN,(left_ of_window+100, left_of_window//2 + 30, 60, 20))
  • text1 = write(str(score), height=14, color=GOLD)
  • text_rect = text1.get_rect()
  • text_rect.center = (left_of_window+100+30Aleft_of_window//2 + 4 0)
  • window.blit(text1, text_rect)
  • rect2 = pygame.draw.rect(window, FORESTGREEN, (left_of_window+165, left_of_window//2 + 30, 60, 20))
  • if best < score:
  • best = score
  • text2 = write(str(best), height=14, color=GOLD)
  • text2_rect = text2.get_rect()
  • text2_rect.center = (left_of_window+l65+30, left_of_window//2 + 4 0)
  • window.blit(text2, text2_rect)
  • #游戏正常结束(即用户合成了 2048或未合成2048但棋盘上已经无法继续下一步操作)
  • else :
  • write_best(best)
  • window.blit(write("游戏结束! ", height = 40, color = FORESTGREEN), (left_of_windowz window_height // 2))

为了实现游戏效果,还有几个关键函数需要定义:一是对棋盘上的数字求和,用于当用户按下上下左右操作键后合并棋盘上的数字,代码如下:

  • def combinate(L):
  • glbal score
  • ans = [0, 0, 0 , 0]
  • num =[]
  • for i in L:
  • if i != 0:
  • num. append. (i)
  • length = len(num)
  • #当不为0的数字有4个时
  • if length == 4:
  • if num[0] == num[1]:
  • ans[0] = num[0] + num[1]
  • score += ans[0]
  • if num[2] == num[3]:
  • ans[1] = num[2] + num [3]
  • score += ans[1]
  • else :
  • ans[1]=num[2]
  • ans [2]=num[3]
  • elif num[1] ==num[2]
  • ans [0]= num[0]
  • ans[1]= num[1] + num[2]
  • ans [2]= num[3]
  • score += ans[1]
  • elif num[2] ==num[3]
  • ans [ 0]= num[0]
  • ans[1]= num[1]
  • ans [2]= num[2] + num[3]
  • score += ans[2]
  • else :
  • for i in range(length):
  • ans[i] = num[i]
  • #当不为0的数字有3个时
  • elif length == 3:
  • if num[0] == num[1]:
  • ans[0] = num[0] + num[1]
  • ans[1] = num[2]
  • score += ans[0]
  • elif num[1] == num[2]:
  • ans [0] = num[0]
  • ans[1]=num[1] + num[2]
  • score += ans[1]
  • else :
  • for i in range(length):
  • ans[i] = num[i]
  • #当不为0的数字有2个时
  • elif length == 2:
  • if num[0] == num[1]:
  • ans[0] = num[0] + num[1]
  • score += ans[0]
  • else :
  • for i in range(length):
  • ans[i] = num[i]
  • #当不为0的数字只有1个时
  • elif length == 1:
  • ans[0] = num[0]
  • else :
  • pass
  • return ans

二是用户按下上下左右控制键后对应的操作,需要注意的是,我们定义存放棋盘上数字的列表是行式二维列表,故处理左右键相对容易,只需对左右相邻的数字判断是否应该合并即可,而处理上下键时则需要按照对应的列找到目标数字,再判断是否应该合并。代码如下:

  • def left():
  • for i in range(4):
  • temp = combinate (boa:rd [ i ])
  • for j in range (4):
  • board[i][j] = temp[j]
  • def right():
  • for i in range(4):
  • temp = combinate (boaird[i][::-1]
  • for j in range (4):
  • board[i][3-j] = temp[j]
  • def up():
  • for i in range(4):
  • to_comb =[]
  • for j in range (4):
  • to_comb.append(board[j][i])
  • temp = combinate(to_comb)
  • for k in range(4):
  • board[k][i] = temp[k]
  • def down():
  • for i in range(4):
  • to_comb =[]
  • for j in range (4):
  • to_comb.append(board[3-j][i])
  • temp = combina.te(to_comb)
  • for k in range (4):
  • board[3-k][i] = temp[k]

三是判断游戏是否结束的函数 is_over( )。按照游戏规则,当棋盘上仍然存在空格,或是同一行/列存在相邻且相同的数字时,游戏方可继续进行,否则游戏结束,该函数可做如下定义:

  • def is_over():
  • #棋盘上仍然存在空格
  • for i in range(4):
  • for j in range(4):
  • if board[i][j]==0:
  • return False
  • #同一行中存在相邻且相同的数字
  • for i in range(4):
  • for j in range(3):
  • if board[i][j] == board[i][j+1]:
  • return False
  • #同一列中存在相邻且相同的数字
  • for i in range(3):
  • for j in range(4):
  • if board[i][j] == board[i+1][j]:
  • return False
  • return True

至此,小游戏 2048 的主要内容和关键代码介绍完毕。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门