百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

打扑克嘛?Python教你“经典纸牌游戏21点”玩法

itomcoil 2025-09-09 00:17 2 浏览

导语


昨天不是周天嘛?


你们在家放松一般都会做什么呢?


周末逛逛街,出去走走看电影......这是你们的周末。


程序员的周末就是在家躺尸唐诗躺尸,偶尔加班加班加班,或者跟着几个朋友在家消遣时间打打麻将,扑克牌玩一下!


尤其是放长假【ps:也没啥假,长假就是过年】在老家的时候,亲戚尤其多,七大姑八大姨的一年好不容易聚一次,打打麻将跟扑克这是常有的事儿,联络下感情这是最快的方式~

说起打扑克,我们经常就是玩儿的二百四、炸金花、三个打一个那就是叫啥名字来着,容我想想......


话说真词穷,我们那都是方言撒,我翻译不过来普通话是叫什么了,我估计240你们也没听懂是啥,23333~


今天的话小编是带大家做一款21点的扑克游戏!


有大佬可优化一下这个代码,做一个精致豪华的界面就好了~~



正文


游戏规则:21点又名黑杰克,该游戏由2到6个人玩,使用除大小王之外的52张牌,游戏者的目标是使手中的牌的点数之和不超过21点且尽量大。当使用1副牌时,以下每种牌各一张(没有大小王):



(1)初始化玩家数:


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def iniGame():
    global playerCount, cards
    while(True):
        try:
            playerCount = int(input('输入玩家数:'))
        except ValueError:
            print('无效输入!')
            continue
        if playerCount < 2:
            print('玩家必须大于1!')
            continue
        else:
            break
    try:
        decks = int(input('输入牌副数:(默认等于玩家数)'))
    except ValueError:
        print('已使用默认值!')
        decks = playerCount
    print('玩家数:', playerCount, ',牌副数:', decks)
    cards = getCards(decks)  # 洗牌</span></span></span>

(2)建立了玩家列表,电脑跟玩家对战。


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def createPlayerList():
    global playerList
    playerList = []
    for i in range(playerCount):
        playerList += [{'id': '', 'cards': [], 'score': 0}].copy()
        playerList[i]['id'] = '电脑' + str(i+1)
    playerList[playerCount-1]['id'] = '玩家'
    random.shuffle(playerList)  # 为各玩家随机排序</span></span></span>

(3)开始会设置2张明牌玩法都可以看到点数。


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def gameStart():
    print('为各玩家分2张明牌:')
    for i in range(playerCount):  # 为每个玩家分2张明牌
        deal(playerList[i]['cards'], cards, 2)
        playerList[i]['score'] = getScore(playerList[i]['cards'])  # 计算初始得分
        print(playerList[i]['id'], ' ', getCardName(playerList[i]['cards']),
              ' 得分 ', playerList[i]['score'])
        time.sleep(1.5)</span></span></span>


(4)游戏为电脑跟玩家依次分发第三张暗牌,这是别人看不到的。


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def gamePlay():
    for i in range(playerCount):
        print('当前', playerList[i]['id'])
        if playerList[i]['id'] == '玩家':  # 玩家
            while(True):
                print('当前手牌:', getCardName(playerList[i]['cards']))
                _isDeal = input('是否要牌?(y/n)')
                if _isDeal == 'y':
                    deal(playerList[i]['cards'], cards)
                    print('新牌:', getCardName(playerList[i]['cards'][-1]))
                    # 重新计算得分:
                    playerList[i]['score'] = getScore(playerList[i]['cards'])
                elif _isDeal == 'n':
                    break
                else:
                    print('请重新输入!')
        else:  # 电脑
            while(True):
                if isDeal(playerList[i]['score']) == 1:  # 为电脑玩家判断是否要牌
                    deal(playerList[i]['cards'], cards)
                    print('要牌。')
                    # 重新计算得分:
                    playerList[i]['score'] = getScore(playerList[i]['cards'])
                else:
                    print('不要了。')
                    break
        time.sleep(1.5)</span></span></span>

(5)随机洗牌:


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def getCards(decksNum):
    cardsList = ['Aa', 'Ab', 'Ac', 'Ad',
                 'Ka', 'Kb', 'Kc', 'Kd',
                 'Qa', 'Qb', 'Qc', 'Qd',
                 'Ja', 'Jb', 'Jc', 'Jd',
                 '0a', '0b', '0c', '0d',
                 '9a', '9b', '9c', '9d',
                 '8a', '8b', '8c', '8d',
                 '7a', '7b', '7c', '7d',
                 '6a', '6b', '6c', '6d',
                 '5a', '5b', '5c', '5d',
                 '4a', '4b', '4c', '4d',
                 '3a', '3b', '3c', '3d',
                 '2a', '2b', '2c', '2d']
    cardsList *= decksNum       # 牌副数
    random.shuffle(cardsList)   # 随机洗牌
    return cardsList</span></span></span>

