無聊用 bolt.new 搞個詐金花的代碼來玩玩,AI 寫的代碼。經常讀 AI 的代碼,進步神速
寫一個程序,實現發牌、比大小判斷輸贏。
遊戲規則:#
一副撲克牌,去掉大小王,每個玩家發 3 張牌,最後比大小,看誰贏。
有以下幾種牌:
豹子:三張一樣的牌,如 3 張 6.
順金:又稱同花順,即 3 張同樣花色的順子,如紅桃 5、6、7
順子:又稱拖拉機,花色不同,但是順子,如紅桃 5、方片 6、黑桃 7,組成的順子
對子:2 張牌一樣
單張:單張最大的為 A
這幾種牌的大小順序為,豹子 > 順金 > 順子 > 對子 > 單張
需程序實現的點:#
-
首先生成一副完整的撲克牌
-
給 5 個玩家隨機發牌
-
統一開牌,比大小,輸出贏家是誰
import random
# 定義牌的花色和點數
suits = ['♥', '♦', '♣', '♠']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
# 生成一副完整的撲克牌
deck = [(suit, rank) for suit in suits for rank in ranks]
# 洗牌
random.shuffle(deck)
# 發牌給5個玩家,每人3張牌
players = []
for i in range(5):
hand = deck[:3]
players.append(hand)
deck = deck[3:]
# 定義牌型的大小順序
def rank_value(rank):
if rank == 'A':
return 14
elif rank == 'K':
return 13
elif rank == 'Q':
return 12
elif rank == 'J':
return 11
else:
return int(rank)
def is_straight(hand):
values = sorted([rank_value(rank) for suit, rank in hand])
return values[0] + 1 == values[1] and values[1] + 1 == values[2]
def is_flush(hand):
suits = [suit for suit, rank in hand]
return len(set(suits)) == 1
def is_three_of_a_kind(hand):
values = [rank_value(rank) for suit, rank in hand]
return values[0] == values[1] == values[2]
def is_pair(hand):
values = [rank_value(rank) for suit, rank in hand]
return values[0] == values[1] or values[1] == values[2] or values[0] == values[2]
def hand_rank(hand):
if is_three_of_a_kind(hand):
return (5, max([rank_value(rank) for suit, rank in hand]))
elif is_straight(hand) and is_flush(hand):
return (4, max([rank_value(rank) for suit, rank in hand]))
elif is_straight(hand):
return (3, max([rank_value(rank) for suit, rank in hand]))
elif is_pair(hand):
return (2, max([rank_value(rank) for suit, rank in hand]))
else:
return (1, max([rank_value(rank) for suit, rank in hand]))
# 比較牌型大小
def compare_hands(hand1, hand2):
rank1 = hand_rank(hand1)
rank2 = hand_rank(hand2)
if rank1 > rank2:
return 1
elif rank1 < rank2:
return -1
else:
return 0
# 輸出每個玩家的牌和牌型
for i, hand in enumerate(players):
print(f"Player {i + 1}: {hand}, Hand Rank: {hand_rank(hand)}")
# 比較所有玩家的牌,找出贏家
winner = players[0]
for hand in players[1:]:
if compare_hands(hand, winner) > 0:
winner = hand
# 輸出贏家
winner_index = players.index(winner)
print(f"Winner is Player {winner_index + 1} with hand {winner}")