This commit is contained in:
Ubuntu
2026-07-03 16:58:28 +08:00
commit 32b43f85bd
6240 changed files with 1987678 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
# 斗地主服务端游戏模块
from .game import DoudizhuGame
from .game_logic import Card, Deck, identify_card_type, can_beat, CARD_TYPES
__all__ = [
'DoudizhuGame',
'Card',
'Deck',
'identify_card_type',
'can_beat',
'CARD_TYPES',
]
+766
View File
@@ -0,0 +1,766 @@
"""
斗地主 AI 适配器实现
支持规则AI和DeepSeek大模型AI
"""
import os
import json
import asyncio
import aiohttp
from typing import Dict, List, Any, Optional
from collections import Counter
import sys
import os as os_module
sys.path.insert(0, os_module.path.dirname(os_module.path.dirname(os_module.path.abspath(__file__))))
from engine.ai_adapter import AIAdapter, RuleBasedAdapter, LLMAdapter
from doudizhu.game_logic import (
Card, identify_card_type, can_beat, evaluate_hand_strength,
find_cards_by_ids, Deck, CardType
)
# 加载斗地主模型配置文件(支持 DeepSeek 等外部模型)
def _load_doudizhu_config():
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'model_config.json')
if os.path.exists(config_path):
with open(config_path, 'r', encoding='utf-8') as f:
return json.load(f)
return {}
DOUDIZHU_CONFIG = _load_doudizhu_config()
class DoudizhuRuleAI(RuleBasedAdapter):
"""
斗地主基于规则的AI
从现有JS代码迁移
"""
def __init__(self, config: Optional[Dict] = None):
super().__init__(config or {})
self.ai_type = 'doudizhu_rule'
def get_name(self) -> str:
return "斗地主规则AI"
def want_to_be_lord(self, cards: List[Card]) -> bool:
"""决定是否叫地主"""
score = evaluate_hand_strength(cards)
return score >= 8 # 分数>=8才当地主
def find_all_valid_plays(self, cards: List[Card], desktop_type: Optional[Dict]) -> List[Dict]:
"""找出所有可出的牌型"""
valid_plays = []
n = len(cards)
# 辅助函数:生成所有组合
def get_combinations(arr, k):
if k == 0:
return [[]]
if len(arr) < k:
return []
result = []
for i in range(len(arr) - k + 1):
sub_combos = get_combinations(arr[i + 1:], k - 1)
for sub in sub_combos:
result.append([arr[i]] + sub)
return result
# 尝试不同数量的牌(限制在合理范围内)
for k in range(1, min(n + 1, 9)): # 最多8张
combos = get_combinations(cards, k)
for combo in combos:
card_type = identify_card_type(combo)
if card_type and can_beat(desktop_type, card_type):
valid_plays.append({
'cards': combo,
'type': card_type,
'card_ids': [c.id for c in combo]
})
# 炸弹单独处理(可以管任何非炸弹)
value_count = {}
for c in cards:
value_count[c.value] = value_count.get(c.value, 0) + 1
for value, count in value_count.items():
if count == 4:
bomb_cards = [c for c in cards if c.value == value]
bomb_type = identify_card_type(bomb_cards)
if bomb_type and can_beat(desktop_type, bomb_type):
# 去重
bomb_ids = set(c.id for c in bomb_cards)
is_duplicate = any(
set(c.id for c in play['cards']) == bomb_ids
for play in valid_plays
)
if not is_duplicate:
valid_plays.append({
'cards': bomb_cards,
'type': bomb_type,
'card_ids': [c.id for c in bomb_cards]
})
# 王炸
jokers = [c for c in cards if c.is_joker]
if len(jokers) == 2:
joker_type = identify_card_type(jokers)
if joker_type and can_beat(desktop_type, joker_type):
valid_plays.append({
'cards': jokers,
'type': joker_type,
'card_ids': [c.id for c in jokers]
})
return valid_plays
# ───────────────────────── 辅助函数 ─────────────────────────
def _estimate_min_rounds(self, cards: List[Card]) -> int:
"""估算最少需要几轮出完(简化版)"""
if not cards:
return 0
n = len(cards)
value_count = Counter(c.value for c in cards)
rounds = 0
# 王炸
if sum(1 for c in cards if c.is_joker) == 2:
rounds += 1
n -= 2
# 炸弹
for v, c in list(value_count.items()):
if c == 4:
rounds += 1
n -= 4
value_count[v] = 0
# 飞机(连续三张)
triples = sorted([v for v, c in value_count.items() if c >= 3 and v <= 14])
if len(triples) >= 2:
streak = 1
for i in range(1, len(triples)):
if triples[i] == triples[i - 1] + 1:
streak += 1
else:
break
if streak >= 2:
rounds += 1
n -= streak * 3
for v in triples[:streak]:
value_count[v] -= 3
# 连对
pairs = sorted([v for v, c in value_count.items() if c >= 2 and v <= 14])
if len(pairs) >= 3:
streak = 1
for i in range(1, len(pairs)):
if pairs[i] == pairs[i - 1] + 1:
streak += 1
else:
break
if streak >= 3:
rounds += 1
n -= streak * 2
for v in pairs[:streak]:
value_count[v] -= 2
# 顺子
unique = sorted([v for v, c in value_count.items() if c > 0 and v <= 14])
if len(unique) >= 5:
streak = 1
max_streak = 1
for i in range(1, len(unique)):
if unique[i] == unique[i - 1] + 1:
streak += 1
max_streak = max(max_streak, streak)
else:
streak = 1
if max_streak >= 5:
rounds += 1
n -= max_streak
# 剩余牌按最紧凑估算
if n > 0:
rounds += max(1, (n + 1) // 2)
return rounds
def _calculate_break_cost(self, cards: List[Card], play_cards: List[Card]) -> float:
"""计算拆牌代价:出了这些牌后,是否拆了原本的组合"""
play_values = {c.value for c in play_cards}
all_values = [c.value for c in cards]
cost = 0.0
# 检查是否拆了顺子
sorted_unique = sorted(set(v for v in all_values if v <= 14))
if len(sorted_unique) >= 5:
# 找最长连续序列
streaks = []
current = [sorted_unique[0]]
for v in sorted_unique[1:]:
if v == current[-1] + 1:
current.append(v)
else:
if len(current) >= 5:
streaks.append(list(current))
current = [v]
if len(current) >= 5:
streaks.append(current)
for streak in streaks:
removed = play_values & set(streak)
if removed and len(removed) < len(streak):
cost += len(removed) * 2.0
# 检查是否拆了连对
value_count = Counter(all_values)
pair_values = sorted([v for v, c in value_count.items() if c >= 2 and v <= 14])
if len(pair_values) >= 3:
current = [pair_values[0]]
for v in pair_values[1:]:
if v == current[-1] + 1:
current.append(v)
else:
if len(current) >= 3:
removed = play_values & set(current)
if removed and len(removed) < len(current):
cost += len(removed) * 3.0
current = [v]
if len(current) >= 3:
removed = play_values & set(current)
if removed and len(removed) < len(current):
cost += len(removed) * 3.0
# 检查是否拆了飞机(连续三张)
triple_values = sorted([v for v, c in value_count.items() if c >= 3 and v <= 14])
if len(triple_values) >= 2:
current = [triple_values[0]]
for v in triple_values[1:]:
if v == current[-1] + 1:
current.append(v)
else:
if len(current) >= 2:
removed = play_values & set(current)
if removed and len(removed) < len(current):
cost += len(removed) * 4.0
current = [v]
if len(current) >= 2:
removed = play_values & set(current)
if removed and len(removed) < len(current):
cost += len(removed) * 4.0
return cost
def _evaluate_remaining_shape(self, cards: List[Card]) -> float:
"""评估剩余手牌的牌型质量(越高越好)"""
if not cards:
return 100.0
quality = 0.0
value_count = Counter(c.value for c in cards)
# 炸弹/王炸
for c in value_count.values():
if c == 4:
quality += 10.0
jokers = [c for c in cards if c.is_joker]
if len(jokers) == 2:
quality += 20.0
# 2 和王
for c in cards:
if c.value == 15:
quality += 3.0
elif c.value >= 16:
quality += 5.0
# 顺子潜力
unique = sorted(set(v for v in value_count.keys() if v <= 14))
streaks = 0
cur = 0
for i, v in enumerate(unique):
if i == 0 or v == unique[i - 1] + 1:
cur += 1
else:
if cur >= 3:
streaks += cur
cur = 1
if cur >= 3:
streaks += cur
quality += streaks * 0.8
# 对子/三张
pairs = sum(1 for c in value_count.values() if c >= 2)
triples = sum(1 for c in value_count.values() if c >= 3)
quality += pairs * 1.5 + triples * 3.0
return quality
def _evaluate_play(self, play: Dict, cards: List[Card],
is_lord: bool, teammate_cards: int,
desktop_type: Optional[Dict]) -> float:
"""评估一个出牌方案的得分,越高越好"""
play_card_ids = {c.id for c in play['cards']}
remaining = [c for c in cards if c.id not in play_card_ids]
remaining_count = len(remaining)
play_count = len(play['cards'])
play_type = play['type']['type']
play_value = play['type']['value']
score = 0.0
# 1. 能出完 → 最高优先级
if remaining_count == 0:
return 20000.0
# 2. 出得多比出得少好(减少轮数)
score += play_count * 5.0
# 3. 剩余轮数估算:轮数越少越好
my_rounds = self._estimate_min_rounds(remaining)
score -= my_rounds * 30.0
# 4. 牌值越小越好(保留大牌)
score -= play_value * 0.8
# 5. 拆牌代价
break_cost = self._calculate_break_cost(cards, play['cards'])
score -= break_cost * 8.0
# 6. 剩余牌质量
remaining_quality = self._evaluate_remaining_shape(remaining)
score += remaining_quality * 1.5
# 7. 炸弹特殊处理
if play_type in ('bomb', 'joker_bomb'):
if remaining_count <= 2:
score += 800 # 快出完了,果断炸
elif teammate_cards <= 2 and not is_lord:
score += 800 # 队友快走完了,炸地主
elif not is_lord and not desktop_type:
score -= 300 # 农民且没人出牌,不要主动炸
else:
score -= 100 # 一般情况,不优先炸
# 8. 角色策略
if is_lord:
# 地主:优先出对方难接的长牌型
if play_type == 'straight' and play_count >= 5:
score += play_count * 3.0
elif play_type == 'double_straight':
score += play_count * 2.5
elif play_type == 'triple_straight':
score += play_count * 3.5
elif play_type in ('triple_with_single', 'triple_with_pair'):
score += 5.0
else:
# 农民:队友牌少时让牌,桌面有牌时要帮管
if teammate_cards <= 3:
if not desktop_type:
score -= 300 # 不要主动抢节奏
elif desktop_type:
score += 150 # 队友快走完了,积极管牌
# 9. 管牌时:尽量用刚好能管的最小组合,优先同类型
if desktop_type:
desktop_type_str = desktop_type['type']
if play_type == desktop_type_str:
score += 25 # 同类型优先,不浪费牌型
elif play_type in ('bomb', 'joker_bomb'):
# 用炸弹管,前面已处理
pass
else:
score -= 10 # 跨类型管牌(如用对子管单张),轻微惩罚
return score
def choose_best_play(self, valid_plays: List[Dict], cards: List[Card],
is_lord: bool, teammate_cards: int,
desktop_type: Optional[Dict] = None) -> Optional[Dict]:
"""选择最佳出牌(多维度评分)"""
if not valid_plays:
return None
# 炸弹/王炸单独收集,最后决策
bombs = [p for p in valid_plays if p['type']['type'] in ('bomb', 'joker_bomb')]
non_bombs = [p for p in valid_plays if p['type']['type'] not in ('bomb', 'joker_bomb')]
best = None
best_score = -float('inf')
# 先评估非炸弹
for play in non_bombs:
score = self._evaluate_play(play, cards, is_lord, teammate_cards, desktop_type)
if score > best_score:
best_score = score
best = play
# 炸弹决策:只在必要时才考虑
if bombs:
# 判断是否该出炸弹
should_bomb = False
remaining_count = len(cards)
if remaining_count <= 2:
should_bomb = True
elif teammate_cards <= 2 and not is_lord:
should_bomb = True
elif desktop_type:
# 桌面牌很大,没有非炸弹能管,必须炸
if not best or best_score < 0:
should_bomb = True
if should_bomb:
# 选最小的炸弹
bombs.sort(key=lambda p: p['type']['value'])
bomb = bombs[0]
bomb_score = self._evaluate_play(bomb, cards, is_lord, teammate_cards, desktop_type)
if bomb_score > best_score:
best = bomb
return best
async def make_decision_calling(self, cards: List[Card]) -> Dict[str, Any]:
"""叫地主决策"""
want = self.want_to_be_lord(cards)
return {
'action': 'call' if want else 'pass',
'data': {'want': want},
'reasoning': f'手牌强度评分: {evaluate_hand_strength(cards)}',
'confidence': 0.8 if want else 0.9
}
async def make_decision_playing(self, cards: List[Card],
desktop_type: Optional[Dict],
is_lord: bool,
teammate_cards: int) -> Dict[str, Any]:
"""出牌决策(优化版)"""
valid_plays = self.find_all_valid_plays(cards, desktop_type)
if not valid_plays:
return {
'action': 'pass',
'data': {},
'reasoning': '没有能管上的牌',
'confidence': 1.0
}
# 农民让牌逻辑:队友快走完了且自己不能一轮出完,不要主动出牌
if not is_lord and not desktop_type and teammate_cards <= 3:
my_rounds = self._estimate_min_rounds(cards)
if my_rounds > 1:
return {
'action': 'pass',
'data': {},
'reasoning': f'队友剩{teammate_cards}张牌,让队友先走',
'confidence': 0.9
}
best_play = self.choose_best_play(valid_plays, cards, is_lord, teammate_cards, desktop_type)
if best_play:
play_name = best_play['type']['name']
remaining = len(cards) - len(best_play['cards'])
reasoning = f'出 {play_name},剩余{remaining}张牌'
# 根据决策补充理由
if best_play['type']['type'] in ('bomb', 'joker_bomb'):
reasoning = f'炸弹!{reasoning}'
elif not is_lord and teammate_cards <= 3:
reasoning = f'帮队友管牌:{reasoning}'
elif is_lord and best_play['type']['type'] in ('straight', 'double_straight', 'triple_straight'):
reasoning = f'地主出长牌型逼拆:{reasoning}'
return {
'action': 'play',
'data': {'card_ids': best_play['card_ids']},
'reasoning': reasoning,
'confidence': 0.88
}
return {
'action': 'pass',
'data': {},
'reasoning': '选择不出',
'confidence': 0.7
}
async def make_decision(self, game_state: Dict[str, Any],
available_actions: List[str],
player_context: Dict[str, Any]) -> Dict[str, Any]:
"""AI 做出决策"""
start_time = asyncio.get_event_loop().time()
# 解析上下文
phase = game_state.get('phase') or game_state.get('data', {}).get('phase')
cards_data = player_context.get('cards', [])
cards = [Card(**c) for c in cards_data]
is_lord = player_context.get('is_lord', False)
teammate_cards = player_context.get('teammate_cards', 17)
# desktop_cards 可能在 game_state['doudizhu'] 或 game_state['data'] 中
desktop_type = None
if 'doudizhu' in game_state:
desktop_type = game_state['doudizhu'].get('desktop_cards')
elif 'data' in game_state:
desktop_type = game_state['data'].get('desktop_cards')
# 决策
if 'call' in available_actions or ('calling' in str(phase) and 'pass' in available_actions):
result = await self.make_decision_calling(cards)
else:
result = await self.make_decision_playing(cards, desktop_type, is_lord, teammate_cards)
# 记录调用时间
latency = (asyncio.get_event_loop().time() - start_time) * 1000
self.record_call(latency)
return result
class DoudizhuDeepSeekAI(LLMAdapter):
"""
斗地主 DeepSeek 大模型 AI
调用 DeepSeek API 做决策
"""
def __init__(self, api_key: str = None, config: Optional[Dict] = None):
file_config = DOUDIZHU_CONFIG.get('deepseek', {})
config = config or {}
# 优先级:传入参数 > 配置文件 > 环境变量 > 硬编码默认值
final_api_key = api_key or file_config.get('api_key') or os.getenv('DEEPSEEK_API_KEY', '')
final_model = config.get('model') or file_config.get('model') or 'deepseek-chat'
final_api_url = config.get('api_url') or file_config.get('api_url') or 'https://api.deepseek.com/v1/chat/completions'
super().__init__(
model=final_model,
api_key=final_api_key,
api_url=final_api_url,
config=config
)
self.ai_type = 'doudizhu_deepseek'
def get_name(self) -> str:
return f"斗地主DeepSeek({self.model})"
def _build_prompt_calling(self, cards: List[Card]) -> str:
"""构建叫地主提示词"""
cards_str = ', '.join([f"{c.suit}{c.rank}" for c in cards])
score = evaluate_hand_strength(cards)
return f"""你是一个斗地主高手。请根据你的手牌决定是否叫地主。
你的手牌(共17张):
{cards_str}
手牌强度评分: {score}/30 (分数越高手牌越好)
评分标准:
- K=1分, A=2分, 2=3分, 王=4分
- 炸弹额外+6分, 王炸额外+10分
规则:
- 如果叫地主,你将获得3张底牌,总共20张牌
- 地主需要对抗两个农民
- 地主先出牌
请决定是否叫地主,回答格式:
{{"call": true/false, "reason": "你的理由"}}
只输出JSON,不要其他内容。"""
def _build_prompt_playing(self, cards: List[Card], desktop_type: Optional[Dict],
is_lord: bool, game_history: List[Dict]) -> str:
"""构建出牌提示词"""
cards_str = ', '.join([f"{c.suit}{c.rank}({c.id})" for c in cards])
desktop_str = "无(你可以出任意牌)"
if desktop_type:
# desktop_type 中不包含 cards 字段(为了JSON序列化)
desktop_name = desktop_type.get('name', '未知')
desktop_value = desktop_type.get('value', 0)
desktop_str = f"{desktop_name} (牌值: {desktop_value})"
history_str = ""
if game_history:
for h in game_history[-5:]: # 最近5步
action = h.get('action', '')
player = h.get('player_id', '')[:8]
history_str += f"- {player}: {action}\n"
role = "地主" if is_lord else "农民"
return f"""你是一个斗地主高手。请根据当前局面选择最佳出牌策略。
你的角色: {role}
你的手牌(共{len(cards)}张):
{cards_str}
桌面上的牌: {desktop_str}
最近的操作记录:
{history_str if history_str else '无'}
牌型说明:
- 单张:任意一张牌
- 对子:两张相同牌值的牌
- 三张:三张相同牌值的牌
- 三带一:三张 + 一张单牌
- 三带二:三张 + 一对
- 顺子:5张或以上连续单牌(如3-4-5-6-7)
- 炸弹:四张相同牌值的牌
- 王炸:大王+小王
规则:
- 如果桌面上没有牌或你是最后出牌的,可以出任意合法牌型
- 否则必须出能管上桌面牌型的牌(同类型且更大,或炸弹/王炸)
- 如果无法或不想出牌,可以选择"不出"
请决定你的行动,回答格式:
{{"action": "play"/"pass", "card_ids": [牌的ID列表], "reason": "你的理由"}}
注意:
- action为"pass"时,card_ids为空数组
- 只能从你的手牌中选择牌的ID
- 只输出JSON,不要其他内容
你的决策:"""
async def _call_deepseek(self, prompt: str) -> Dict[str, Any]:
"""调用 DeepSeek API"""
if not self.api_key:
raise ValueError("DeepSeek API Key 未配置")
headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
payload = {
'model': self.model,
'messages': [
{'role': 'system', 'content': '你是一个斗地主游戏AI助手。请根据提示做出最佳决策,只输出JSON格式。'},
{'role': 'user', 'content': prompt}
],
'temperature': 0.3,
'max_tokens': 500
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(
self.api_url,
headers=headers,
json=payload,
timeout=aiohttp.ClientTimeout(total=self.timeout)
) as response:
if response.status != 200:
error_text = await response.text()
raise Exception(f"API Error: {response.status} - {error_text}")
data = await response.json()
content = data['choices'][0]['message']['content']
# 解析 JSON
try:
# 尝试直接解析
result = json.loads(content)
except json.JSONDecodeError:
# 尝试从文本中提取 JSON
import re
json_match = re.search(r'\{[^}]+\}', content)
if json_match:
result = json.loads(json_match.group())
else:
raise Exception(f"无法解析响应: {content}")
return result
except Exception as e:
print(f"DeepSeek API 调用失败: {e}")
# 失败时返回默认决策
return {'action': 'pass', 'reason': f'API调用失败: {str(e)}'}
async def make_decision(self, game_state: Dict[str, Any],
available_actions: List[str],
player_context: Dict[str, Any]) -> Dict[str, Any]:
"""AI 做出决策"""
import time
start_time = time.time()
# 解析上下文
phase = game_state.get('phase') or game_state.get('data', {}).get('phase')
cards_data = player_context.get('cards', [])
cards = [Card(**c) for c in cards_data]
is_lord = player_context.get('is_lord', False)
game_history = game_state.get('history', [])
# desktop_cards 可能在 game_state['doudizhu'] 或 game_state['data'] 中
desktop_type = None
if 'doudizhu' in game_state:
desktop_type = game_state['doudizhu'].get('desktop_cards')
elif 'data' in game_state:
desktop_type = game_state['data'].get('desktop_cards')
try:
if 'call' in available_actions or ('calling' in str(phase) and 'pass' in available_actions):
# 叫地主决策
prompt = self._build_prompt_calling(cards)
result = await self._call_deepseek(prompt)
want = result.get('call', False)
reason = result.get('reason', '大模型决策')
action_result = {
'action': 'call' if want else 'pass',
'data': {'want': want},
'reasoning': reason,
'confidence': 0.75
}
else:
# 出牌决策
prompt = self._build_prompt_playing(cards, desktop_type, is_lord, game_history)
result = await self._call_deepseek(prompt)
action = result.get('action', 'pass')
card_ids = result.get('card_ids', []) if action == 'play' else []
reason = result.get('reason', '大模型决策')
action_result = {
'action': action,
'data': {'card_ids': card_ids} if card_ids else {},
'reasoning': reason,
'confidence': 0.75
}
except Exception as e:
# 出错时回退到规则AI
print(f"DeepSeek AI 出错,回退到规则AI: {e}")
rule_ai = DoudizhuRuleAI()
action_result = await rule_ai.make_decision(game_state, available_actions, player_context)
# 记录调用时间
latency = (time.time() - start_time) * 1000
self.record_call(latency)
return action_result
def create_doudizhu_ai(ai_type: str, **kwargs) -> AIAdapter:
"""
创建斗地主AI的工厂函数
Args:
ai_type: 'rule' 或 'deepseek'
**kwargs: 额外配置
Returns:
AIAdapter 实例
"""
if ai_type == 'rule':
return DoudizhuRuleAI(kwargs.get('config'))
elif ai_type == 'deepseek':
api_key = kwargs.get('api_key') or os.getenv('DEEPSEEK_API_KEY')
return DoudizhuDeepSeekAI(api_key=api_key, config=kwargs.get('config'))
else:
raise ValueError(f"未知的AI类型: {ai_type}")
+470
View File
@@ -0,0 +1,470 @@
"""
斗地主游戏服务端实现
"""
import random
import logging
from typing import Dict, List, Optional, Any, Tuple
from enum import Enum
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
logger = logging.getLogger(__name__)
from engine.game_base import GameBase, GamePhase
from engine.player import Player
from doudizhu.game_logic import (
Deck, Card, identify_card_type, can_beat,
evaluate_hand_strength, cards_to_dicts, find_cards_by_ids,
CardType
)
class DoudizhuPhase(Enum):
"""斗地主游戏阶段"""
DEALING = "dealing" # 发牌中
CALLING = "calling" # 叫地主
PLAYING = "playing" # 出牌中
class DoudizhuGame(GameBase):
"""
斗地主游戏
3人游戏,支持 AI 和真人玩家
"""
def __init__(self, room_id: str, game_type: str = "doudizhu"):
super().__init__(room_id, game_type)
# 斗地主特定状态
self.deck: List[Card] = []
self.bottom_cards: List[Card] = []
self.lord_id: Optional[str] = None
self.doudizhu_phase = DoudizhuPhase.DEALING
self.desktop_cards: Optional[Dict] = None # 桌面上的牌型
self.last_played_id: Optional[str] = None # 最后出牌的玩家
self.pass_count = 0 # 连续不出次数
# 玩家手牌
self.player_cards: Dict[str, List[Card]] = {}
# 叫地主相关
self.calling_order: List[str] = [] # 叫地主顺序
self.calling_index = 0 # 当前叫地主索引
self.call_records: List[Dict] = [] # 叫地主记录
@property
def min_players(self) -> int:
"""最少玩家数"""
return 3
@property
def max_players(self) -> int:
"""最多玩家数"""
return 3
@property
def player_count(self) -> int:
return len(self.players)
def can_start(self) -> bool:
"""检查是否可以开始游戏"""
return self.player_count == self.max_players
def start(self):
"""开始游戏 - 发牌阶段"""
if not self.can_start():
raise ValueError("需要3名玩家才能开始")
# 初始化玩家手牌
self.player_cards = {pid: [] for pid in self.players}
# 创建并洗牌
self.deck = Deck.shuffle(Deck.create_full_deck())
# 发牌:每人17张
for i in range(51):
player_id = self.player_order[i % 3]
self.player_cards[player_id].append(self.deck[i])
# 剩余3张作为底牌
self.bottom_cards = self.deck[51:54]
# 排序手牌
for pid in self.player_cards:
self.player_cards[pid] = Deck.sort_cards(self.player_cards[pid])
# 初始化 state.player_states(供客户端使用)
for pid in self.players:
self.state.player_states[pid] = {
'cards': cards_to_dicts(self.player_cards[pid]),
'card_count': len(self.player_cards[pid]),
'score': 0
}
# 进入叫地主阶段
self.doudizhu_phase = DoudizhuPhase.CALLING
self.calling_order = self.player_order.copy()
self.calling_index = 0
# 随机决定谁先叫地主
random.shuffle(self.calling_order)
# 设置第一个叫地主的玩家
self.state.next_turn(self.calling_order[0])
self.state.phase = GamePhase.PLAYING
self.is_started = True
# 更新游戏状态数据
self._update_state_data()
def _update_state_data(self):
"""更新游戏状态数据"""
# desktop_cards 需要移除 cards 字段以便 JSON 序列化
desktop_cards_clean = None
if self.desktop_cards:
desktop_cards_clean = {k: v for k, v in self.desktop_cards.items() if k != 'cards'}
self.state.data = {
'phase': self.doudizhu_phase.value,
'current_turn': self.state.current_turn_player_id,
'lord_id': self.lord_id,
'bottom_cards': cards_to_dicts(self.bottom_cards) if self.lord_id else [],
'desktop_cards': desktop_cards_clean,
'last_played_id': self.last_played_id,
'pass_count': self.pass_count,
'player_cards_count': {
pid: len(cards) for pid, cards in self.player_cards.items()
},
}
def get_player_view(self, player_id: str) -> Dict[str, Any]:
"""
获取玩家的视角(只能看到自己的牌)
"""
view = self.to_dict()
# 只包含自己的手牌
for pid in self.players:
if pid == player_id:
view['my_cards'] = cards_to_dicts(self.player_cards.get(pid, []))
else:
view['my_cards'] = []
return view
def handle_action(self, player_id: str, action: str, data: Dict) -> Dict[str, Any]:
"""处理玩家操作"""
# 检查玩家是否存在
if player_id not in self.players:
return {'success': False, 'message': '玩家不存在'}
# 检查是否是当前回合
if self.state.current_turn_player_id != player_id:
return {'success': False, 'message': '不是你的回合'}
if self.doudizhu_phase == DoudizhuPhase.CALLING:
return self._handle_calling_action(player_id, action, data)
elif self.doudizhu_phase == DoudizhuPhase.PLAYING:
return self._handle_playing_action(player_id, action, data)
else:
return {'success': False, 'message': '无效的游戏阶段'}
def _handle_calling_action(self, player_id: str, action: str, data: Dict) -> Dict[str, Any]:
"""处理叫地主阶段的操作"""
if action not in ['call', 'pass']:
return {'success': False, 'message': '无效的操作,只能是 call 或 pass'}
want_to_call = data.get('want', False)
# 记录叫地主
self.call_records.append({
'player_id': player_id,
'action': action,
'want': want_to_call
})
if action == 'call' and want_to_call:
# 成为地主
self.lord_id = player_id
logger.info(f"Player {player_id} calling lord, before: {len(self.player_cards[player_id])} cards")
self.player_cards[player_id].extend(self.bottom_cards)
self.player_cards[player_id] = Deck.sort_cards(self.player_cards[player_id])
logger.info(f"After adding bottom cards: {len(self.player_cards[player_id])} cards")
# 更新 state.player_states
self.state.player_states[player_id] = {
'cards': cards_to_dicts(self.player_cards[player_id]),
'card_count': len(self.player_cards[player_id]),
'score': 0
}
# 设置地主为第一个出牌
self.doudizhu_phase = DoudizhuPhase.PLAYING
self.state.next_turn(player_id)
self._update_state_data()
return {
'success': True,
'message': f'{self.players[player_id].name} 成为地主',
'lord_id': player_id,
'bottom_cards': cards_to_dicts(self.bottom_cards),
'phase': 'playing'
}
# 下一个叫地主
self.calling_index += 1
# 如果都没叫,随机选一个人当地主
if self.calling_index >= len(self.calling_order):
lord_id = random.choice(self.calling_order)
self.lord_id = lord_id
self.player_cards[lord_id].extend(self.bottom_cards)
self.player_cards[lord_id] = Deck.sort_cards(self.player_cards[lord_id])
# 更新 state.player_states
self.state.player_states[lord_id] = {
'cards': cards_to_dicts(self.player_cards[lord_id]),
'card_count': len(self.player_cards[lord_id]),
'score': 0
}
self.doudizhu_phase = DoudizhuPhase.PLAYING
self.state.next_turn(lord_id)
self._update_state_data()
return {
'success': True,
'message': f'{self.players[lord_id].name} 成为地主(随机)',
'lord_id': lord_id,
'bottom_cards': cards_to_dicts(self.bottom_cards),
'phase': 'playing'
}
# 轮到下一个
next_caller = self.calling_order[self.calling_index]
self.state.next_turn(next_caller)
self._update_state_data()
return {
'success': True,
'message': f'轮到 {self.players[next_caller].name} 叫地主',
'next_caller': next_caller
}
def _handle_playing_action(self, player_id: str, action: str, data: Dict) -> Dict[str, Any]:
"""处理出牌阶段的操作"""
import logging
logger = logging.getLogger(__name__)
if action not in ['play', 'pass']:
return {'success': False, 'message': '无效的操作,只能是 play 或 pass'}
if action == 'pass':
return self._handle_pass(player_id)
# 出牌
card_ids = data.get('card_ids', [])
logger.info(f"Player {player_id} trying to play cards: {card_ids}")
logger.info(f"Player cards: {[c.id for c in self.player_cards[player_id]]}")
if not card_ids:
return {'success': False, 'message': '请选择要出的牌'}
# 查找牌
cards = find_cards_by_ids(self.player_cards[player_id], card_ids)
logger.info(f"Found cards: {cards}")
if len(cards) != len(card_ids):
return {'success': False, 'message': f'无效的牌ID: 期望{card_ids}, 找到{[c.id for c in cards]}'}
# 识别牌型
card_type = identify_card_type(cards)
if not card_type:
return {'success': False, 'message': '非法牌型'}
# 验证能否管上
if self.desktop_cards and not can_beat(self.desktop_cards, card_type):
return {'success': False, 'message': '管不上'}
# 检查牌是否都在手中
player_card_ids = {c.id for c in self.player_cards[player_id]}
if not set(card_ids).issubset(player_card_ids):
return {'success': False, 'message': '牌不在手中'}
# 执行出牌
self.player_cards[player_id] = [
c for c in self.player_cards[player_id]
if c.id not in card_ids
]
# 更新 state.player_states
self.state.player_states[player_id] = {
'cards': cards_to_dicts(self.player_cards[player_id]),
'card_count': len(self.player_cards[player_id]),
'score': 0
}
self.desktop_cards = card_type
self.last_played_id = player_id
self.pass_count = 0
# 记录历史
self.state.add_history('play', player_id, {
'cards': cards_to_dicts(cards),
'card_type': card_type['name']
})
# 检查胜利
if len(self.player_cards[player_id]) == 0:
self.end_game(player_id)
self._update_state_data()
return {
'success': True,
'message': f'{self.players[player_id].name} 获胜!',
'winner': player_id,
'played_cards': cards_to_dicts(cards),
'card_type': {k: v for k, v in card_type.items() if k != 'cards'},
'game_over': True
}
# 下一个玩家
self._next_player()
self._update_state_data()
return {
'success': True,
'message': f'{self.players[player_id].name} 出了 {card_type["name"]}',
'played_cards': cards_to_dicts(cards),
'card_type': {k: v for k, v in card_type.items() if k != 'cards'},
'next_player': self.state.current_turn_player_id,
'remaining_cards': len(self.player_cards[player_id])
}
def _handle_pass(self, player_id: str) -> Dict[str, Any]:
"""处理不出"""
# 如果自己是最后出牌的,不能不出
if self.last_played_id == player_id:
return {'success': False, 'message': '你必须出牌'}
self.pass_count += 1
# 记录历史
self.state.add_history('pass', player_id, {})
# 如果连续两人不出,清空桌面,轮到下家
if self.pass_count >= 2:
self.desktop_cards = None
self.pass_count = 0
self._next_player() # 关键:清空后轮到下家出牌
self._update_state_data()
return {
'success': True,
'message': f'{self.players[player_id].name} 不出,桌面清空',
'clear_desktop': True,
'next_player': self.state.current_turn_player_id
}
self._next_player()
self._update_state_data()
return {
'success': True,
'message': f'{self.players[player_id].name} 不出',
'next_player': self.state.current_turn_player_id
}
def _next_player(self):
"""切换到下一个玩家"""
current_idx = self.player_order.index(self.state.current_turn_player_id)
next_idx = (current_idx + 1) % 3
self.state.next_turn(self.player_order[next_idx])
def get_valid_actions(self, player_id: str) -> List[str]:
"""获取可用操作"""
if self.state.current_turn_player_id != player_id:
return []
if self.doudizhu_phase == DoudizhuPhase.CALLING:
return ['call', 'pass']
elif self.doudizhu_phase == DoudizhuPhase.PLAYING:
actions = ['pass']
# 检查是否可以出牌
if self.last_played_id != player_id:
actions.append('play')
else:
# 自己是最后出牌的,必须出牌
actions = ['play']
return actions
return []
def get_current_player(self):
"""获取当前回合玩家"""
if self.state.current_turn_player_id:
return self.players.get(self.state.current_turn_player_id)
return None
def check_winner(self) -> Optional[str]:
"""检查获胜者"""
return self.state.winner_id
def to_dict(self) -> Dict[str, Any]:
"""序列化游戏状态"""
data = super().to_dict()
# 添加斗地主特定数据
# desktop_cards 需要正确处理cards字段以便 JSON 序列化
desktop_cards_clean = None
if self.desktop_cards:
desktop_cards_clean = {
k: (cards_to_dicts(v) if k == 'cards' else v)
for k, v in self.desktop_cards.items()
}
player_cards_count = {
pid: len(cards) for pid, cards in self.player_cards.items()
}
logger.info(f"to_dict: player_cards_count = {player_cards_count}")
data['doudizhu'] = {
'phase': self.doudizhu_phase.value if self.doudizhu_phase else None,
'lord_id': self.lord_id,
'bottom_cards': cards_to_dicts(self.bottom_cards) if self.lord_id else [],
'desktop_cards': desktop_cards_clean,
'last_played_id': self.last_played_id,
'pass_count': self.pass_count,
'player_cards_count': player_cards_count,
}
return data
def get_game_result(self) -> Dict[str, Any]:
"""获取游戏结果"""
if not self.is_ended:
return {'ended': False}
winner = self.players.get(self.state.winner_id)
is_lord_win = self.state.winner_id == self.lord_id
return {
'ended': True,
'winner_id': self.state.winner_id,
'winner_name': winner.name if winner else 'Unknown',
'is_lord_win': is_lord_win,
'lord_id': self.lord_id,
'players': [
{
'id': pid,
'name': p.name,
'is_lord': pid == self.lord_id,
'remaining_cards': len(self.player_cards.get(pid, []))
}
for pid, p in self.players.items()
]
}
+338
View File
@@ -0,0 +1,338 @@
"""
斗地主游戏逻辑
牌型识别、牌组管理、规则验证
"""
import random
from typing import List, Dict, Optional, Any
from dataclasses import dataclass, asdict
from enum import Enum
class CardType(Enum):
"""牌型枚举"""
SINGLE = "single" # 单张
PAIR = "pair" # 对子
TRIPLE = "triple" # 三张
TRIPLE_WITH_SINGLE = "triple_with_single" # 三带一
TRIPLE_WITH_PAIR = "triple_with_pair" # 三带二
STRAIGHT = "straight" # 顺子
DOUBLE_STRAIGHT = "double_straight" # 连对
TRIPLE_STRAIGHT = "triple_straight" # 飞机
QUAD_WITH_TWO = "quad_with_two" # 四带二
BOMB = "bomb" # 炸弹
JOKER_BOMB = "joker_bomb" # 王炸
PASS = "pass" # 不出
@dataclass
class Card:
"""扑克牌"""
id: int
rank: str
suit: str
value: int
is_joker: bool = False
def to_dict(self) -> Dict:
return asdict(self)
def __repr__(self):
return f"{self.suit}{self.rank}"
class Deck:
"""牌组管理"""
SUITS = ['♠', '♥', '♣', '♦']
RANKS = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2']
@classmethod
def create_full_deck(cls) -> List[Card]:
"""创建完整牌组(54张)"""
deck = []
card_id = 0
# 52张普通牌
for rank in cls.RANKS:
for suit in cls.SUITS:
value = cls.RANKS.index(rank) + 3 # 3=3, ..., A=14, 2=15
deck.append(Card(
id=card_id,
rank=rank,
suit=suit,
value=value,
is_joker=False
))
card_id += 1
# 小王
deck.append(Card(
id=card_id,
rank='小王',
suit='🃏',
value=16,
is_joker=True
))
card_id += 1
# 大王
deck.append(Card(
id=card_id,
rank='大王',
suit='🃏',
value=17,
is_joker=True
))
return deck
@classmethod
def shuffle(cls, deck: List[Card]) -> List[Card]:
"""洗牌"""
shuffled = deck.copy()
random.shuffle(shuffled)
return shuffled
@classmethod
def sort_cards(cls, cards: List[Card]) -> List[Card]:
"""按牌值排序"""
return sorted(cards, key=lambda c: c.value)
def identify_card_type(cards: List[Card]) -> Optional[Dict[str, Any]]:
"""
识别牌型
返回: {type: str, value: int, length: int, name: str, cards: List[Card]}
注意: type 返回字符串而非 CardType 枚举,便于 JSON 序列化
"""
if not cards or len(cards) == 0:
return None
n = len(cards)
sorted_cards = Deck.sort_cards(cards)
values = [c.value for c in sorted_cards]
# 统计每个牌值的数量
value_count = {}
for v in values:
value_count[v] = value_count.get(v, 0) + 1
counts = sorted(value_count.values(), reverse=True)
unique_values = sorted(value_count.keys())
# 王炸
if n == 2 and all(c.is_joker for c in cards):
return {
'type': 'joker_bomb',
'value': 100,
'length': 2,
'name': '王炸',
'cards': cards
}
# 单张
if n == 1:
return {
'type': 'single',
'value': values[0],
'length': 1,
'name': f'单张{sorted_cards[0].rank}',
'cards': cards
}
# 对子
if n == 2 and counts == [2]:
return {
'type': 'pair',
'value': values[0],
'length': 2,
'name': f'对子{sorted_cards[0].rank}',
'cards': cards
}
# 三张
if n == 3 and counts == [3]:
return {
'type': 'triple',
'value': values[0],
'length': 3,
'name': f'三张{sorted_cards[0].rank}',
'cards': cards
}
# 三带一
if n == 4 and counts == [3, 1]:
triple_value = [v for v, c in value_count.items() if c == 3][0]
return {
'type': 'triple_with_single',
'value': triple_value,
'length': 4,
'name': f'三带一',
'cards': cards
}
# 三带二
if n == 5 and counts == [3, 2]:
triple_value = [v for v, c in value_count.items() if c == 3][0]
return {
'type': 'triple_with_pair',
'value': triple_value,
'length': 5,
'name': f'三带二',
'cards': cards
}
# 炸弹
if n == 4 and counts == [4]:
return {
'type': 'bomb',
'value': values[0],
'length': 4,
'name': f'炸弹{sorted_cards[0].rank}',
'cards': cards
}
# 顺子 (>=5张连续,不能含2和王)
if n >= 5 and max(values) <= 14: # A=14
if len(unique_values) == n and unique_values[-1] - unique_values[0] == n - 1 and counts == [1] * n:
return {
'type': 'straight',
'value': unique_values[0],
'length': n,
'name': f'{n}连顺',
'cards': cards
}
# 连对 (>=3对连续)
if n >= 6 and n % 2 == 0 and counts == [2] * (n // 2):
pair_values = [v for v, c in value_count.items() if c == 2]
if len(pair_values) == n // 2 and max(pair_values) <= 14:
if pair_values[-1] - pair_values[0] == len(pair_values) - 1:
return {
'type': 'double_straight',
'value': pair_values[0],
'length': n // 2,
'name': f'{n // 2}连对',
'cards': cards
}
# 飞机 (>=2组连续三张)
if n >= 6 and n % 3 == 0:
triple_values = [v for v, c in value_count.items() if c == 3]
if len(triple_values) == n // 3 and max(triple_values) <= 14:
if triple_values[-1] - triple_values[0] == len(triple_values) - 1:
return {
'type': 'triple_straight',
'value': triple_values[0],
'length': n // 3,
'name': f'{n // 3}连三张',
'cards': cards
}
# 四带二
if n == 6 and counts == [4, 1, 1]:
quad_value = [v for v, c in value_count.items() if c == 4][0]
return {
'type': 'quad_with_two',
'value': quad_value,
'length': 6,
'name': '四带二',
'cards': cards
}
if n == 8 and counts == [4, 2, 2]:
quad_value = [v for v, c in value_count.items() if c == 4][0]
return {
'type': 'quad_with_two',
'value': quad_value,
'length': 8,
'name': '四带两对',
'cards': cards
}
return None
def can_beat(desktop_type: Optional[Dict], new_type: Dict) -> bool:
"""
判断新牌型能否管上桌面牌型
type字段现在是字符串而非CardType枚举
"""
if not desktop_type:
return True
new_type_str = new_type['type']
desktop_type_str = desktop_type['type']
# 王炸最大
if new_type_str == 'joker_bomb':
return True
if desktop_type_str == 'joker_bomb':
return False
# 炸弹 > 非炸弹
if new_type_str == 'bomb' and desktop_type_str != 'bomb':
return True
if desktop_type_str == 'bomb' and new_type_str != 'bomb':
return False
# 同类型比较
if new_type_str != desktop_type_str:
return False
# 连牌数量必须相同
if new_type.get('length') != desktop_type.get('length'):
return False
# 比较牌值
return new_type['value'] > desktop_type['value']
def evaluate_hand_strength(cards: List[Card]) -> int:
"""
评估手牌强度(用于叫地主决策)
返回分数,越高表示手牌越好
"""
score = 0
# 大牌加分
for card in cards:
if card.value >= 16: # 王
score += 4
elif card.value == 15: # 2
score += 3
elif card.value == 14: # A
score += 2
elif card.value == 13: # K
score += 1
# 炸弹加分
value_count = {}
for c in cards:
value_count[c.value] = value_count.get(c.value, 0) + 1
for count in value_count.values():
if count == 4:
score += 6
# 王炸
jokers = [c for c in cards if c.is_joker]
if len(jokers) == 2:
score += 10
return score
def cards_to_dicts(cards: List[Card]) -> List[Dict]:
"""转换为字典列表"""
return [c.to_dict() for c in cards]
def find_cards_by_ids(all_cards: List[Card], card_ids: List[int]) -> List[Card]:
"""通过ID查找牌"""
card_map = {c.id: c for c in all_cards}
return [card_map.get(cid) for cid in card_ids if cid in card_map]
# 导出
CARD_TYPES = CardType
+7
View File
@@ -0,0 +1,7 @@
{
"deepseek": {
"api_key": "sk-8cb88f614b5b4def882d0ac46025cdcc",
"model": "deepseek-v4-flash",
"api_url": "https://api.deepseek.com/v1/chat/completions"
}
}