(6)设置牌名字典:


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">cardNameDict = {'Aa': '黑桃A', 'Ab': '红桃A', 'Ac': '梅花A', 'Ad': '方片A',
                'Ka': '黑桃K', 'Kb': '红桃K', 'Kc': '梅花K', 'Kd': '方片K',
                'Qa': '黑桃Q', 'Qb': '红桃Q', 'Qc': '梅花Q', 'Qd': '方片Q',
                'Ja': '黑桃J', 'Jb': '红桃J', 'Jc': '梅花J', 'Jd': '方片J',
                '0a': '黑桃10', '0b': '红桃10', '0c': '梅花10', '0d': '方片10',
                '9a': '黑桃9', '9b': '红桃9', '9c': '梅花9', '9d': '方片9',
                '8a': '黑桃8', '8b': '红桃8', '8c': '梅花8', '8d': '方片8',
                '7a': '黑桃7', '7b': '红桃7', '7c': '梅花7', '7d': '方片7',
                '6a': '黑桃6', '6b': '红桃6', '6c': '梅花6', '6d': '方片6',
                '5a': '黑桃5', '5b': '红桃5', '5c': '梅花5', '5d': '方片5',
                '4a': '黑桃4', '4b': '红桃4', '4c': '梅花4', '4d': '方片4',
                '3a': '黑桃3', '3b': '红桃3', '3c': '梅花3', '3d': '方片3',
                '2a': '黑桃2', '2b': '红桃2', '2c': '梅花2', '2d': '方片2'}</span></span></span>

(7)判断胜负:


<span style="color:#333333"><span style="background-color:#ffffff"><span style="background-color:#f8f8f8">def showWinAndLose():
    loserList = []  # [['id', score], ['id', score], ...]
    winnerList = []  # [['id', score], ['id', score], ...]
    winnerCount = 0
    loserCount = 0
    for i in range(playerCount):
        if playerList[i]['score'] > 21:  # 爆牌直接进入败者列表
            loserList.append([playerList[i]['id'],  playerList[i]['score']])
        else:  # 临时胜者列表
            winnerList.append([playerList[i]['id'], playerList[i]['score']])
    if len(winnerList) == 0:  # 极端情况:全部爆牌
        print('全部玩家爆牌:')
        for i in range(len(loserList)):
            print(loserList[i][0], loserList[i][1])
    elif len(loserList) == 0:  # 特殊情况:无人爆牌
        winnerList.sort(key=lambda x: x[1], reverse=True)  # 根据分数值排序胜者列表
        for i in range(len(winnerList)):  # 计算最低分玩家数量
            if i != len(winnerList)-1:
                if winnerList[-i-1][1] == winnerList[-i-2][1]:
                    loserCount = (i+2)
                else:
                    if loserCount == 0:
                        loserCount = 1
                    break
            else:
                loserCount = len(loserList)
        if loserCount == 1:
            loserList.append(winnerList.pop())
        else:
            while(len(loserList) != loserCount):
                loserList.append(winnerList.pop())
        for i in range(len(winnerList)):  # 计算最高分玩家数量
            if i != len(winnerList)-1:
                if winnerList[i][1] == winnerList[i+1][1]:
                    winnerCount = (i+2)
                else:
                    if winnerCount == 0:
                        winnerCount = 1
                    break
            else:
                winnerCount = len(winnerList)
        while(len(winnerList) != winnerCount):
            winnerList.pop()
        print('获胜:')
        for i in range(len(winnerList)):
            print(winnerList[i][0], winnerList[i][1])
        print('失败:')
        for i in range(len(loserList)):
            print(loserList[i][0], loserList[i][1])
    else:  # 一般情况:有人爆牌
        winnerList.sort(key=lambda x: x[1], reverse=True)  # 根据分数值排序胜者列表
        for i in range(len(winnerList)):  # 计算最高分玩家数量
            if i != len(winnerList)-1:
                if winnerList[i][1] == winnerList[i+1][1]:
                    winnerCount = (i+2)
                else:
                    if winnerCount == 0:
                        winnerCount = 1
                    break
            else:
                winnerCount = len(winnerList)
        while(len(winnerList) != winnerCount):
            winnerList.pop()
        print('获胜:')
        for i in range(len(winnerList)):
            print(winnerList[i][0], winnerList[i][1])
        print('失败:')
        for i in range(len(loserList)):
            print(loserList[i][0], loserList[i][1])</span></span></span>

游戏效果:咳咳咳.......感觉这游戏看运气也看胆量!!



总结


哈哈哈!小编玩游戏比较废,你们要来试试嘛?无聊的时候可以摸摸鱼,打打酱油~


