用python写一个斗地主游戏
时间: 2023-12-22 12:05:23 浏览: 116
好的,这是一个简单的斗地主游戏的Python代码示例:
```python
import random
# 定义牌型和对应的权值
card_value = {
'3': 1, '4': 2, '5': 3, '6': 4, '7': 5, '8': 6, '9': 7, '10': 8,
'J': 9, 'Q': 10, 'K': 11, 'A': 12, '2': 13, '小王': 14, '大王': 15
}
# 定义牌堆
cards = list(card_value.keys()) * 4 + ['小王', '大王']
# 洗牌
random.shuffle(cards)
# 发牌
player1 = sorted(cards[:17], key=lambda x: card_value[x])
player2 = sorted(cards[17:34], key=lambda x: card_value[x])
player3 = sorted(cards[34:51], key=lambda x: card_value[x])
bottom = sorted(cards[51:], key=lambda x: card_value[x])
# 定义出牌规则
def check_play(cards):
if len(cards) == 1:
return True
elif len(cards) == 2 and cards[0] == cards[1]:
return True
elif len(cards) == 3 and cards[0] == cards[1] and cards[1] == cards[2]:
return True
elif len(cards) == 4 and cards[0] == cards[1] and cards[1] == cards[2] and cards[2] == cards[3]:
return True
elif len(cards) == 5 and cards[0] == cards[1] and cards[1] == cards[2] and cards[2] == cards[3] and cards[3] == cards[4]:
return True
elif len(cards) == 6:
values = [card_value[cards[i]] for i in range(0, 6, 2)]
if values[0] == values[1] and values[1] == values[2] and values[3] == values[4] and values[4] == values[5]:
return True
elif len(cards) == 8:
values = [card_value[cards[i]] for i in range(0, 8, 2)]
if values[0] == values[1] and values[1] == values[2] and values[2] == values[3] and values[4] == values[5] and values[5] == values[6] and values[6] == values[7]:
return True
elif len(cards) == 10:
values = [card_value[cards[i]] for i in range(0, 10, 2)]
if values[0] == values[1] and values[1] == values[2] and values[2] == values[3] and values[4] == values[5] and values[5] == values[6] and values[6] == values[7] and values[8] == values[9]:
return True
elif len(cards) == 12:
values = [card_value[cards[i]] for i in range(0, 12, 2)]
if values[0] == values[1] and values[1] == values[2] and values[2] == values[3] and values[4] == values[5] and values[5] == values[6] and values[6] == values[7] and values[8] == values[9] and values[9] == values[10] and values[10] == values[11]:
return True
return False
# 开始游戏
players = [player1, player2, player3]
turn = 0
last_cards = []
while True:
print('玩家1:', player1)
print('玩家2:', player2)
print('玩家3:', player3)
print('底牌:', bottom)
print('上家出牌:', last_cards)
cards = players[turn]
print('轮到玩家{}出牌:'.format(turn+1))
play_cards = input().split()
if not check_play(play_cards):
print('出牌不符合规则,请重新出牌。')
continue
for card in play_cards:
if card not in cards:
print('出牌不符合手牌,请重新出牌。')
break
else:
for card in play_cards:
cards.remove(card)
last_cards = play_cards
if not cards:
print('玩家{}获胜!'.format(turn+1))
break
turn = (turn + 1) % 3
```
这个代码只是一个简单的示例,可以根据需要进行扩展和优化。同时,还需要注意牌型和出牌规则的定义,以保证游戏的公平和趣味性。
阅读全文