import random

import time

def main():

while(True):

iniGame()

createPlayerList()

gameStart()

gamePlay()

showResult()

showWinAndLose()

startNewGame = input('开始新游戏?(y)')

if startNewGame != 'y':

break

# 初始化玩家参数

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) # 洗牌

# 建立玩家列表

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) # 为各玩家随机排序

# 分2张明牌并计算得分

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)

# 按顺序询问玩家是否要牌

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)

# 展示最终得分、手牌情况

def showResult():

print('最终得分:')

for i in range(playerCount):

print(playerList[i]['id'], playerList[i]['score'],

getCardName(playerList[i]['cards']))

# 胜负情况判定

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])

# 获取洗好的牌

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

# 要牌概率

probDict = {12: 0.92, 13: 0.87, 14: 0.74, 15: 0.5,

16: 0.205, 17: 0.1294, 18: 0.07580895, 19: 0.033117337}

# 牌名字典

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'}

# 判断是否要牌

def isDeal(currentScore):

if currentScore > 11:

if currentScore > 19:

return 0 # 点数大于19点或已爆牌必定不要牌

prob = probDict[currentScore] # 获取要牌概率

if prob > random.uniform(0, 1): # 使用投骰子的方式根据概率判断

return 1

else:

return 0

else:

return 1 # 点数不大于11必定要牌

# 当前得分

def getScore(cardsList):

scoreNum = 0

for i in range(len(cardsList)):

if cardsList[i][0] == 'A':

scoreNum += 1

elif (cardsList[i][0] == '0' or cardsList[i][0] == 'K' or

cardsList[i][0] == 'Q' or cardsList[i][0] == 'J'):

scoreNum += 10

else:

scoreNum += int(cardsList[i][0])

return scoreNum

# 分牌函数

def deal(playerCardsList, cardsList, num=1):

for i in range(num):

playerCardsList.append(cardsList.pop(0))

# 打印卡牌名字

def getCardName(playerCardsList):

nameStr = ''

if isinstance(playerCardsList, str) != 1:

for i in range(len(playerCardsList)):

nameStr += cardNameDict[playerCardsList[i]]

if i != len(playerCardsList):

nameStr += ' '

else:

nameStr = cardNameDict[playerCardsList]

return nameStr

main()

python小游戏源码-python21点小游戏源码免费下载相关推荐

  1. 自从学会Python后,无视百度文库VIP,所有文档免费下载阅读

    最近要用到百度文库查资料,但是很多都需要付费VIP或者下载券,还不能复制,就有点苦逼! 还好小编会Python,在Python面前真的所有VIP都是小意思,啥视频网站,资料网站等等,统统无视收费机制! ...

  2. python基础教程第三版电子版百度云-《python基础教程第三版》高清版PDF免费下载...

    下载地址1:http://t.cn/EGxO1sW Python基础教程 第3版Python简明教程书籍 Python编程从入门到实践 灵程序设计丛书 <python基础教程第三版>高清版 ...

  3. python基础教程第三版电子版-《python基础教程第三版》PDF高清完整版-免费下载...

    <python基础教程第3版>高清PDF下载地址:http://t.cn/EGxO1sW Python基础教程 第3版Python简明教程书籍 Python编程从入门到实践 灵程序设计丛书 ...

  4. 【通知】▁▂▃ Himi 最新著作《iOS游戏编程之从零开始—Cocos2d-x与cocos2d引擎游戏开发》★书籍源码+第4/5/6样章★-免费下载★ ▃▂▁

    2013年新年,Himi的第二本著作:<iOS游戏编程之从零开始-Cocos2d-x与cocos2d引擎游戏开发>一书正式发售: (大家可以到新华书店.淘宝.拍拍.当当.亚马逊等进行购买) ...

  5. [转] Himi 著作《Android游戏编程之从零开始》★书籍源码+第4/6/7样章—免费下载★...

    本文转自:http://blog.csdn.net/xiaominghimi/article/details/6802444 Himi 原创, 转载请注明出处,谢谢! 原文地址:http://blog ...

  6. python经典100例答案pdf-Python 入门 100 案例,PDF免费下载

    原标题:Python 入门 100 案例,PDF免费下载 大家好,我是振哥.在过去一年多时间,我先后打磨了几个Python类开源教程.所有教程力求通俗易懂,有趣,并结合一个一个的小例子.小案例讲解,让 ...

  7. 酷炫小程序相册源码,制作属于自己的相册,免费下载

    下载地址:http://sucaiip.com/article-291.html 现有功能: 1.相册海报生成功能. 2.目前拥有34套相册模板. 3.模板消息群发功能. 4.广告功能,可调整小程序. ...

  8. 蘑菇导航源码安装教程,wordpress导航主题免费下载[Wordpress主题]

    主题介绍: 蘑菇导航的列表页有两种风格,分别对应宽屏.窄屏.可以点击 文章.博客 查看演示.文章页也是如此,这两种风格可以在后台设置. 本站菜单中的 VIP解析.音乐.图床,是单独的源码,不包含在本次 ...

  9. Spring源码深度解析 (第2版) PDF 免费下载

    获取方式 链接:https://pan.baidu.com/s/1b_fdck0jEkAafHajIeQ-4Q 密码: 如连接被和谐,请在评论区或公众号告知我. 除此以外,关注公众号回复 电子书 还可 ...

最新文章

  1. SRM596 DIV2 1000
  2. 有了人工智能还不够?腾讯的工具产品想试试社交
  3. Jmeter当获取正则表达式匹配数字为负数时获取所有匹配的值
  4. OpenCV与图像处理学习十三——Harris角点检测(含代码)
  5. 2021年的Angular最佳实践
  6. Python+django网页设计入门(8):网站项目文件夹布局
  7. Android--Activity中使用Intent传值
  8. JSON与JAVA的数据转换
  9. 我的家乡河北涿州岐沟村(岐沟关)
  10. Monkey 命令 基本参数介绍
  11. SCP不会覆盖已有文件
  12. 模糊综合评价在实际问题中的应用(案例)
  13. 【NLP】第 1 章 语言处理和 Python
  14. 所有程序员会面临的问题:程序员只能吃青春饭?
  15. kafka HW机制的作用
  16. Java开发个人总结
  17. Java实现各种节日维护 农历,阳历,二十四节气 自定义节日,根据当前日期获取节日
  18. C++之sstream
  19. 我的投资经历(写给关注我的友军)
  20. 第八次前端培训(JavaScript)

热门文章

  1. Nginx配置与使用
  2. django 模板语言之 simple_tag 自定义模板
  3. 旋转动画 rotate
  4. [转]那些年我们一起清除过的浮动
  5. Nginx源码研究三:Epoll在NGINX中的使用
  6. -- HTML标记大全参考手册[推荐]
  7. Linux修改文件及文件夹权限
  8. 实验二 建立基本的游戏场景
  9. WPF and Silverlight 学习笔记(十八):WPF样式(Style)与模板(Template)
  10. c++ 在哪里找文档来看_FPX双C十四连败引热议!Doinb:我再也不跟LWX双排了