Python解決斗地主發牌問題及串列基礎知識運用
? 用一張串列保存54張撲克牌,洗牌,按斗地主的發牌方式把牌
發給三個玩家,多的三張牌給第一個玩家,把每個玩家手上的牌顯示出來,
? 我們運用前面所學的串列與回圈分支結構知識求解,
方法一
shuffle()是庫random中的函式其作用為亂序,打亂順序,
#首先我們要獲得一副撲克牌
import random
cards = []#一次一次錄入會比較麻煩
suites = ['?','?','?','?']# 沒圖形的可以輸入字符表示如:方塊
faces = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
for suite in suites:#做兩次for回圈每個花色與牌色對應
for face in faces:
#print(f'{suite}{face}',end=' ')
cards.append(f'{suite}{face}')#把牌放入card
#把大小王加入其中
cards.append('大王')
cards.append('小王')
print(cards) #獲得一副新牌
random.shuffle(cards)#洗牌(隨機亂序)
#做三個玩家空串列 把每次發到的牌放到對應的玩家空串列中
players_one = []
players_two = []
players_three = []
#開始發牌,每人17張
for _ in range(1,18):
players_one.append(cards.pop())
players_two.append(cards.pop())
players_three.append(cards.pop())
'''函式pop()默認洗掉的是串列cards的最后一個元素,pop洗掉的程序中還會回傳其洗掉的元素,再利用append追加到每個玩家空串列中,如要從前面發牌則用pop(0)'''
players_one.extend(cards)#extend()擴展合并,把最后三張牌拼接到第一個玩家(地主)
print(f'地主牌為{players_one}')
print(f'農民1{players_two})')
print(f'農民2{players_three}')

方法二
運用串列切片索引知識解決問題
import random
cards = []#一次一次錄入會比較麻煩
suites = ['?','?','?','?']# 沒圖形的可以輸入字符表示如:方塊
faces = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
for suite in suites:#做兩次for回圈每個花色與牌色對應
for face in faces:
#print(f'{suite}{face}',end=' ')
cards.append(f'{suite}{face}')#把牌放入card
#把大小王加入其中
cards.append('大王')
cards.append('小王')
print(cards) #獲得一副新牌
random.shuffle(cards)#洗牌(隨機亂序)
# 與上一種方法不一樣的是發牌的方式
# 開始發牌,每人17張
player_one = cards[1:52:3] #步長為3表示每人一張
players_two = cards[2:52:3]
player_three = cards[3:52:3]
last = cards[51:] #最后三張放為一個集合
player_one = player_one + last #把最后三張給地主
#也可以用函式extend()擴展合并
print(player_one)
print(players_two)
print(player_three)
方法三
與前兩種方法不一樣的是,這里我們將會用到嵌套串列
可以改變玩家的數量與玩牌的方式,比如 三個人玩炸金花
嵌套串列如:nums = [ [], [], [], [] ]
相當于大盒子里面再放一些小盒子
import random
cards = []#一次一次錄入會比較麻煩
suites = ['?','?','?','?']# 沒圖形的可以輸入字符表示如:方塊
faces = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
for suite in suites:#做兩次for回圈每個花色與牌色對應
for face in faces:
#print(f'{suite}{face}',end=' ')
cards.append(f'{suite}{face}')#把牌放入card
#把大小王加入其中
cards.append('大王')
cards.append('小王')
print(cards) #獲得一副新牌
random.shuffle(cards)#洗牌(隨機亂序)
players = [[] for _ in range(3)] #可改變范圍規定參與人數
for _ in range(3):#改變范圍規定發牌數
for player in players:# 遍歷回圈玩家,回圈發牌
player.append(porke_nums.pop())
for player in players: # 遍歷回圈玩家,整理發到手上的撲克
player.sort(key=lambda x: x[1:])
for card in player:# 回圈輸出玩家手里的撲克
print(card, end=' ')
print()

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/290884.html
標籤:python
上一篇:Python游戲開發,pygame模塊,Python實作經典吃豆豆小游戲
下一篇:python:洗掉串列中重復元素
