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
+447
View File
@@ -0,0 +1,447 @@
/**
* 斗地主游戏核心逻辑
* 本地实现,完整游戏流程
*/
// ========== 牌组定义 ==========
const SUITS = ['♠', '♥', '♣', '♦'];
const RANKS = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2'];
// 生成完整牌组
function generateDeck() {
const deck = [];
let id = 0;
for (const rank of RANKS) {
for (const suit of SUITS) {
deck.push({
id: id++,
rank: rank,
suit: suit,
value: RANKS.indexOf(rank) + 3,
isJoker: false
});
}
}
deck.push({ id: id++, rank: '小王', suit: '🃏', value: 16, isJoker: true });
deck.push({ id: id++, rank: '大王', suit: '🃏', value: 17, isJoker: true });
return deck;
}
// 洗牌
function shuffleDeck(deck) {
const shuffled = [...deck];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
// ========== 牌型识别 ==========
const CARD_TYPES = {
SINGLE: 'single', // 单张
PAIR: 'pair', // 对子
TRIPLE1: 'triple1', // 三带一
STRAIGHT: 'straight', // 顺子
BOMB: 'bomb', // 炸弹
JOKER: 'joker' // 王炸
};
// 识别牌型
function identifyCardType(cards) {
if (!cards || cards.length === 0) return null;
const sorted = [...cards].sort((a, b) => a.value - b.value);
const n = cards.length;
// 王炸
if (n === 2 && cards.every(c => c.isJoker)) {
return { type: CARD_TYPES.JOKER, value: 100, cards: cards, name: '王炸' };
}
// 单张
if (n === 1) {
return { type: CARD_TYPES.SINGLE, value: cards[0].value, cards: cards, name: '单张' };
}
// 对子
if (n === 2 && sorted[0].value === sorted[1].value) {
return { type: CARD_TYPES.PAIR, value: sorted[0].value, cards: cards, name: '对子' };
}
// 炸弹
if (n === 4 && sorted.every(c => c.value === sorted[0].value)) {
return { type: CARD_TYPES.BOMB, value: sorted[0].value, cards: cards, name: '炸弹' };
}
// 三带一
if (n === 4) {
const valueCount = {};
cards.forEach(c => valueCount[c.value] = (valueCount[c.value] || 0) + 1);
const values = Object.values(valueCount);
if (values.includes(3) && values.includes(1)) {
const tripleValue = parseInt(Object.keys(valueCount).find(k => valueCount[k] === 3));
return { type: CARD_TYPES.TRIPLE1, value: tripleValue, cards: cards, name: '三带一' };
}
}
// 顺子 (>=5张连续,不能含2和王)
if (n >= 5) {
const hasInvalid = cards.some(c => c.value >= 15); // 2=15, 王=16,17
if (!hasInvalid) {
const isStraight = sorted.every((c, i) => {
if (i === 0) return true;
return c.value === sorted[i-1].value + 1;
});
if (isStraight) {
return {
type: CARD_TYPES.STRAIGHT,
value: sorted[0].value,
length: n,
cards: cards,
name: '顺子'
};
}
}
}
return null;
}
// 比较牌型大小
function canBeat(desktop, newType) {
if (!desktop) return true;
// 王炸最大
if (newType.type === CARD_TYPES.JOKER) return true;
if (desktop.type === CARD_TYPES.JOKER) return false;
// 炸弹 > 非炸弹
if (newType.type === CARD_TYPES.BOMB && desktop.type !== CARD_TYPES.BOMB) return true;
if (desktop.type === CARD_TYPES.BOMB && newType.type !== CARD_TYPES.BOMB) return false;
// 同类型比较
if (newType.type !== desktop.type) return false;
if (newType.length && desktop.length && newType.length !== desktop.length) return false;
return newType.value > desktop.value;
}
// ========== AI逻辑 ==========
class DoudizhuAI {
constructor(playerId) {
this.id = playerId;
}
// 评估手牌强度(用于叫地主)
evaluateHand(cards) {
let score = 0;
// 大牌加分
cards.forEach(c => {
if (c.value >= 15) score += 3; // 2, 王
else if (c.value >= 14) score += 2; // A
else if (c.value >= 13) score += 1; // K
});
// 炸弹加分
const valueCount = {};
cards.forEach(c => valueCount[c.value] = (valueCount[c.value] || 0) + 1);
Object.values(valueCount).forEach(count => {
if (count === 4) score += 5;
});
// 王炸
if (cards.filter(c => c.isJoker).length === 2) score += 8;
return score;
}
// 决定是否叫地主
wantToBeLord(cards) {
const score = this.evaluateHand(cards);
return score >= 8; // 分数>=8才当地主
}
// 找出所有可出的牌型
findAllValidPlays(cards, desktop) {
const validPlays = [];
const n = cards.length;
// 辅助函数:生成所有组合
const getCombinations = (arr, k) => {
if (k === 0) return [[]];
if (arr.length < k) return [];
const result = [];
for (let i = 0; i <= arr.length - k; i++) {
const subCombos = getCombinations(arr.slice(i + 1), k - 1);
subCombos.forEach(sub => result.push([arr[i], ...sub]));
}
return result;
};
// 尝试不同数量的牌
for (let k = 1; k <= Math.min(5, n); k++) {
const combos = getCombinations(cards, k);
combos.forEach(combo => {
const cardType = identifyCardType(combo);
if (cardType && canBeat(desktop, cardType)) {
validPlays.push({ cards: combo, type: cardType });
}
});
}
// 炸弹单独处理(可以管任何非炸弹)
const valueCount = {};
cards.forEach(c => valueCount[c.value] = (valueCount[c.value] || 0) + 1);
Object.entries(valueCount).forEach(([value, count]) => {
if (count === 4) {
const bombCards = cards.filter(c => c.value == value);
const bombType = identifyCardType(bombCards);
if (bombType && canBeat(desktop, bombType)) {
validPlays.push({ cards: bombCards, type: bombType });
}
}
});
// 王炸
const jokers = cards.filter(c => c.isJoker);
if (jokers.length === 2) {
const jokerType = identifyCardType(jokers);
if (jokerType && canBeat(desktop, jokerType)) {
validPlays.push({ cards: jokers, type: jokerType });
}
}
return validPlays;
}
// 选择最佳出牌
chooseBestPlay(validPlays, cards, isLord, teammateCards) {
if (validPlays.length === 0) return null;
// 排序策略
validPlays.sort((a, b) => {
// 优先出能走完的
const aRemaining = cards.length - a.cards.length;
const bRemaining = cards.length - b.cards.length;
if (aRemaining === 0) return -1;
if (bRemaining === 0) return 1;
// 优先出小牌
return a.type.value - b.type.value;
});
// 选择第一个(最小且合法的)
return validPlays[0];
}
// AI决策
makeDecision(cards, desktop, isLord, teammateCards) {
const validPlays = this.findAllValidPlays(cards, desktop);
if (validPlays.length === 0) {
return { action: 'pass' };
}
const bestPlay = this.chooseBestPlay(validPlays, cards, isLord, teammateCards);
if (bestPlay) {
return { action: 'play', cards: bestPlay.cards, type: bestPlay.type };
}
return { action: 'pass' };
}
}
// ========== 游戏主类 ==========
class DoudizhuGame {
constructor() {
this.players = [
{ id: 0, cards: [], isLord: false, name: '玩家', ai: null },
{ id: 1, cards: [], isLord: false, name: '农民甲', ai: new DoudizhuAI(1) },
{ id: 2, cards: [], isLord: false, name: '农民乙', ai: new DoudizhuAI(2) }
];
this.deck = [];
this.bottomCards = [];
this.currentPlayer = 0;
this.gamePhase = 'init';
this.desktopCards = null;
this.lastAction = null;
this.passCount = 0;
}
init() {
this.deck = shuffleDeck(generateDeck());
this.players.forEach(p => {
p.cards = [];
p.isLord = false;
});
this.bottomCards = [];
this.desktopCards = null;
this.passCount = 0;
this.gamePhase = 'dealing';
}
deal() {
// 发51张,每人17张
for (let i = 0; i < 51; i++) {
this.players[i % 3].cards.push(this.deck[i]);
}
// 剩余3张底牌
this.bottomCards = this.deck.slice(51, 54);
// 排序
this.players.forEach(p => {
p.cards.sort((a, b) => a.value - b.value);
});
this.gamePhase = 'calling';
return {
players: this.players.map(p => ({
id: p.id,
cardCount: p.cards.length,
cards: p.id === 0 ? p.cards : null // 只有玩家能看到自己的牌
})),
bottomCards: this.bottomCards
};
}
// 叫地主
callLord(playerId, want) {
if (want) {
this.players[playerId].isLord = true;
this.players[playerId].cards.push(...this.bottomCards);
this.players[playerId].cards.sort((a, b) => a.value - b.value);
this.currentPlayer = playerId;
this.gamePhase = 'playing';
return { success: true, lordId: playerId };
}
return { success: false };
}
// AI叫地主
aiCallLord() {
for (let i = 1; i <= 2; i++) {
const ai = this.players[i].ai;
if (ai.wantToBeLord(this.players[i].cards)) {
return this.callLord(i, true);
}
}
// 都没叫,随机选一个
const randomLord = Math.floor(Math.random() * 3);
return this.callLord(randomLord, true);
}
// 出牌
playCards(playerId, cards) {
const player = this.players[playerId];
// 验证牌是否在手中
const cardIds = cards.map(c => c.id);
const hasAllCards = cardIds.every(id =>
player.cards.some(c => c.id === id)
);
if (!hasAllCards) return { success: false, error: '牌不在手中' };
// 识别牌型
const cardType = identifyCardType(cards);
if (!cardType) return { success: false, error: '非法牌型' };
// 验证能否管上
if (this.desktopCards && !canBeat(this.desktopCards, cardType)) {
return { success: false, error: '管不上' };
}
// 执行出牌
player.cards = player.cards.filter(c => !cardIds.includes(c.id));
this.desktopCards = cardType;
this.lastAction = 'play';
this.passCount = 0;
// 检查胜利
if (player.cards.length === 0) {
return {
success: true,
cardType: cardType,
remainingCards: player.cards.length,
gameOver: true,
winner: playerId
};
}
// 下一个玩家
this.currentPlayer = (playerId + 1) % 3;
return {
success: true,
cardType: cardType,
remainingCards: player.cards.length,
nextPlayer: this.currentPlayer
};
}
// 不出
pass(playerId) {
this.passCount++;
this.lastAction = 'pass';
// 如果连续两人不出,清空桌面
if (this.passCount >= 2) {
this.desktopCards = null;
this.passCount = 0;
this.currentPlayer = (playerId + 1) % 3;
return { success: true, clearDesktop: true, nextPlayer: this.currentPlayer };
}
this.currentPlayer = (playerId + 1) % 3;
return { success: true, nextPlayer: this.currentPlayer };
}
// AI决策
aiPlay() {
const aiPlayer = this.players[this.currentPlayer];
const ai = aiPlayer.ai;
const teammateCards = this.currentPlayer === 1
? this.players[2].cards.length
: this.players[1].cards.length;
const decision = ai.makeDecision(
aiPlayer.cards,
this.desktopCards,
aiPlayer.isLord,
teammateCards
);
if (decision.action === 'play') {
return this.playCards(this.currentPlayer, decision.cards);
} else {
return this.pass(this.currentPlayer);
}
}
// 获取游戏状态
getState() {
return {
phase: this.gamePhase,
currentPlayer: this.currentPlayer,
desktopCards: this.desktopCards,
players: this.players.map(p => ({
id: p.id,
name: p.name,
isLord: p.isLord,
cardCount: p.cards.length,
cards: p.id === 0 ? p.cards : null
}))
};
}
}
// 导出
if (typeof module !== 'undefined' && module.exports) {
module.exports = { DoudizhuGame, DoudizhuAI, identifyCardType, canBeat, CARD_TYPES };
}
+121
View File
@@ -0,0 +1,121 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI斗地主</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- 用户分数栏 -->
<div class="score-bar" id="scoreBar">
<div class="score-info">
<span class="score-label">斗地主积分:</span>
<span class="score-value" id="scoreValue">--</span>
</div>
<div class="user-name" id="userName">--</div>
</div>
<div class="game-container">
<!-- 顶部:底牌区 -->
<div class="deck-area">
<div class="deck-label">底牌</div>
<div class="deck-cards">
<div class="card back"></div>
<div class="card back"></div>
<div class="card back"></div>
</div>
</div>
<!-- 左侧玩家 -->
<div class="player left-player">
<div class="avatar">
<div class="avatar-img">AI1</div>
<div class="player-name">农民甲</div>
<div class="player-role" id="left-role">?</div>
</div>
<div class="card-count">17张</div>
<div class="cards-back">
<!-- 牌背堆叠 -->
<div class="card-stack">
<div class="card-small back"></div>
<div class="card-small back"></div>
<div class="card-small back"></div>
</div>
</div>
</div>
<!-- 右侧玩家 -->
<div class="player right-player">
<div class="card-count">17张</div>
<div class="cards-back">
<div class="card-stack">
<div class="card-small back"></div>
<div class="card-small back"></div>
<div class="card-small back"></div>
</div>
</div>
<div class="avatar">
<div class="avatar-img">AI2</div>
<div class="player-name">农民乙</div>
<div class="player-role" id="right-role">?</div>
</div>
</div>
<!-- 中央:桌面出牌区 -->
<div class="table-area">
<div class="last-played">
<div class="played-by">等待出牌...</div>
<div class="played-cards">
<!-- 出的牌显示在这里 -->
</div>
</div>
</div>
<!-- 底部:玩家自己 -->
<div class="player-self">
<div class="self-info">
<div class="avatar">
<div class="avatar-img me">我</div>
<div class="player-name">玩家</div>
<div class="player-role" id="my-role">?</div>
</div>
</div>
<!-- 手牌区 -->
<div class="hand-cards" id="hand-cards">
<!-- 手牌由JS动态生成 -->
</div>
<!-- 操作按钮 -->
<div class="action-buttons">
<button class="btn btn-primary" id="btn-play" disabled>出牌</button>
<button class="btn btn-secondary" id="btn-pass" disabled>不出</button>
<button class="btn btn-hint" id="btn-hint" disabled>提示</button>
</div>
</div>
<!-- 游戏状态提示 -->
<div class="game-status" id="game-status">点击"开始游戏"</div>
<!-- 开始按钮(居中) -->
<div class="start-screen" id="start-screen">
<button class="btn-start" id="btn-start">开始游戏</button>
</div>
<!-- 叫地主弹窗 -->
<div class="call-lord-modal" id="call-lord-modal" style="display: none;">
<div class="modal-content">
<h3>是否叫地主?</h3>
<div class="modal-buttons">
<button class="btn btn-primary" id="btn-call-yes">叫地主</button>
<button class="btn btn-secondary" id="btn-call-no">不叫</button>
</div>
</div>
</div>
</div>
<script src="game.js?v=2"></script>
<script src="ui.js?v=2"></script>
</body>
</html>
+866
View File
@@ -0,0 +1,866 @@
/* 斗地主UI样式 - 参考QQ斗地主 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background: linear-gradient(135deg, #0d2847 0%, #1a3a5c 50%, #0d2847 100%);
min-height: 100vh;
overflow: hidden;
}
/* ========== 顶部分数栏 ========== */
.score-bar {
position: fixed;
top: 10px;
right: 10px;
display: flex;
align-items: center;
gap: 15px;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(10px);
padding: 8px 16px;
border-radius: 20px;
border: 1px solid rgba(255, 215, 0, 0.2);
z-index: 1000;
}
.score-info {
display: flex;
align-items: center;
gap: 6px;
}
.score-label {
font-size: 12px;
color: rgba(255, 255, 255, 0.6);
}
.score-value {
font-size: 16px;
font-weight: bold;
color: #ffd700;
text-shadow: 0 0 10px rgba(255, 215, 0, 0.5);
}
.score-bar .user-name {
font-size: 13px;
color: rgba(255, 255, 255, 0.8);
padding-left: 12px;
border-left: 1px solid rgba(255, 255, 255, 0.2);
}
.game-container {
position: relative;
width: 100vw;
height: 100vh;
max-width: 1200px;
max-height: 900px;
margin: 0 auto;
}
/* ========== 牌桌背景纹理 ========== */
.game-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image:
radial-gradient(circle at 20% 50%, rgba(255,255,255,0.03) 0%, transparent 50%),
radial-gradient(circle at 80% 50%, rgba(255,255,255,0.03) 0%, transparent 50%);
pointer-events: none;
}
/* ========== 顶部底牌区 ========== */
.deck-area {
position: absolute;
top: 10px;
left: 10px;
display: flex;
flex-direction: column;
align-items: center;
gap: 5px;
z-index: 50;
}
.deck-label {
color: #ffd700;
font-size: 14px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}
.deck-cards {
display: flex;
gap: -15px;
}
.deck-cards .card {
width: 50px;
height: 70px;
margin-left: -15px;
}
.deck-cards .card:first-child {
margin-left: 0;
}
/* ========== 扑克牌样式 ========== */
.card {
width: 80px;
height: 112px;
background: white;
border-radius: 8px;
border: 1px solid #ccc;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 6px;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
user-select: none;
position: relative;
overflow: hidden;
}
/* 扑克牌角标 */
.card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, transparent, rgba(0,0,0,0.1), transparent);
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 12px rgba(0,0,0,0.4);
}
.card.selected {
transform: translateY(-15px);
box-shadow: 0 6px 16px rgba(255,215,0,0.4);
border-color: #ffd700;
}
.card.back {
background: linear-gradient(135deg, #1e3a5f 0%, #2d5a8f 50%, #1e3a5f 100%);
border: 2px solid #4a7ab8;
}
.card.back::after {
content: '♠';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
color: rgba(255,255,255,0.3);
}
.card-small {
width: 40px;
height: 56px;
border-radius: 4px;
}
/* 牌面内容 */
.card-top {
font-size: 16px;
font-weight: bold;
line-height: 1;
}
.card-center {
font-size: 36px;
text-align: center;
line-height: 1;
}
.card-bottom {
font-size: 16px;
font-weight: bold;
line-height: 1;
transform: rotate(180deg);
}
.red { color: #e74c3c; }
.black { color: #2c3e50; }
/* ========== 玩家头像 ========== */
.avatar {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
}
.avatar-img {
width: 60px;
height: 60px;
border-radius: 50%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
font-size: 18px;
border: 3px solid rgba(255,255,255,0.3);
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}
.avatar-img.me {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
.player-name {
color: white;
font-size: 12px;
text-shadow: 0 1px 2px rgba(0,0,0,0.5);
}
.player-role {
color: #ffd700;
font-size: 11px;
background: rgba(0,0,0,0.3);
padding: 2px 8px;
border-radius: 10px;
}
/* ========== 左侧玩家 ========== */
.left-player {
position: absolute;
left: 20px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.left-player .card-count {
color: #ffd700;
font-size: 14px;
font-weight: bold;
}
/* ========== 右侧玩家 ========== */
.right-player {
position: absolute;
right: 20px;
top: 50%;
transform: translateY(-50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
}
.right-player .card-count {
color: #ffd700;
font-size: 14px;
font-weight: bold;
}
/* ========== 牌背堆叠效果 ========== */
.card-stack {
position: relative;
width: 40px;
height: 56px;
}
.card-stack .card-small {
position: absolute;
top: 0;
left: 0;
}
.card-stack .card-small:nth-child(1) { transform: translate(0, 0); }
.card-stack .card-small:nth-child(2) { transform: translate(2px, -2px); }
.card-stack .card-small:nth-child(3) { transform: translate(4px, -4px); }
/* ========== 中央桌面区 ========== */
.table-area {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 400px;
height: 200px;
display: flex;
align-items: center;
justify-content: center;
}
.last-played {
text-align: center;
}
.played-by {
color: #ffd700;
font-size: 16px;
font-weight: bold;
margin-bottom: 15px;
text-shadow: 0 2px 4px rgba(0,0,0,0.5);
background: rgba(0,0,0,0.3);
padding: 5px 15px;
border-radius: 15px;
display: inline-block;
}
.played-cards {
display: flex;
justify-content: center;
gap: 5px;
min-height: 112px;
}
/* ========== 底部玩家自己 ========== */
.player-self {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 15px;
width: 100%;
max-width: 800px;
}
.self-info {
display: flex;
align-items: center;
gap: 15px;
}
/* 手牌区 */
.hand-cards {
display: flex;
justify-content: center;
gap: -30px;
padding: 20px;
min-height: 140px;
}
.hand-cards .card {
margin-left: -30px;
}
.hand-cards .card:first-child {
margin-left: 0;
}
/* ========== 按钮样式 ========== */
.action-buttons {
display: flex;
gap: 15px;
}
.btn {
padding: 10px 30px;
border: none;
border-radius: 25px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: all 0.2s;
box-shadow: 0 4px 8px rgba(0,0,0,0.3);
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(0,0,0,0.4);
}
.btn:active {
transform: translateY(0);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-secondary {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
.btn-hint {
background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
color: white;
}
/* 开始按钮 */
.btn-start {
padding: 15px 50px;
font-size: 20px;
background: linear-gradient(135deg, #ffd700 0%, #ff8c00 100%);
color: #333;
border: none;
border-radius: 30px;
font-weight: bold;
cursor: pointer;
box-shadow: 0 4px 15px rgba(255,215,0,0.4);
transition: all 0.2s;
}
.btn-start:hover {
transform: scale(1.05);
box-shadow: 0 6px 20px rgba(255,215,0,0.6);
}
/* ========== 游戏状态提示 ========== */
.game-status {
position: absolute;
top: 10px;
right: 10px;
color: #ffd700;
font-size: 14px;
font-weight: bold;
text-shadow: 0 2px 4px rgba(0,0,0,0.5);
pointer-events: none;
background: rgba(0,0,0,0.4);
padding: 5px 12px;
border-radius: 15px;
white-space: nowrap;
}
/* ========== 开始界面 ========== */
.start-screen {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
}
/* ========== 弹窗样式 ========== */
.call-lord-modal {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.modal-content {
background: linear-gradient(135deg, #1a3a5c 0%, #0d2847 100%);
padding: 30px 50px;
border-radius: 15px;
border: 2px solid #4a7ab8;
text-align: center;
}
.modal-content h3 {
color: white;
margin-bottom: 20px;
font-size: 20px;
}
.modal-buttons {
display: flex;
gap: 20px;
justify-content: center;
}
/* ========== 动画效果 ========== */
@keyframes dealCard {
0% {
opacity: 0;
transform: translateY(-100px) scale(0.5);
}
50% {
opacity: 1;
}
100% {
opacity: 1;
transform: translateY(0) scale(1);
}
}
@keyframes playCard {
0% {
transform: scale(1);
}
50% {
transform: scale(1.1) translateY(-20px);
}
100% {
transform: scale(1);
}
}
@keyframes bombShake {
0%, 100% { transform: translateX(0); }
10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
20%, 40%, 60%, 80% { transform: translateX(5px); }
}
.dealing .card {
animation: dealCard 0.3s ease-out;
}
.playing .card {
animation: playCard 0.3s ease-out;
}
.bomb-effect {
animation: bombShake 0.5s ease-in-out;
}
/* 出牌提示 */
.turn-indicator {
position: absolute;
width: 70px;
height: 70px;
border-radius: 50%;
border: 3px solid #ffd700;
box-shadow: 0 0 20px rgba(255, 215, 0, 0.5);
animation: pulse 1.5s infinite;
pointer-events: none;
}
@keyframes pulse {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.1); opacity: 0.7; }
}
/* ========== 计时器 ========== */
.timer {
position: absolute;
width: 40px;
height: 40px;
border-radius: 50%;
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a5a 100%);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
font-size: 16px;
box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}
/* ========== 聊天/提示气泡 ========== */
.chat-bubble {
position: absolute;
background: white;
padding: 8px 12px;
border-radius: 10px;
font-size: 14px;
color: #333;
box-shadow: 0 2px 8px rgba(0,0,0,0.2);
white-space: nowrap;
}
.chat-bubble::after {
content: '';
position: absolute;
bottom: -8px;
left: 50%;
transform: translateX(-50%);
border: 8px solid transparent;
border-top-color: white;
}
/* ========== 响应式适配 ========== */
@media (max-width: 768px) {
.card {
width: 60px;
height: 84px;
}
.card-small {
width: 30px;
height: 42px;
}
.avatar-img {
width: 50px;
height: 50px;
font-size: 14px;
}
.hand-cards .card {
margin-left: -20px;
}
.btn {
padding: 8px 20px;
font-size: 14px;
}
}
/* ========== 竖屏手机适配 ========== */
@media (max-width: 480px) and (orientation: portrait) {
.game-table {
min-width: 100vw;
min-height: 100vh;
}
/* 手牌区 - 更紧凑 */
.hand-cards {
padding: 10px 5px;
min-height: 100px;
max-width: 100vw;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
.hand-cards .card {
margin-left: -35px;
transform: scale(0.85);
}
.hand-cards .card:first-child {
margin-left: 5px;
}
.hand-cards .card:last-child {
margin-right: 10px;
}
/* 牌选中效果调整 */
.hand-cards .card.selected {
transform: scale(0.85) translateY(-15px);
}
/* 左右玩家位置调整 */
.left-player {
left: 5px;
}
.right-player {
right: 5px;
}
.left-player .avatar,
.right-player .avatar {
transform: scale(0.8);
}
/* 中央区域调整 */
.table-area {
width: 200px;
height: 150px;
}
.played-cards {
min-height: 80px;
}
.played-cards .card {
transform: scale(0.7);
}
/* 按钮调整 */
.action-buttons {
gap: 8px;
padding: 0 10px;
}
.btn {
padding: 8px 15px;
font-size: 13px;
border-radius: 20px;
}
/* 底牌区域调整 */
.deck-area {
top: 80px;
}
.deck-cards {
gap: 3px;
}
.deck-cards .card {
transform: scale(0.6);
}
/* 叫地主弹窗调整 */
.call-lord-modal .modal-content {
padding: 30px 20px;
width: 85%;
}
.call-lord-modal h2 {
font-size: 20px;
}
.call-lord-buttons {
gap: 15px;
}
.call-lord-buttons .btn {
padding: 12px 30px;
font-size: 16px;
}
}
/* ========== 横屏手机适配 ========== */
@media (max-height: 500px) and (orientation: landscape) {
.game-table {
min-height: 100vh;
transform: scale(0.9);
transform-origin: center top;
}
/* 顶部底牌区上移 */
.deck-area {
top: 5px;
}
.deck-cards .card {
transform: scale(0.5);
}
/* 左右玩家位置上移 */
.left-player, .right-player {
top: 30%;
}
.avatar-img {
width: 40px;
height: 40px;
font-size: 12px;
}
.player-name {
font-size: 10px;
}
.player-role {
font-size: 9px;
padding: 1px 5px;
}
/* 手牌区 - 整体下移 */
.player-self {
bottom: 35px;
max-width: 98%;
}
.self-info {
display: none;
}
.hand-cards {
padding: 2px;
min-height: 60px;
margin-bottom: 0;
}
/* 按钮下移,与牌保持间距 */
.action-buttons {
position: absolute;
bottom: -5px;
left: 50%;
transform: translateX(-50%);
gap: 10px;
margin: 0;
}
.hand-cards .card {
margin-left: -40px;
transform: scale(0.44);
}
.hand-cards .card.selected {
transform: scale(0.44) translateY(-6px);
}
/* 按钮 */
.action-buttons {
gap: 8px;
margin-top: 5px;
}
.btn {
padding: 5px 15px;
font-size: 12px;
}
/* 中央区域 - 居中显示 */
.table-area {
width: 200px;
height: 100px;
top: 50%;
transform: translate(-50%, -50%);
}
.played-cards {
min-height: 50px;
}
.played-cards .card {
transform: scale(0.5);
}
.played-by {
font-size: 11px;
margin-bottom: 5px;
padding: 4px 12px;
}
.last-played {
margin-top: 10px;
}
.game-status {
font-size: 11px;
top: 5px;
left: 50%;
transform: translateX(-50%);
padding: 3px 8px;
}
/* 叫地主弹窗 */
.call-lord-modal {
align-items: center;
}
/* 底牌区域居中偏上 */
.deck-area {
top: 35px;
left: 50%;
transform: translateX(-50%);
}
.deck-label {
font-size: 9px;
}
.deck-cards .card {
transform: scale(0.4);
}
}
+630
View File
@@ -0,0 +1,630 @@
/**
* 斗地主UI控制器
* 连接游戏逻辑和界面
*/
let game = null;
let userScore = 0; // 当前用户积分
// ========== 用户积分相关 ==========
const GAME_ID = 'doudizhu';
const API_BASE = ''; // 同域,相对路径
// 获取用户积分
async function loadUserScore() {
try {
const response = await fetch(`${API_BASE}/api/user/score/${GAME_ID}`, {
credentials: 'include'
});
if (response.status === 401) {
// 未登录,显示提示
document.getElementById('userName').textContent = '未登录';
document.getElementById('scoreValue').textContent = '-';
return;
}
const data = await response.json();
if (data.score !== undefined) {
userScore = data.score;
document.getElementById('scoreValue').textContent = userScore;
}
} catch (error) {
console.error('获取积分失败:', error);
document.getElementById('scoreValue').textContent = '-';
}
}
// 获取用户名
async function loadUserInfo() {
try {
const response = await fetch(`${API_BASE}/api/auth/status`, {
credentials: 'include'
});
const data = await response.json();
if (data.authenticated && data.user) {
document.getElementById('userName').textContent = data.user.username;
} else {
document.getElementById('userName').textContent = '游客';
}
} catch (error) {
document.getElementById('userName').textContent = '游客';
}
}
// 提交游戏积分
async function submitScore(points) {
if (points <= 0) return;
try {
const response = await fetch(`${API_BASE}/api/user/score`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({
game: GAME_ID,
points: points
})
});
if (response.ok) {
const data = await response.json();
if (data.success) {
userScore = data.score;
document.getElementById('scoreValue').textContent = userScore;
// 显示获得积分动画
showScoreAnimation(points);
}
}
} catch (error) {
console.error('提交积分失败:', error);
}
}
// 显示获得积分动画
function showScoreAnimation(points) {
const scoreEl = document.getElementById('scoreValue');
const anim = document.createElement('div');
anim.textContent = `+${points}`;
anim.style.cssText = `
position: fixed;
top: 40px;
right: 20px;
color: #ffd700;
font-size: 24px;
font-weight: bold;
text-shadow: 0 0 20px rgba(255, 215, 0, 0.8);
pointer-events: none;
z-index: 1001;
animation: scoreFloat 1.5s ease-out forwards;
`;
document.body.appendChild(anim);
// 高亮分数
scoreEl.style.transform = 'scale(1.3)';
scoreEl.style.transition = 'transform 0.3s';
setTimeout(() => {
scoreEl.style.transform = 'scale(1)';
}, 300);
setTimeout(() => anim.remove(), 1500);
}
// 添加分数浮动动画
const style = document.createElement('style');
style.textContent = `
@keyframes scoreFloat {
0% { opacity: 1; transform: translateY(0) scale(1); }
100% { opacity: 0; transform: translateY(-30px) scale(1.2); }
}
`;
document.head.appendChild(style);
// ========== 牌的HTML渲染 ==========
function createCardHTML(card, selectable = true) {
if (!card) return '';
if (card.isJoker) {
const color = card.rank === '大王' ? '#e74c3c' : '#3498db';
return `
<div class="card joker" data-id="${card.id}" ${selectable ? 'onclick="toggleSelect(this)"' : ''}>
<div class="card-top" style="color:${color};font-size:12px;">${card.rank}</div>
<div class="card-center" style="font-size:32px;color:${color};">🃏</div>
<div class="card-bottom" style="color:${color};font-size:12px;transform:rotate(180deg);">${card.rank}</div>
</div>
`;
}
const isRed = card.suit === '♥' || card.suit === '♦';
const color = isRed ? '#e74c3c' : '#2c3e50';
return `
<div class="card" data-id="${card.id}" data-rank="${card.rank}" data-suit="${card.suit}" ${selectable ? 'onclick="toggleSelect(this)"' : ''}>
<div class="card-top" style="color:${color};font-size:14px;line-height:1.2;">${card.rank}<br>${card.suit}</div>
<div class="card-center" style="color:${color};font-size:40px;">${card.suit}</div>
<div class="card-bottom" style="color:${color};font-size:14px;line-height:1.2;transform:rotate(180deg);">${card.rank}<br>${card.suit}</div>
</div>
`;
}
function createCardBackHTML() {
return '<div class="card back"></div>';
}
// ========== 选牌交互 ==========
function toggleSelect(cardEl) {
if (game && game.currentPlayer !== 0) return; // 不是玩家回合不能选
cardEl.classList.toggle('selected');
updateActionButtons();
}
function updateActionButtons() {
const selected = document.querySelectorAll('.hand-cards .card.selected');
const hasSelection = selected.length > 0;
const isPlayerTurn = game && game.currentPlayer === 0 && game.gamePhase === 'playing';
document.getElementById('btn-play').disabled = !hasSelection || !isPlayerTurn;
document.getElementById('btn-pass').disabled = !isPlayerTurn;
document.getElementById('btn-hint').disabled = !isPlayerTurn;
}
// ========== 游戏流程控制 ==========
function startGame() {
document.getElementById('start-screen').style.display = 'none';
game = new DoudizhuGame();
game.init();
// 发牌动画
document.getElementById('game-status').textContent = '正在发牌...';
animateDeal();
}
function animateDeal() {
const handContainer = document.getElementById('hand-cards');
handContainer.innerHTML = '';
handContainer.classList.add('dealing');
// 先快速发完(动画效果)
let cardIndex = 0;
const dealInterval = setInterval(() => {
const playerIndex = cardIndex % 3;
if (playerIndex === 0) {
// 玩家显示背面
const cardEl = document.createElement('div');
cardEl.innerHTML = createCardBackHTML();
handContainer.appendChild(cardEl.firstElementChild);
}
updateAICardCounts();
cardIndex++;
if (cardIndex >= 51) {
clearInterval(dealInterval);
handContainer.classList.remove('dealing');
// 真正发牌
const result = game.deal();
// 显示底牌
showBottomCardsBack();
// 显示玩家手牌
renderPlayerCards();
// 进入叫地主
setTimeout(() => {
showCallLordModal();
}, 500);
}
}, 30);
}
function renderPlayerCards() {
const container = document.getElementById('hand-cards');
container.innerHTML = '';
const playerCards = game.players[0].cards;
playerCards.forEach(card => {
const div = document.createElement('div');
div.innerHTML = createCardHTML(card, true);
container.appendChild(div.firstElementChild);
});
}
function updateAICardCounts() {
document.querySelector('.left-player .card-count').textContent =
game ? game.players[1].cards.length + '张' : '17张';
document.querySelector('.right-player .card-count').textContent =
game ? game.players[2].cards.length + '张' : '17张';
}
function showBottomCardsBack() {
const deckArea = document.querySelector('.deck-cards');
deckArea.innerHTML = '';
for (let i = 0; i < 3; i++) {
deckArea.innerHTML += createCardBackHTML();
}
}
function showBottomCardsFront(cards) {
const deckArea = document.querySelector('.deck-cards');
deckArea.innerHTML = '';
cards.forEach(card => {
const div = document.createElement('div');
div.innerHTML = createCardHTML(card, false);
deckArea.appendChild(div.firstElementChild);
});
}
// ========== 叫地主 ==========
function showCallLordModal() {
document.getElementById('call-lord-modal').style.display = 'flex';
document.getElementById('game-status').textContent = '轮到你了:是否叫地主?';
}
function callLord(want) {
document.getElementById('call-lord-modal').style.display = 'none';
const result = game.callLord(0, want);
if (result.success) {
becomeLord(0);
} else {
// AI叫地主
aiCallLordProcess();
}
}
function becomeLord(playerId) {
const player = game.players[playerId];
// 显示底牌
showBottomCardsFront(game.bottomCards);
// 更新角色显示
updateRoleDisplay();
// 如果是玩家,更新手牌
if (playerId === 0) {
renderPlayerCards();
document.getElementById('game-status').textContent = '你是地主,请出牌';
updateActionButtons();
} else {
document.getElementById('game-status').textContent = player.name + '是地主,游戏开始';
setTimeout(() => aiTurn(), 1500);
}
}
function updateRoleDisplay() {
game.players.forEach(p => {
const roleEl = document.getElementById(p.id === 0 ? 'my-role' :
(p.id === 1 ? 'left-role' : 'right-role'));
if (roleEl) {
roleEl.textContent = p.isLord ? '地主' : '农民';
}
});
}
function aiCallLordProcess() {
document.getElementById('game-status').textContent = '等待其他玩家...';
setTimeout(() => {
// AI1叫地主
if (game.players[1].ai.wantToBeLord(game.players[1].cards)) {
game.callLord(1, true);
becomeLord(1);
return;
}
// AI2叫地主
setTimeout(() => {
if (game.players[2].ai.wantToBeLord(game.players[2].cards)) {
game.callLord(2, true);
becomeLord(2);
return;
}
// 都没叫,玩家默认当地主
game.callLord(0, true);
becomeLord(0);
}, 1000);
}, 1000);
}
// ========== 出牌逻辑 ==========
function playCards() {
const selected = document.querySelectorAll('.hand-cards .card.selected');
if (selected.length === 0) return;
const cardIds = Array.from(selected).map(el => parseInt(el.dataset.id));
const cards = game.players[0].cards.filter(c => cardIds.includes(c.id));
const result = game.playCards(0, cards);
if (!result.success) {
showToast(result.error);
return;
}
// 更新UI
executePlayUI(0, cards, result.cardType);
if (result.gameOver) {
endGame(0);
return;
}
// AI回合
setTimeout(() => aiTurn(), 1000);
}
function passTurn() {
// 先取消所有选中的牌(让牌回归原位)
document.querySelectorAll('.hand-cards .card.selected').forEach(card => {
card.classList.remove('selected');
});
updateActionButtons();
const result = game.pass(0);
showPlayedCards([], 0, '不出');
if (result.clearDesktop) {
clearDesktop();
}
setTimeout(() => aiTurn(), 1000);
}
function executePlayUI(playerId, cards, cardType) {
// 从手牌移除
if (playerId === 0) {
renderPlayerCards();
}
// 显示到桌面
const typeName = cardType ? cardType.name : '出牌';
showPlayedCards(cards, playerId, typeName);
// 更新AI牌数
updateAICardCounts();
// 取消选中
updateActionButtons();
}
function showPlayedCards(cards, playerId, actionName) {
const container = document.querySelector('.played-cards');
const playerName = game.players[playerId].name;
const playerRole = game.players[playerId].isLord ? '【地主】' : '【农民】';
// 如果是"不出",只更新文字,不清空牌(保留上一轮出的牌)
if (cards.length === 0) {
document.querySelector('.played-by').textContent = `${playerName}${playerRole}: 不出`;
document.getElementById('game-status').textContent = `${playerName}选择不出`;
return;
}
// 有牌出,更新牌显示
container.innerHTML = '';
container.classList.add('playing');
cards.forEach(card => {
const div = document.createElement('div');
div.innerHTML = createCardHTML(card, false);
container.appendChild(div.firstElementChild);
});
// 显示出牌者 + 牌型
document.querySelector('.played-by').textContent = `${playerName}${playerRole}: ${actionName}`;
document.getElementById('game-status').textContent = `${playerName}出了 ${actionName}`;
setTimeout(() => container.classList.remove('playing'), 300);
}
function clearDesktop() {
setTimeout(() => {
document.querySelector('.played-cards').innerHTML = '';
document.querySelector('.played-by').textContent = '新一轮出牌';
game.desktopCards = null;
}, 1000);
}
// ========== AI回合 ==========
function aiTurn() {
if (!game || game.gamePhase !== 'playing') return;
const currentId = game.currentPlayer;
if (currentId === 0) {
document.getElementById('game-status').textContent = '轮到你了';
updateActionButtons();
return;
}
const player = game.players[currentId];
document.getElementById('game-status').textContent = player.name + '正在思考...';
setTimeout(() => {
const result = game.aiPlay();
if (result.success) {
if (result.cardType) {
// AI出了牌
executePlayUI(currentId, result.cardType.cards, result.cardType);
} else {
// AI选择不出
showPlayedCards([], currentId, '不出');
}
if (result.clearDesktop) {
clearDesktop();
}
if (result.gameOver) {
endGame(result.winner);
return;
}
// 继续下一个
setTimeout(() => aiTurn(), 1500);
}
}, 1500);
}
// ========== 提示功能 ==========
function showHint() {
if (!game || game.currentPlayer !== 0) return;
const cards = game.players[0].cards;
if (cards.length === 0) return;
// 取消之前的选中
document.querySelectorAll('.hand-cards .card.selected').forEach(c => c.classList.remove('selected'));
// 找出一个合法的出牌
const ai = new DoudizhuAI(0);
const validPlays = ai.findAllValidPlays(cards, game.desktopCards);
if (validPlays.length > 0) {
// 选最小的
validPlays.sort((a, b) => a.type.value - b.type.value);
const hintCards = validPlays[0].cards;
hintCards.forEach(card => {
const cardEl = document.querySelector(`.hand-cards .card[data-id="${card.id}"]`);
if (cardEl) cardEl.classList.add('selected');
});
updateActionButtons();
showToast('提示: ' + validPlays[0].type.name);
} else {
showToast('没有可出的牌,建议不出');
}
}
// ========== 游戏结束 ==========
function endGame(winnerId) {
const winner = game.players[winnerId];
const isPlayerWin = winnerId === 0;
const isLordWin = winner.isLord;
let message;
let earnedPoints = 0;
if (isPlayerWin) {
// 玩家获胜,计算积分
earnedPoints = isLordWin ? 3 : 1;
const roleName = isLordWin ? '地主' : '农民';
message = `恭喜你,${roleName}获胜!\n获得 ${earnedPoints} 积分`;
// 提交积分
submitScore(earnedPoints);
} else {
message = isLordWin ? `${winner.name}(地主)获胜!` : '农民获胜!\n你输了';
}
document.getElementById('game-status').textContent = message.replace('\n', ' ');
setTimeout(() => {
if (confirm(message + '\n\n是否重新开始?')) {
location.reload();
}
}, 800);
}
// ========== 工具函数 ==========
function showToast(message) {
// 简单的提示
const status = document.getElementById('game-status');
const oldText = status.textContent;
status.textContent = message;
setTimeout(() => {
status.textContent = oldText;
}, 2000);
}
// ========== 登录检查 ==========
async function checkLogin() {
try {
const response = await fetch('/api/auth/status', {
credentials: 'include'
});
const data = await response.json();
if (!data.authenticated) {
// 未登录,显示遮罩
showLoginRequired();
return false;
}
return true;
} catch (error) {
showLoginRequired();
return false;
}
}
function showLoginRequired() {
// 创建登录提示遮罩
const overlay = document.createElement('div');
overlay.id = 'login-required-overlay';
overlay.innerHTML = `
<div style="
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.85);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
backdrop-filter: blur(8px);
">
<div style="
background: linear-gradient(145deg, #1e293b 0%, #0f172a 100%);
padding: 40px;
border-radius: 16px;
text-align: center;
max-width: 320px;
border: 1px solid rgba(255, 215, 0, 0.3);
">
<div style="font-size: 48px; margin-bottom: 16px;">🔒</div>
<div style="font-size: 20px; font-weight: bold; color: #fff; margin-bottom: 8px;">请先登录</div>
<div style="font-size: 14px; color: #888; margin-bottom: 24px;">登录后才能游玩斗地主</div>
<button onclick="location.href='/'" style="
padding: 12px 32px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
">去登录</button>
</div>
</div>
`;
document.body.appendChild(overlay);
}
// ========== 事件绑定 ==========
document.addEventListener('DOMContentLoaded', async function() {
// 先检查登录
const isLoggedIn = await checkLogin();
if (!isLoggedIn) return;
// 加载用户信息和积分
loadUserInfo();
loadUserScore();
document.getElementById('btn-start').addEventListener('click', startGame);
document.getElementById('btn-call-yes').addEventListener('click', () => callLord(true));
document.getElementById('btn-call-no').addEventListener('click', () => callLord(false));
document.getElementById('btn-play').addEventListener('click', playCards);
document.getElementById('btn-pass').addEventListener('click', passTurn);
document.getElementById('btn-hint').addEventListener('click', showHint);
});