免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1583 | 回复: 0

2048的python实现(基于OSC网友的代码修改) [复制链接]

论坛徽章:
0
发表于 2015-07-07 09:57 |显示全部楼层
2048的python实现。解决了原网友版本的两个小bug:
1. 原版游戏每次只消除一次,而不是递归消除。如 [2 ,2 ,2 ,2] 左移动的话应该是 [4, 4, 0, 0] , 而不是[8 , 0 , 0 ,0]
2. 对游戏结束的侦测有bug,已经改正。

原网友版本:http://www.oschina.net/code/snippet_1756807_35638
我的实现版本:http://my.oschina.net/u/923087/blog/286050

2048game.py
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul  1 14:15:39 2014

  4. @author: kelvin
  5. """

  6. import random

  7. class game2048:
  8.     totalScore = 0
  9.     v = [[2, 8, 8, 2],
  10.          [4, 2, 4, 8],
  11.          [2, 4, 2, 0],
  12.          [4, 2, 4, 0]]
  13.     '''
  14.     v = [[0, 0, 0, 0],
  15.          [0, 0, 0, 0],
  16.          [0, 0, 0, 0],
  17.          [0, 0, 0, 0]]
  18.     '''
  19.     def __init__(self):
  20.         for i in range(4):
  21.             self.v[i] = [random.choice([0,0,0,2,2,4]) for x in range(4)]


  22.     def display(self):
  23.         print('{0:4} {1:4} {2:4} {3:4}'.format(self.v[0][0], self.v[0][1], self.v[0][2], self.v[0][3]))
  24.         print('{0:4} {1:4} {2:4} {3:4}'.format(self.v[1][0], self.v[1][1], self.v[1][2], self.v[1][3]))
  25.         print('{0:4} {1:4} {2:4} {3:4}'.format(self.v[2][0], self.v[2][1], self.v[2][2], self.v[2][3]))
  26.         print('{0:4} {1:4} {2:4} {3:4}'.format(self.v[3][0], self.v[3][1], self.v[3][2], self.v[3][3]))
  27.         print('得分为:{0:4}'.format(self.totalScore))
  28.         print('游戏是否结束:{0:4}'.format(self.isOver()))
  29.     #重新排列
  30.     def align(self,vList, direction):
  31.         for i in range(vList.count(0)):
  32.             vList.remove(0)
  33.         zeros = [0 for x in range(4-len(vList))]
  34.         if direction == 'left':
  35.             vList.extend(zeros)
  36.         else:
  37.             vList[:0] = zeros
  38.     #将相同的元素相加,返回新增积分
  39.     def addSame(self,vList, direction):
  40.         increment=0
  41.         if direction == 'left':
  42.             for i in [0,1,2]:
  43.                 if vList[i]==vList[i+1] and vList[i+1]!=0:
  44.                     vList[i] *= 2
  45.                     vList[i+1] = 0
  46.                     increment += vList[i]
  47.         else:
  48.             for i in [3,2,1]:
  49.                 if vList[i]==vList[i-1] and vList[i-1]!=0:
  50.                     vList[i] *= 2
  51.                     vList[i-1] = 0
  52.                     increment += vList[i]
  53.         return increment
  54.     #处理行和方向,返回新增积分
  55.     def handle(self, vList, direction):
  56.         self.align(vList, direction)
  57.         increment = self.addSame(vList, direction)
  58.         self.align(vList, direction)
  59.         self.totalScore += increment #直接加到总值
  60.         return increment
  61.     #判断游戏是否结束
  62.     def judge(self):
  63.          
  64.         if self.isOver():
  65.             print('你输了,游戏结束!')
  66.             return False
  67.         else:
  68.             if self.totalScore >= 2048:
  69.                 print('你赢了,游戏结束!但是你还可以继续玩。')
  70.             return True
  71.     #判断游戏是否真正结束
  72.     def isOver(self):
  73.         N = self.calcCharNumber(0)
  74.         if N!=0:
  75.             return False
  76.         else:
  77.             for row in range(4):
  78.                 flag = self.isListOver(self.v[row])
  79.                 if flag==False:
  80.                     return False   
  81.             for col in range(4):
  82.                 # 将矩阵中一列复制到一个列表中然后处理
  83.                 vList = [self.v[row][col] for row in range(4)]
  84.                 flag = self.isListOver(vList)
  85.                 if flag==False:
  86.                     return False
  87.         return True
  88.      
  89.     #判断一个列表是否还可以合并
  90.     def isListOver(self, vList):
  91.         for i in [0,1,2]:
  92.             if vList[i]==vList[i+1] and vList[i+1]!=0:
  93.                 return False
  94.         return True
  95.     def calcCharNumber(self, char):
  96.         n = 0
  97.         for q in self.v:
  98.             n += q.count(char)
  99.         return n
  100.     def addElement(self):
  101.         # 统计空白区域数目 N
  102.         N = self.calcCharNumber(0)
  103.         if N!=0:
  104.             # 按2和4出现的几率为3/1来产生随机数2和4
  105.             num = random.choice([2, 2, 2, 4])
  106.             # 产生随机数k,上一步产生的2或4将被填到第k个空白区域
  107.             k = random.randrange(1, N+1)    #k的范围为[1,N]
  108.             n = 0
  109.             for i in range(4):
  110.                 for j in range(4):
  111.                     if self.v[i][j] == 0:
  112.                         n += 1
  113.                         if n == k:
  114.                             self.v[i][j] = num
  115.                             return

  116.                  
  117.     def moveLeft(self):
  118.         self.moveHorizontal('left')
  119.     def moveRight(self):
  120.         self.moveHorizontal('right')
  121.     def moveHorizontal(self, direction):
  122.         for row in range(4):
  123.             self.handle(self.v[row], direction)

  124.     def moveUp(self):
  125.         self.moveVertical('left')
  126.     def moveDown(self):
  127.         self.moveVertical('right')
  128.     def moveVertical(self, direction):
  129.         for col in range(4):
  130.             # 将矩阵中一列复制到一个列表中然后处理
  131.             vList = [self.v[row][col] for row in range(4)]
  132.             self.handle(vList, direction)
  133.             # 从处理后的列表中的数字覆盖原来矩阵中的值
  134.             for row in range(4):
  135.                 self.v[row][col] = vList[row]
  136.                  
  137.     #主要的处理函数
  138.     def operation(self):
  139.         op = input('operator:')
  140.         if op in ['a', 'A']:    # 向左移动
  141.             self.moveLeft()
  142.             self.addElement()
  143.         elif op in ['d', 'D']:  # 向右移动
  144.             self.moveRight()
  145.             self.addElement()
  146.         elif op in ['w', 'W']:  # 向上移动
  147.             self.moveUp()
  148.             self.addElement()
  149.         elif op in ['s', 'S']:  # 向下移动
  150.             self.moveDown()
  151.             self.addElement()
  152.         else:
  153.             print('错误的输入。请输入 [W, S, A, D] 或者是其小写')   
  154.    
  155. #开始
  156. print('输入:W(上移) S(下移) A(左移) D(右移), press <CR>.')
  157. g =game2048()
  158. flag = True
  159. while True:
  160.     g.display()
  161.     flag = g.judge()
  162.     g.operation()
  163.     flag = g.judge()
复制代码
1.jpg
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP