Python新手实现2048小游戏


Posted in Python onMarch 31, 2015

接触 Python 不久,看到很多人写2048,自己也捣鼓了一个,主要是熟悉Python语法。

程序使用Python3 写的,代码150行左右,基于控制台,方向键使用输入字符模拟。

演示图片

Python新手实现2048小游戏

2048.py

# -*- coding:UTF-8 -*-
#! /usr/bin/python3
 
import random
 
v = [[0, 0, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 0],
   [0, 0, 0, 0]]
 
def display(v, score):
    '''显示界面
 
    '''
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[0][0], v[0][1], v[0][2], v[0][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[1][0], v[1][1], v[1][2], v[1][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[2][0], v[2][1], v[2][2], v[2][3]))
    print('{0:4} {1:4} {2:4} {3:4}'.format(v[3][0], v[3][1], v[3][2], v[3][3]), '  Total score: ', score)
 
def init(v):
    '''随机分布网格值
     
    '''
    for i in range(4):
        v[i] = [random.choice([0, 0, 0, 2, 2, 4]) for x in range(4)]
 
def align(vList, direction):
    '''对齐非零的数字
 
    direction == 'left':向左对齐,例如[8,0,0,2]左对齐后[8,2,0,0]
    direction == 'right':向右对齐,例如[8,0,0,2]右对齐后[0,0,8,2]
    '''
 
    # 移除列表中的0
    for i in range(vList.count(0)):
        vList.remove(0)
    # 被移除的0
    zeros = [0 for x in range(4 - len(vList))]
    # 在非0数字的一侧补充0
    if direction == 'left':
        vList.extend(zeros)
    else:
        vList[:0] = zeros
     
def addSame(vList, direction):
    '''在列表查找相同且相邻的数字相加, 找到符合条件的返回True,否则返回False,同时还返回增加的分数
     
    direction == 'left':从右向左查找,找到相同且相邻的两个数字,左侧数字翻倍,右侧数字置0
    direction == 'right':从左向右查找,找到相同且相邻的两个数字,右侧数字翻倍,左侧数字置0
    '''
    score = 0
    if direction == 'left':
        for i in [0, 1, 2]:
            if vList[i] == vList[i+1] != 0: 
                vList[i] *= 2
                vList[i+1] = 0
                score += vList[i]
                return {'bool':True, 'score':score}
    else:
        for i in [3, 2, 1]:
            if vList[i] == vList[i-1] != 0:
                vList[i-1] *= 2
                vList[i] = 0
                score += vList[i-1]
                return {'bool':True, 'score':score}
    return {'bool':False, 'score':score}
 
def handle(vList, direction):
    '''处理一行(列)中的数据,得到最终的该行(列)的数字状态值, 返回得分
 
    vList: 列表结构,存储了一行(列)中的数据
    direction: 移动方向,向上和向左都使用方向'left',向右和向下都使用'right'
    '''
    totalScore = 0
    align(vList, direction)
    result = addSame(vList, direction)
    while result['bool'] == True:
        totalScore += result['score']
        align(vList, direction)
        result = addSame(vList, direction)
    return totalScore
     
 
def operation(v):
    '''根据移动方向重新计算矩阵状态值,并记录得分
    '''
    totalScore = 0
    gameOver = False
    direction = 'left'
    op = input('operator:')
    if op in ['a', 'A']:  # 向左移动
        direction = 'left'
        for row in range(4):
            totalScore += handle(v[row], direction)
    elif op in ['d', 'D']: # 向右移动
        direction = 'right'
        for row in range(4):
            totalScore += handle(v[row], direction)
    elif op in ['w', 'W']: # 向上移动
        direction = 'left'
        for col in range(4):
            # 将矩阵中一列复制到一个列表中然后处理
            vList = [v[row][col] for row in range(4)]
            totalScore += handle(vList, direction)
            # 从处理后的列表中的数字覆盖原来矩阵中的值
            for row in range(4):
                v[row][col] = vList[row]
    elif op in ['s', 'S']: # 向下移动
        direction = 'right'
        for col in range(4):
            # 同上
            vList = [v[row][col] for row in range(4)]
            totalScore += handle(vList, direction)
            for row in range(4):
                v[row][col] = vList[row]
    else:
        print('Invalid input, please enter a charactor in [W, S, A, D] or the lower')
        return {'gameOver':gameOver, 'score':totalScore}
 
    # 统计空白区域数目 N
    N = 0
    for q in v:
      N += q.count(0)
    # 不存在剩余的空白区域时,游戏结束
    if N == 0:
        gameOver = True
        return {'gameOver':gameOver, 'score':totalScore}
 
    # 按2和4出现的几率为3/1来产生随机数2和4
    num = random.choice([2, 2, 2, 4]) 
    # 产生随机数k,上一步产生的2或4将被填到第k个空白区域
    k = random.randrange(1, N+1)
    n = 0
    for i in range(4):
        for j in range(4):
            if v[i][j] == 0:
                n += 1
                if n == k:
                    v[i][j] = num
                    break
 
    return {'gameOver':gameOver, 'score':totalScore}
 
