python 简单实现2048,一看就会

文章目录5.Map三、心得

一、介绍
一共五个.py文件,三个模块+两个辅助
直接在cmd中执行 core.py 即可启动2048.
二、代码 1.初始化
import mapimport controlimport movemapsize = 4# 定义尺寸4*4MAP = map.Map(mapsize)# 初始化【面板】MOVE = move.Move(mapsize)# 初始化【移动面板的工具】CONTROL = control.Control() # 初始化【获取键盘的工具】MAP.printMap()# 显示初始面板GAMEOVER = False
2.循环主体
while GAMEOVER==False:dir = CONTROL.getdir()# 获取键盘方向ISCHANGE = MOVE.movemap(MAP,dir)# 根据方向执行操作,返回【面板】是否有变化if ISCHANGE:# 如果【面板】有变化LASTONE = MAP.addone()#肯定可以添加,返回是不是最后一个空MAP.printMap()#打印面板# 如果填充是最后一个空,则判断是否不能再操作GAMEOVER = MAP.isend() if LASTONE else False
3.
提供方法:获取键盘按键
详细说明参考:
class Control:def __init__(self):self.dir_ = None # dir一定要用成员变量,不然没办法在on_press中修改def getdir(self):self.dir_ = None# 如果是不是上下左右则返回Nonedef on_press(key):if key == Key.up:self.dir_ = Direction.UPelif key == Key.down:self.dir_ = Direction.DOWNelif key == Key.left:self.dir_ = Direction.LEFTelif key == Key.right:self.dir_ = Direction.RIGHTreturn Falselistener = Listener(on_press=on_press) # 创建监听器listener.start()# 开始监听,每次获取一个键listener.join()# 加入线程listener.stop()# 结束监听return self.dir_
4.Move
提供方法:根据移动的方向,修改map
()
class Move:def __init__(self,size):self.size_ = size# 尺寸和map一样self.needmerge_ = []# 临时存放需要合并的一行、一列self.oldmap_ = []# 用来与合并后的map作比较def movemap(self,map,dir):"""根据输入的方向移动如果map变化了返回True,如果没变化返回False"""if dir == Direction.UP:return self.moveup(map)elif dir == Direction.DOWN:return self.movedown(map)elif dir == Direction.LEFT:return self.moveleft(map)elif dir == Direction.RIGHT:return self.moveright(map)else:return False
() 和 () 差不多
() 和 () 差不多
()
def moveup(self,map):"""需求:2048执行向上操作深拷贝一份,用来比较是否发生变化思路:对每一列操作:获取这一列放到列表 needmerge_ 中合并 needmerge_从 needmerge_ 放回"""self.oldmap_ = copy.deepcopy(map.map_)for col in range(self.size_):self.needmerge_.clear()for row in range(self.size_):self.needmerge_.append(map.map_[row][col])self.merge()for row in range(self.size_):map.map_[row][col] = self.needmerge_[row]return self.oldmap_ != map.map_
()
【python 简单实现2048,一看就会】def moveleft(self,map):"""需求:2048执行向左操作深拷贝一份,用来比较是否发生变化思路:对每一行操作:获取每一行到 needmerge_合并放回"""self.oldmap_ = copy.deepcopy(map.map_)for row in range(self.size_):self.needmerge_=map.map_[row]self.merge()map.map_[row] = self.needmerge_.copy()return self.oldmap_ != map.map_

python 简单实现2048,一看就会

文章插图
merge()
def merge(self):"""合并 needmerge_,思路:去零->合并->去零->补零"""self.needmerge_ = [x for x in self.needmerge_ if x!=0]for i in range(len(self.needmerge_)-1):if(self.needmerge_[i]==self.needmerge_[i+1]):self.needmerge_[i]*=2self.needmerge_[i+1]=0self.needmerge_ = [x for x in self.needmerge_ if x!=0]while len(self.needmerge_).size_:self.needmerge_.append(0)