用python写斗地主程序
时间: 2023-12-16 13:03:46 浏览: 25
写斗地主程序需要用到Python的基础知识和一些算法思想,比如洗牌算法、决策树等。下面是一个简单的斗地主程序示例:
```python
import random
# 定义扑克牌
poker = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
# 定义花色
suits = ['♠', '♥', '♣', '♦']
# 定义牌型
patterns = ['单牌', '对子', '三带一', '三带二', '顺子', '连对', '飞机带翅膀']
# 初始化牌堆
cards = []
for suit in suits:
for point in poker:
cards.append(suit + point)
cards.append('小王')
cards.append('大王')
# 洗牌
random.shuffle(cards)
# 发牌
landlord_cards = cards[:20]
player1_cards = landlord_cards[:17]
player2_cards = landlord_cards[17:34]
player3_cards = landlord_cards[34:]
# 打印每个玩家的牌
print('地主牌:', landlord_cards)
print('玩家1的牌:', player1_cards)
print('玩家2的牌:', player2_cards)
print('玩家3的牌:', player3_cards)
# 判断牌型
def get_pattern(cards):
length = len(cards)
if length == 1:
return patterns[0]
elif length == 2 and cards[0][1:] == cards[1][1:]:
return patterns[1]
elif length == 3 and cards[0][1:] == cards[1][1:] == cards[2][1:]:
return patterns[2]
elif length == 4 and cards[0][1:] == cards[1][1:] == cards[2][1:] == cards[3][1:]:
return patterns[3]
elif length >= 5 and is_straight(cards):
return patterns[4]
elif length >= 6 and is_double_straight(cards):
return patterns[5]
elif length >= 8 and is_triple_straight(cards):
return patterns[6]
else:
return '无法出牌'
# 判断是否为顺子
def is_straight(cards):
for i in range(len(cards) - 1):
if poker.index(cards[i][1:]) + 1 != poker.index(cards[i+1][1:]):
return False
return True
# 判断是否为连对
def is_double_straight(cards):
if len(cards) % 2 != 0:
return False
for i in range(0, len(cards), 2):
if cards[i][1:] != cards[i+1][1:]:
return False
if i+3 < len(cards) and poker.index(cards[i][1:]) + 1 != poker.index(cards[i+3][1:]):
return False
return True
# 判断是否为飞机带翅膀
def is_triple_straight(cards):
if len(cards) % 4 != 0:
return False
triples = []
for i in range(0, len(cards), 3):
if cards[i][1:] == cards[i+1][1:] == cards[i+2][1:]:
triples.append(cards[i:i+3])
if len(triples) < 2:
return False
for i in range(len(triples) - 1):
if poker.index(triples[i][0][1:]) + 1 != poker.index(triples[i+1][0][1:]):
return False
return True
# 测试牌型
print(get_pattern(['♥6', '♠6', '♣6'])) # 三带零
print(get_pattern(['♥6', '♠6', '♣6', '♦6'])) # 炸弹
print(get_pattern(['♥6', '♠7', '♣8', '♦9', '♥10'])) # 顺子
print(get_pattern(['♥6', '♠6', '♣7', '♦7', '♥8', '♠8', '♣9', '♦9'])) # 连对
print(get_pattern(['♥6', '♠6', '♣6', '♦7', '♥7', '♠7', '♣8', '♦8', '♥8', '♠9', '♣9', '♦10'])) # 飞机带翅膀
print(get_pattern(['♥6', '♠6', '♣6', '♦7', '♥7', '♠7', '♣8', '♦8', '♥8', '♠9', '♣9', '♦9'])) # 飞机带翅膀
print(get_pattern(['♥6', '♠6', '♣6', '♦7', '♥7', '♠7', '♣8', '♦8', '♥8', '♠9', '♣9', '♦9', '♥10'])) # 无法出牌
```
以上代码只是一个简单的示例,实际上,编写一个完整的斗地主程序需要考虑更多的细节问题,如出牌规则、牌型比较等。