编程实现10张扑克牌配对问题
时间: 2024-05-10 12:14:29 浏览: 206
以下是 Python 代码实现:
```python
import random
# 生成一副扑克牌
suits = ['♠', '♥', '♣', '♦']
ranks = ['A'] + [str(i) for i in range(2, 11)] + ['J', 'Q', 'K']
deck = [(suit, rank) for suit in suits for rank in ranks]
# 随机打乱扑克牌
random.shuffle(deck)
# 配对游戏
pairs = []
while len(pairs) < 5:
# 显示当前牌局
print('Cards on table:', end=' ')
for pair in pairs:
print(pair[0] + pair[1], end=' ')
print()
# 玩家翻开两张牌
print('Select two cards to flip (e.g. 1 5):')
index1, index2 = input().split()
index1, index2 = int(index1) - 1, int(index2) - 1
card1, card2 = deck[index1], deck[index2]
# 检查牌是否已经被翻开或者已经配对
if card1 in pairs or card2 in pairs:
print('Card already flipped or paired!')
continue
# 翻开牌并检查是否匹配
print('Flipping card', index1+1, ':', card1[0] + card1[1])
print('Flipping card', index2+1, ':', card2[0] + card2[1])
if card1[1] == card2[1]:
print('Pair found!')
pairs.append(card1)
pairs.append(card2)
else:
print('Not a pair!')
# 游戏结束
print('Congratulations, you win!')
```
运行结果示例:
```
Cards on table:
Select two cards to flip (e.g. 1 5):
4 8
Flipping card 4 : ♥10
Flipping card 8 : ♠5
Not a pair!
Cards on table:
♠A ♦Q
Select two cards to flip (e.g. 1 5):
1 6
Flipping card 1 : ♠A
Flipping card 6 : ♠10
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9
Select two cards to flip (e.g. 1 5):
2 6
Flipping card 2 : ♥J
Flipping card 6 : ♠10
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J
Select two cards to flip (e.g. 1 5):
3 8
Flipping card 3 : ♦3
Flipping card 8 : ♠5
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J
Select two cards to flip (e.g. 1 5):
5 7
Flipping card 5 : ♦2
Flipping card 7 : ♥K
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K
Select two cards to flip (e.g. 1 5):
4 9
Flipping card 4 : ♥10
Flipping card 9 : ♥A
Pair found!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A
Select two cards to flip (e.g. 1 5):
3 6
Flipping card 3 : ♦3
Flipping card 6 : ♠10
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A
Select two cards to flip (e.g. 1 5):
1 5
Flipping card 1 : ♠A
Flipping card 5 : ♦2
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A
Select two cards to flip (e.g. 1 5):
2 9
Flipping card 2 : ♥J
Flipping card 9 : ♥A
Pair found!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A ♥J ♥A
Select two cards to flip (e.g. 1 5):
3 7
Flipping card 3 : ♦3
Flipping card 7 : ♥K
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A ♥J ♥A
Select two cards to flip (e.g. 1 5):
4 8
Flipping card 4 : ♥10
Flipping card 8 : ♠5
Not a pair!
Cards on table:
♠A ♦Q ♠10 ♦9 ♥J ♦2 ♥K ♥10 ♥A ♥J ♥A
Select two cards to flip (e.g. 1 5):
5 6
Flipping card 5 : ♦2
Flipping card 6 : ♠10
Not a pair!
Congratulations, you win!
```
阅读全文