init(v)
score = 0
print('Input:W(Up) S(Down) A(Left) D(Right), press <CR>.')
while True:
    display(v, score)
    result = operation(v)
    if result['gameOver'] == True:
        print('Game Over, You failed!')
        print('Your total score:', score)
    else:
        score += result['score']
        if score >= 2048:
            print('Game Over, You Win!!!')
            print('Your total score:', score)

以上所述就是本文给大家分享的全部代码了,希望能够对大家学习Python有所帮助。

Python 相关文章推荐
详解Python使用simplejson模块解析JSON的方法
Mar 24 Python
Python运行报错UnicodeDecodeError的解决方法
Jun 07 Python
教你用 Python 实现微信跳一跳(Mac+iOS版)
Jan 04 Python
python自动登录12306并自动点击验证码完成登录的实现源代码
Apr 25 Python
python操作redis方法总结
Jun 06 Python
python 将print输出的内容保存到txt文件中
Jul 17 Python
python 实现数字字符串左侧补零的方法
Dec 04 Python
Python容器使用的5个技巧和2个误区总结
Sep 26 Python
python中property和setter装饰器用法
Dec 19 Python
Python面向对象之多态原理与用法案例分析
Dec 30 Python
pycharm配置python 设置pip安装源为豆瓣源
Feb 05 Python
python实现b站直播自动发送弹幕功能
Feb 20 Python
举例介绍Python中的25个隐藏特性
Mar 30 #Python
在Python的循环体中使用else语句的方法
Mar 30 #Python
python实现2048小游戏
Mar 30 #Python
利用一个简单的例子窥探CPython内核的运行机制
Mar 30 #Python
30分钟搭建Python的Flask框架并在上面编写第一个应用
Mar 30 #Python
编写同时兼容Python2.x与Python3.x版本的代码的几个示例
Mar 30 #Python
以Python的Pyspider为例剖析搜索引擎的网络爬虫实现方法
Mar 30 #Python
You might like
冰滴咖啡制作步骤
2021/03/03 冲泡冲煮
PHP读MYSQL中文乱码的解决方法
2006/12/17 PHP
Ubuntu中搭建Nginx、PHP环境最简单的方法
2015/03/05 PHP
php实现的简易扫雷游戏实例
2015/07/09 PHP
php轻量级的性能分析工具xhprof的安装使用
2015/08/12 PHP
PHP封装的多文件上传类实例与用法详解
2017/02/07 PHP
stripos函数知识点实例分享
2019/02/11 PHP
php实现断点续传大文件示例代码
2020/06/19 PHP
语义化 H1 标签
2008/01/14 Javascript
javascript显示选择目录对话框的代码
2008/11/10 Javascript
10个新的最有前途的JavaScript框架
2009/03/12 Javascript
JavaScript 继承详解(三)
2009/07/13 Javascript
jquery聚焦文本框与扩展文本框聚焦方法
2012/10/12 Javascript
jquery的选择器的使用技巧之如何选择input框
2013/09/22 Javascript
jquery prop的使用介绍及与attr的区别
2013/12/19 Javascript
jQuery使用height()获取高度需要注意的地方
2014/12/13 Javascript
微信小程序 倒计时组件实现代码
2016/10/24 Javascript
vue脚手架vue-cli的学习使用教程
2017/06/06 Javascript
jQuery实现对网页节点的增删改查功能示例
2017/09/18 jQuery
axios取消请求的实践记录分享
2018/09/26 Javascript
vue获取form表单的值示例
2019/10/29 Javascript
Element Badge标记的使用方法
2020/07/27 Javascript
vant 解决tab切换插件标题样式自定义的问题
2020/11/13 Javascript
python3基于TCP实现CS架构文件传输
2018/07/28 Python
英国著名的化妆品折扣网站:Allbeauty.com
2016/07/21 全球购物
韩国著名的在线综合购物网站:Akmall
2016/08/07 全球购物
台湾百利市购物中心:e-Payless
2017/08/16 全球购物
日本乐天德国站:Rakuten.de
2019/05/16 全球购物
高中毕业自我鉴定
2013/12/13 职场文书
创建精神文明单位实施方案
2014/03/08 职场文书
爱耳日活动总结
2014/04/30 职场文书
创业女性典型材料
2014/05/02 职场文书
小学生环保倡议书
2014/05/15 职场文书
鸟的天堂导游词
2015/01/31 职场文书
五四青年节比赛演讲稿
2015/03/18 职场文书
详解Java实践之适配器模式
2021/06/18 Java/Android