制作不易,记得一键三连哦!! 如果需要本文完整的代码+图片素材。


Python新手安装包、免费激活码、等等更多Python资料 【私信小编06】即可免费领取哦!!

相关推荐

Excel表格,100个常用函数_excel表格各种函数用法

1.SUM:求和函数2.AVERAGE:平均值函数3.MAX:最大值函数4.MIN:最小值函数5.COUNT:计数函数6.IF:条件函数7.VLOOKUP:垂直查找函数8.HLOOKU...

每天学一点Excel2010 (62)—Multinomial、Aggregate、Subtotal

138multinominal助记:英文的“多项式”类别:数学和三角语法:multinominal(number1,[number2],…)参数:1~255个参数number1必需。第1个数值参数...

182.人工智能——构建大模型应用_人工智能:模型与算法

一直认为人工智能的本质其实就是:算法+算力+大数据。算法的尽头是数学,算力是能源、而大数据则是人类共同智慧的而且是有限的宝贵资源,也是决定大模型的能力上限。人工智能不断的发展,也是人类文明进步的必然趋...

Excel伽马函数GAMMA_伽马函数表怎么看

Gamma函数是阶乘函数在实数与复数上扩展的一类函数,通常写作Γ(x)。伽玛函数在分析学、概率论、离散数学、偏微分方程中有重要的作用,属于应用最广泛的函数之一函数公式如下伽玛函数满足递推关系Γ(N+1...

2.黎曼ζ函数与黎曼猜想_黎曼函数的作用
2.黎曼ζ函数与黎曼猜想_黎曼函数的作用

2.黎曼ζ函数与黎曼猜想那么这个让上帝如此吝啬的黎曼猜想究竟是一个什么样的猜想呢?在回答这个问题之前我们先得介绍一个函数:黎曼ζ函数(RiemannZeta-function)。这个函数...

2025-09-09 00:24 itomcoil

嵌入式C语言基础编程—5年程序员给你讲函数,你真的懂函数吗?

本文主要是对C基础编程关于函数的初步讲解,后续会深入讲解C高级相关的概念(C大神可先略过)。本人近期会陆续上传IT编程相关的资料和视频教程,可以关注一下互相交流:CC++Javapython...

进一步理解函数_解读函数

函数的定义和基本调用应该是比较容易理解的,但有很多细节可能令初学者困惑,包括参数传递、返回、函数命名、调用过程等,我们逐个介绍。1.参数传递有两类特殊类型的参数:数组和可变长度的参数。(1)数组数组作...

可以降低阶乘运算复杂度的Stirling公式

转发一个关于Stirling公式的推导方法:Wallis公式是关于圆周率的无穷乘积的公式,但Wallis公式中只有乘除运算,连开方都不需要,形式上十分简单。虽然Wallis公式对π的近似计算没有直接影...

Agent杂谈:Agent的能力上下限及「Agent构建」核心技术栈调研分享~

2025年Agent技术持续演进,已从简单任务处理向具备独立规划、协作能力的智能系统转变。文章从系统设计视角出发,先梳理Agent的核心定义与架构框架,再深入分析决定其能力上下限的关键因素...

无炮塔的“S”坦克/Strv-103主战坦克

  20世纪50年代,瑞典陆军为了对付当时苏联T-54坦克,着手研制了一种无炮塔坦克——“S”坦克(瑞典编号为Strv103),并于1967年正式投产。这种坦克具有创新的设计思想,打破了传统的设计方...

shell——字符串操作_shell字符串处理命令

str="abc123abcABC"#计算字符串的长度echo${#str}#12exprlength$strexpr"$str":".*&#...

XSS的两种攻击方式及五种防御方式

跨站脚本攻击指的是自己的网站运行了外部输入代码攻击原理是原本需要接受数据但是一段脚本放置在了数据中:该攻击方式能做什么?获取页面数据获取Cookies劫持前端逻辑发送请求到攻击者自己的网站实现资料的盗...

C语言字符数组和字符串_c语言中的字符数组

用来存放字符的数组称为字符数组,例如:charc[10];字符数组也可以是二维或多维数组。例如:charc[5][10];字符数组也允许在定义时进行初始化,例如:charc[10]={'c',...

Python 和 JS 有什么相似?_python跟js

Python是一门运用很广泛的语言,自动化脚本、爬虫,甚至在深度学习领域也都有Python的身影。作为一名前端开发者,也了解ES6中的很多特性借鉴自Python(比如默认参数、解构赋值、...

【python】装饰器的原理_python装饰器详细教程

装饰器的原理是利用了Python的函数特性,即函数可以作为参数传递给另一个函数,也可以作为另一个函数的返回值。装饰器本质上是一个接受一个函数作为参数,并返回一个新函数的函数。这个新函数通常会在执行原函...