刚学了一点 python 基础知识,现跟着老师写一个简单的洗牌游戏:
# 实现 52 张牌的随机存取
import random
class PokerGame():
# 定义两个类成员,类似于 java 中的 static 修饰
color = ['黑桃','红桃','方块','梅花']
poker = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
# 定义构造函数
def __init__(self):
self.__initPoker = {} #用来放初始的52张牌
self.__randomPoker = [] #用来放随机后的52张牌
pass
def initPoker(self): #初始化
self.__initPoker = {'黑桃':PokerGame.poker[:], #黑桃十三张
'红桃':PokerGame.poker[:],
'方块':PokerGame.poker[:],
'梅花':PokerGame.poker[:]}
pass
def randomPoker(self): # 随机化
# 当随机出来的牌少于 52 张时,继续
while len(self.__randomPoker) <52 :
# 1、随机牌的颜色
colorIndex = random.randint(0,3)
# 通过索引得到随机牌色
colorValue = PokerGame.color[colorIndex]
pokerColorList = self.__initPoker[colorValue] #通过字典 键 访问方式,获取同一颜色的所有卡牌
# 2、随机牌的大小
if len(pokerColorList) <=0 : #如果当前颜色的牌数发完了,跳过继续随机
continue
pass
# 在当前颜色还有的前提下,继续随机牌面数的索引
pokerIndex = random.randint(0,len(pokerColorList)-1)
# 通过索引得到随机牌面数
pokerValue = pokerColorList[pokerIndex]
# 将随机后卡牌的颜色和数字组合在一起,存入洗牌结果列表
self.__randomPoker.append(colorValue + ":" + pokerValue)
#避免洗牌后有重复值,需将随机过的进行删除
pokerColorList.remove(pokerValue)
pass
pass
def getRandomPoker(self): #由于目标列表是私有的,要定义一个
return self.__randomPoker
if __name__ == "__main__":
poker = PokerGame()
poker.initPoker()
poker.randomPoker()
print(poker.getRandomPoker()) # 输出
pass