主要利用了random模块:
import random #生成牌 def get_cards(): num=[‘A‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘,‘10‘,‘J‘,‘Q‘,‘K‘] suits=[‘\u2660‘,‘\u2663‘,‘\u2665‘,‘\u2666‘] cards=[] for i in range(0,len(suits)): for j in range(0,len(num)): card=suits[i]+num[j] cards.append(card) cards.append(‘大王‘) cards.append(‘小王‘) return cards def deal_cards(): #选取底牌 cards=get_cards() bottoms=random.sample(cards,3) for i in range(0,len(bottoms)): cards.remove(bottoms[i]) #发牌 p1=[] p2=[] p3=[] for i in range(0,13): one=random.sample(cards,1) p1.append(one) cards.remove(one[0]) del one two=random.sample(cards,1) p2.append(two) cards.remove(two[0]) del two three=random.sample(cards,1) p3.append(three) cards.remove(three[0]) del three #抢地主,拿底牌 landlord=random.randint(1,3) if landlord==1: p1.append(bottoms) p1.insert(0,‘地主‘) p2.insert(0,‘农民‘) p3.insert(0, ‘农民‘) elif landlord==2: p2.append(bottoms) p2.insert(0,‘地主‘) p1.insert(0, ‘农民‘) p3.insert(0, ‘农民‘) else: p3.append(bottoms) p3.insert(0,‘地主‘) p1.insert(0, ‘农民‘) p2.insert(0, ‘农民‘) print(‘p1是:‘,p1[0],‘,手牌是:‘,p1[1:]) print(‘p2是:‘,p2[0],‘,手牌是:‘,p2[1:]) print(‘p3是:‘,p3[0],‘,手牌是:‘,p3[1:]) deal_cards()
运行如下:
p1是: 地主 ,手牌是: [[‘♣8‘], [‘♥2‘], [‘♦5‘], [‘♣3‘], [‘♣2‘], [‘♦4‘], [‘♣7‘], [‘♦Q‘], [‘♥Q‘], [‘♠4‘], [‘♣10‘], [‘♥9‘], [‘♠8‘], [‘♦K‘, ‘♣Q‘, ‘♣5‘]] p2是: 农民 ,手牌是: [[‘♥7‘], [‘♠J‘], [‘♥10‘], [‘♣9‘], [‘♠7‘], [‘♦7‘], [‘♣J‘], [‘♥K‘], [‘♠3‘], [‘♦8‘], [‘♥A‘], [‘♣4‘], [‘♠2‘]] p3是: 农民 ,手牌是: [[‘♥4‘], [‘♠A‘], [‘小王‘], [‘♣K‘], [‘♦9‘], [‘♥3‘], [‘♠Q‘], [‘♦2‘], [‘♥6‘], [‘♠9‘], [‘♥J‘], [‘♦J‘], [‘♦A‘]]
代码任需优化!!
原文:https://www.cnblogs.com/raccoonx95/p/11338660.html