前言:做核心算法之前我们可以玩一玩这个小游戏来了解一下规则。2048在线试玩
运行效果:
代码案例:
# 2048小游戏# 1.将列表中零移动到列表的末尾
def move_zeroes():x = 0for i in range(len(list_nums)):if list_nums[i] != 0:list_nums[x], list_nums[i] = list_nums[i], list_nums[x]x += 1# 2.将相邻相等的合并
def merge():move_zeroes()for i in range(len(list_nums) - 1):if list_nums[i] == list_nums[i + 1]:list_nums[i] *= 2list_nums.pop(i + 1)list_nums.append(0)# 向左移动
def move_left():global list_numsfor item in list_map:list_nums = itemmerge()# 向左移动
def move_right():global list_numsfor item in list_map:list_nums = item[::-1]merge()item[::-1] = list_numsdef transpose():global list_maplist_map = list((list(item) for item in zip(*list_map)))# 向上移动
def move_up():transpose()move_left()transpose()# 向上移动
def move_down():transpose()move_right()transpose()def select_num():show_all()num = input("请操作(wsad):")if num == 'w':move_up()show_all()elif num =='s':move_down()show_all()elif num == 'a':move_left()show_all()elif num == 'd':move_right()show_all()def show_all():for item in list_map:for i in item:print(i, end='\t')print()if __name__ == '__main__':list_nums = None # type:list | Nonelist_map = [[2, 0, 2, 0],[0, 2, 0, 2],[4, 0, 4, 0],[0, 2, 0, 2]]while True:select_num()print("---------------------")