好的,我们来创建一个使用 HTML、CSS 和 JavaScript 实现的 Solitaire (Klondike Turn 1) 游戏。
游戏将包含以下区域:
- 牌堆 (Deck): 左上角,抽取新牌。
- 废牌堆 (Waste): 牌堆右边,存放抽出的牌。
- 地基区 (Foundations - 4个): 废牌堆右边,按花色从 A 到 K 收集牌。
- 排版区 (Tableau - 7列): 游戏下方,构建主游戏区。
我们将使用 emoji (♥ ♦ ♣ ♠) 和颜色 (红色/黑色) 来表示花色和颜色,不使用图片。所有代码将在一个 HTML 文件中。
HTML 结构 (index.html)
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Solitaire (Turn 1)</title>
<style>
body {
font-family: sans-serif;
background-color: #228B22; /* Forest Green background */
margin: 0;
padding: 20px;
display: flex;
flex-direction: column;
align-items: center;
}
.game-area {
display: grid;
grid-template-areas:
"deck waste . foundation1 foundation2 foundation3 foundation4"
"tableau1 tableau2 tableau3 tableau4 tableau5 tableau6 tableau7";
gap: 15px;
max-width: 900px; /* Limit width for better layout */
width: 100%;
}
.deck-area { grid-area: deck; }
.waste-area { grid-area: waste; }
.foundation-area.f1 { grid-area: foundation1; }
.foundation-area.f2 { grid-area: foundation2; }
.foundation-area.f3 { grid-area: foundation3; }
.foundation-area.f4 { grid-area: foundation4; }
.tableau-area.t1 { grid-area: tableau1; }
.tableau-area.t2 { grid-area: tableau2; }
.tableau-area.t3 { grid-area: tableau3; }
.tableau-area.t4 { grid-area: tableau4; }
.tableau-area.t5 { grid-area: tableau5; }
.tableau-area.t6 { grid-area: tableau6; }
.tableau-area.t7 { grid-area: tableau7; }
/* Generic pile/area styling */
.pile, .foundation-area, .tableau-area {
border: 2px dashed rgba(255, 255, 255, 0.3);
border-radius: 5px;
min-width: 70px; /* Card width */
min-height: 100px; /* Card height */
position: relative; /* For positioning cards inside */
box-sizing: border-box;
}
.foundation-area, .tableau-area {
/* Allow dropping */
min-height: 120px; /* Make tableau columns taller */
}
.deck-area .card.face-down {
/* Position the deck cards slightly offset */
position: absolute;
top: 0;
left: 0;
/* Will be adjusted by JS for visual stack */
}
.waste-area .card {
position: absolute;
top: 0;
left: 0;
/* Will be adjusted by JS for visual stack */
}
/* Card Styling */
.card {
width: 70px;
height: 100px;
border: 1px solid #333;
border-radius: 5px;
background-color: #fff;
position: absolute; /* For positioning within piles/tableau */
box-sizing: border-box;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 5px;
font-size: 18px;
cursor: pointer;
transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out;
z-index: 1; /* Default z-index */
user-select: none; /* Prevent selecting text inside card */
}
.card .rank, .card .suit {
line-height: 1; /* Better vertical alignment */
}
.card .rank.bottom, .card .suit.bottom {
align-self: flex-end; /* Position at bottom right */
transform: rotate(180deg); /* Rotate for bottom */
}
.card.red {
color: red;
}
.card.black {
color: black;
}
.card.face-down {
background-color: #8B4513; /* SaddleBrown */
border-color: #5a2d0c;
color: transparent; /* Hide content */
justify-content: center;
align-items: center;
font-size: 30px;
}
.card.face-down::before {
content: '?'; /* Optional: A symbol on the back */
color: rgba(255, 255, 255, 0.5);
}
/* Dragging styles */
.card.dragging {
z-index: 1000; /* Bring to front */
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.5);
transform: scale(1.05); /* Slightly larger */
transition: none; /* No transition while dragging */
}
/* Offset for stacked cards in tableau */
.tableau-area .card {
position: absolute; /* Enable offset stacking */
left: 0;
/* 'top' will be set by JS */
}
/* Offset for cards dragged in a stack */
.card.dragging .card-stack-offset {
position: absolute;
left: 0;
/* 'top' will be set relative to the dragged card by JS */
}
.message {
margin-top: 20px;
color: white;
font-size: 1.2em;
}
.win-message {
color: gold;
font-size: 2em;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Solitaire (Turn 1)</h1>
<div class="game-area" id="gameArea">
<div class="pile deck-area" id="deckArea"></div>
<div class="pile waste-area" id="wasteArea"></div>
<div class="pile foundation-area f1" id="foundationArea-H"></div>
<div class="pile foundation-area f2" id="foundationArea-D"></div>
<div class="pile foundation-area f3" id="foundationArea-C"></div>
<div class="pile foundation-area f4" id="foundationArea-S"></div>
<div class="pile tableau-area t1" id="tableauArea-0"></div>
<div class="pile tableau-area t2" id="tableauArea-1"></div>
<div class="pile tableau-area t3" id="tableauArea-2"></div>
<div class="pile tableau-area t4" id="tableauArea-3"></div>
<div class="pile tableau-area t5" id="tableauArea-4"></div>
<div class="pile tableau-area t6" id="tableauArea-5"></div>
<div class="pile tableau-area t7" id="tableauArea-6"></div>
</div>
<div class="message" id="gameMessage"></div>
<script>
// --- Game State ---
const suits = ['H', 'D', 'C', 'S']; // Hearts, Diamonds, Clubs, Spades
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const colors = { H: 'red', D: 'red', C: 'black', S: 'black' };
const suitEmojis = { H: '♥', D: '♦', C: '♣', S: '♠' };
let deck = [];
let waste = [];
let foundations = { H: [], D: [], C: [], S: [] };
let tableau = [[], [], [], [], [], [], []]; // 7 columns
// --- DOM Elements ---
const deckEl = document.getElementById('deckArea');
const wasteEl = document.getElementById('wasteArea');
const foundationEls = {
H: document.getElementById('foundationArea-H'),
D: document.getElementById('foundationArea-D'),
C: document.getElementById('foundationArea-C'),
S: document.getElementById('foundationArea-S')
};
const tableauEls = Array.from({ length: 7 }, (_, i) => document.getElementById(`tableauArea-${i}`));
const gameMessageEl = document.getElementById('gameMessage');
// --- Card Creation and Rendering ---
let cardIdCounter = 0; // Simple unique ID for cards
function createDeck() {
deck = [];
for (const suit of suits) {
for (let i = 0; i < ranks.length; i++) {
deck.push({
id: cardIdCounter++,
rank: ranks[i],
suit: suit,
color: colors[suit],
isFaceUp: false,
// Optional: store initial position/state if needed later
});
}
}
}
function shuffleDeck(deckArray) {
for (let i = deckArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[deckArray[i], deckArray[j]] = [deckArray[j], deckArray[i]]; // Swap
}
}
function createCardElement(card) {
const cardEl = document.createElement('div');
cardEl.classList.add('card');
cardEl.dataset.id = card.id;
cardEl.dataset.rank = card.rank;
cardEl.dataset.suit = card.suit;
cardEl.dataset.color = card.color;
updateCardElement(cardEl, card); // Set initial face up/down state
return cardEl;
}
function updateCardElement(cardEl, card) {
cardEl.dataset.isFaceUp = card.isFaceUp;
if (card.isFaceUp) {
cardEl.classList.remove('face-down');
cardEl.classList.add(card.color);
cardEl.innerHTML = `
<div class="rank">${card.rank}</div>
<div class="suit">${suitEmojis[card.suit]}</div>
<div class="rank bottom">${card.rank}</div>
<div class="suit bottom">${suitEmojis[card.suit]}</div>
`;
} else {
cardEl.classList.add('face-down');
cardEl.classList.remove('red', 'black');
cardEl.innerHTML = ''; // Hide content when face down
}
}
function renderGame() {
// Clear existing cards
deckEl.innerHTML = '';
wasteEl.innerHTML = '';
Object.values(foundationEls).forEach(el => el.innerHTML = '');
tableauEls.forEach(el => el.innerHTML = '');
// Render Deck
deck.forEach((card, index) => {
const cardEl = createCardElement(card);
// Position deck cards slightly for visual stack
cardEl.style.position = 'absolute';
// Simple visual stack: top, left offset
const offset = index * 0.5; // Small offset
cardEl.style.top = `${offset}px`;
cardEl.style.left = `${offset}px`;
// Ensure only the top card is fully visible/clickable in reality,
// but visually render all for effect.
// For interactions, we'll only target the actual top card.
cardEl.style.zIndex = index; // Stack visually
deckEl.appendChild(cardEl);
});
// Make only the *visual* top card interactive
if (deckEl.lastChild) {
deckEl.lastChild.style.pointerEvents = 'auto';
// The actual clickable area for drawing is the pile itself
} else {
// Indicate empty deck visually if needed
}
// Render Waste
waste.forEach((card, index) => {
const cardEl = createCardElement(card);
// Position waste cards slightly for visual stack (optional, often just show top)
const offset = index * 0.5; // Small offset
cardEl.style.top = `${offset}px`;
cardEl.style.left = `${offset}px`;
cardEl.style.zIndex = index;
wasteEl.appendChild(cardEl);
// Only the top card is interactive
cardEl.style.pointerEvents = 'none'; // Disable interaction for cards under the top one
});
if (wasteEl.lastChild) {
wasteEl.lastChild.style.pointerEvents = 'auto'; // Enable interaction for the top card
}
// Render Foundations
for (const suit in foundations) {
const foundationAreaEl = foundationEls[suit];
foundations[suit].forEach(card => {
const cardEl = createCardElement(card);
// Position at 0,0 in foundation
cardEl.style.top = '0px';
cardEl.style.left = '0px';
// Z-index not strictly needed if only top is interactive
foundationAreaEl.appendChild(cardEl);
});
}
// Render Tableau
tableau.forEach((column, colIndex) => {
const tableauAreaEl = tableauEls[colIndex];
column.forEach((card, cardIndex) => {
const cardEl = createCardElement(card);
// Stack cards with vertical offset
const offset = cardIndex * 20; // Pixels offset for each card
cardEl.style.top = `${offset}px`;
cardEl.style.left = '0px';
cardEl.style.zIndex = cardIndex; // Ensure correct stacking order
tableauAreaEl.appendChild(cardEl);
// Ensure only the last card in the column (if face up) is directly interactive for dragging
if (cardIndex < column.length - 1 || !card.isFaceUp) {
cardEl.style.pointerEvents = 'none';
} else {
cardEl.style.pointerEvents = 'auto';
}
});
});
}
function dealInitial() {
createDeck();
shuffleDeck(deck);
// Deal to tableau
for (let i = 0; i < 7; i++) { // For each column
for (let j = 0; j <= i; j++) { // Deal i+1 cards
const card = deck.pop();
if (j === i) { // Last card is face up
card.isFaceUp = true;
}
tableau[i].push(card);
}
}
// The rest remain in the deck (face down by default)
}
// --- Game Logic Helper Functions ---
function getCardElement(cardId) {
return document.querySelector(`.card[data-id="${cardId}"]`);
}
function getCardData(cardEl) {
const cardId = parseInt(cardEl.dataset.id);
// Find the card object in the state arrays
const findCard = (arr) => arr.find(c => c.id === cardId);
let card = findCard(deck);
if (card) return { card, location: 'deck' };
card = findCard(waste);
if (card) return { card, location: 'waste' };
for (const suit in foundations) {
card = findCard(foundations[suit]);
if (card) return { card, location: 'foundation', suit: suit };
}
for (let i = 0; i < tableau.length; i++) {
card = findCard(tableau[i]);
if (card) return { card, location: 'tableau', column: i, index: tableau[i].indexOf(card) };
}
return null; // Card not found (shouldn't happen if element exists)
}
function isValidTableauMove(draggedStack, targetColumn) {
const topDraggedCard = draggedStack[0];
const targetCards = tableau[targetColumn];
const targetTopCard = targetCards.length > 0 ? targetCards[targetCards.length - 1] : null;
// Rule 1: Empty column only accepts a King
if (!targetTopCard) {
return topDraggedCard.rank === 'K';
}
// Rule 2: Must be one rank lower and opposite color
const targetRankIndex = ranks.indexOf(targetTopCard.rank);
const draggedRankIndex = ranks.indexOf(topDraggedCard.rank);
return draggedRankIndex === targetRankIndex - 1 &&
topDraggedCard.color !== targetTopCard.color;
}
function isValidFoundationMove(card, targetSuit) {
const foundation = foundations[targetSuit];
const topFoundationCard = foundation.length > 0 ? foundation[foundation.length - 1] : null;
// Rule 1: Empty foundation only accepts an Ace of the correct suit
if (!topFoundationCard) {
return card.rank === 'A' && card.suit === targetSuit;
}
// Rule 2: Must be the same suit and one rank higher
const topRankIndex = ranks.indexOf(topFoundationCard.rank);
const cardRankIndex = ranks.indexOf(card.rank);
return card.suit === targetSuit && cardRankIndex === topRankIndex + 1;
}
// Helper to find a valid auto-move target
function findAutoMoveTarget(card) {
if (!card.isFaceUp) return null; // Can only auto-move face-up cards
// Try Foundations first
for (const suit in foundations) {
if (isValidFoundationMove(card, suit)) {
return { type: 'foundation', suit: suit };
}
}
// Try Tableau columns
for (let i = 0; i < tableau.length; i++) {
// Need to check if this *single* card is a valid start of a stack or a single card move
// isValidTableauMove expects a stack, but for single card, stack is just [card]
if (isValidTableauMove([card], i)) {
return { type: 'tableau', column: i };
}
}
return null; // No valid target found
}
function moveCard(card, currentLocation, targetLocation, targetInfo) {
let cardToMove; // The single card being moved (or the top of a stack)
let sourceArray;
let stackToMove = []; // For tableau to tableau moves
// Find the source array and card(s)
if (currentLocation.location === 'waste') {
sourceArray = waste;
cardToMove = waste[waste.length - 1]; // Only the top card is movable
if (cardToMove.id !== card.id) return false; // Not the top card
stackToMove = [cardToMove];
} else if (currentLocation.location === 'tableau') {
sourceArray = tableau[currentLocation.column];
// Find the card and everything stacked on top of it
const startIndex = sourceArray.findIndex(c => c.id === card.id);
if (startIndex === -1 || !sourceArray[startIndex].isFaceUp) return false; // Card not found or face down
stackToMove = sourceArray.slice(startIndex); // Get card and stack above it
cardToMove = stackToMove[0];
// Basic check: can only drag from tableau if it's the last card or a face-up stack
if (currentLocation.index !== sourceArray.length - stackToMove.length) return false; // Card is not the start of a valid draggable stack
} else {
return false; // Cannot move from deck or foundation (foundations can't be dragged *from* in standard solitaire)
}
// Validate the move based on the target
let isValid = false;
if (targetLocation === 'foundation') {
if (stackToMove.length === 1) { // Only single cards to foundation
isValid = isValidFoundationMove(cardToMove, targetInfo.suit);
}
} else if (targetLocation === 'tableau') {
isValid = isValidTableauMove(stackToMove, targetInfo.column);
}
if (isValid) {
// Perform the move
if (currentLocation.location === 'waste') {
waste.pop(); // Remove from waste
} else if (currentLocation.location === 'tableau') {
// Remove stack from tableau column
tableau[currentLocation.column].splice(currentLocation.index);
// Flip face-down card if necessary
if (tableau[currentLocation.column].length > 0) {
const topCardAfterMove = tableau[currentLocation.column][tableau[currentLocation.column].length - 1];
if (!topCardAfterMove.isFaceUp) {
topCardAfterMove.isFaceUp = true;
// Update the element immediately
const topCardEl = getCardElement(topCardAfterMove.id);
if(topCardEl) updateCardElement(topCardEl, topCardAfterMove);
}
}
}
if (targetLocation === 'foundation') {
foundations[targetInfo.suit].push(cardToMove); // Add to foundation
} else if (targetLocation === 'tableau') {
// Add stack to tableau column
tableau[targetInfo.column].push(...stackToMove);
}
// Re-render relevant parts or the whole game for simplicity
renderGame();
checkWinCondition();
return true; // Move successful
}
return false; // Move failed
}
function checkWinCondition() {
// Win if all foundations have 13 cards (A to K)
const totalFoundationCards = Object.values(foundations).reduce((sum, pile) => sum + pile.length, 0);
if (totalFoundationCards === 52) {
gameMessageEl.textContent = "恭喜!你赢了!🎉";
gameMessageEl.classList.add('win-message');
// Disable further interaction? Or add a "Play Again" button?
// For now, just display the message.
} else {
gameMessageEl.textContent = ""; // Clear message if not winning
gameMessageEl.classList.remove('win-message');
}
}
// --- Event Handling: Drawing from Deck ---
deckEl.addEventListener('click', () => {
if (deck.length > 0) {
const card = deck.pop();
card.isFaceUp = true;
waste.push(card);
} else if (waste.length > 0) {
// Move waste back to deck (Turn 1 rules: move all back face down)
while (waste.length > 0) {
const card = waste.pop();
card.isFaceUp = false;
deck.push(card);
}
// No need to shuffle waste back to deck in standard Turn 1
}
renderGame();
});
// --- Event Handling: Drag and Drop ---
let draggingCardEl = null;
let dragOffsetX, dragOffsetY;
let draggedStackEls = []; // Elements being dragged
let draggedStackData = []; // Card data for the stack
document.addEventListener('mousedown', (e) => {
// Start drag only if it's a card and left click
if (e.target.closest('.card') && e.button === 0) {
const cardEl = e.target.closest('.card');
const cardDataInfo = getCardData(cardEl);
if (!cardDataInfo) return; // Should not happen
const card = cardDataInfo.card;
const location = cardDataInfo.location;
let stackToDrag = [];
let stackElsToDrag = [];
// Determine if the card/stack is draggable
if (location === 'waste' && cardDataInfo.index === waste.length - 1 && card.isFaceUp) {
// Can drag the top of the waste pile
stackToDrag = [card];
stackElsToDrag = [cardEl];
} else if (location === 'tableau' && card.isFaceUp) {
// Can drag a face-up card and any face-up stack on top of it
const column = tableau[cardDataInfo.column];
const startIndex = cardDataInfo.index;
// Check if all cards from startIndex onwards are face up
let canDragStack = true;
for(let i = startIndex; i < column.length; i++) {
if (!column[i].isFaceUp) {
canDragStack = false;
break;
}
}
if (canDragStack) {
stackToDrag = column.slice(startIndex);
stackElsToDrag = tableauEls[cardDataInfo.column].querySelectorAll('.card');
stackElsToDrag = Array.from(stackElsToDrag).filter(el => {
const elCardData = getCardData(el);
return elCardData && elCardData.location === 'tableau' && elCardData.column === cardDataInfo.column && elCardData.index >= startIndex;
});
}
} else {
// Card is face down or not in a draggable location (deck, foundation)
return;
}
if (stackToDrag.length > 0) {
draggingCardEl = cardEl; // The specific element clicked to start drag
draggedStackEls = stackElsToDrag;
draggedStackData = stackToDrag; // Keep track of the actual card data
// Calculate initial offset
const rect = cardEl.getBoundingClientRect();
dragOffsetX = e.clientX - rect.left;
dragOffsetY = e.clientY - rect.top;
// Prepare elements for dragging
draggedStackEls.forEach((el, index) => {
el.classList.add('dragging');
// Set position to absolute and calculate initial offset relative to the *document*
const elRect = el.getBoundingClientRect();
el.style.position = 'fixed'; // Use fixed to drag relative to viewport
el.style.left = `${elRect.left}px`;
el.style.top = `${elRect.top}px`;
el.style.zIndex = 1000 + index; // Ensure correct stacking during drag
// Remove from original parent temporarily (visually, DOM is still there)
// We update the DOM structure only on successful drop.
// For visual purposes, we just reposition the elements.
// A more complex approach might involve cloning or moving to a temporary parent.
// Let's rely on 'fixed' positioning and z-index for now.
});
// Prevent default drag behavior
e.preventDefault();
}
}
});
document.addEventListener('mousemove', (e) => {
if (draggingCardEl) {
// Update position of the whole stack
draggedStackEls.forEach((el, index) => {
// Position relative to the mouse, maintaining the initial offset for the primary card
// and relative stacking offset for the rest of the stack.
const newX = e.clientX - dragOffsetX;
const newY = e.clientY - dragOffsetY + (index * 20); // Maintain stacking offset visually
el.style.left = `${newX}px`;
el.style.top = `${newY}px`;
});
e.preventDefault();
}
});
document.addEventListener('mouseup', (e) => {
if (draggingCardEl) {
const draggedCardDataInfo = getCardData(draggingCardEl);
if (!draggedCardDataInfo) { // Should not happen if draggingCardEl exists
cancelDrag();
return;
}
const draggedCard = draggedCardDataInfo.card; // This is the card the drag started on
// Determine the drop target
let dropTarget = null;
// Check foundations first
for (const suit in foundationEls) {
const el = foundationEls[suit];
const rect = el.getBoundingClientRect();
// Check if the *center* of the dragged card is within the target area
const cardRect = draggingCardEl.getBoundingClientRect();
const cardCenterX = cardRect.left + cardRect.width / 2;
const cardCenterY = cardRect.top + cardRect.height / 2;
if (cardCenterX > rect.left && cardCenterX < rect.right &&
cardCenterY > rect.top && cardCenterY < rect.bottom) {
dropTarget = { type: 'foundation', suit: suit, el: el };
break; // Found a foundation target
}
}
// If not dropped on a foundation, check tableau columns
if (!dropTarget) {
for (let i = 0; i < tableauEls.length; i++) {
const el = tableauEls[i];
const rect = el.getBoundingClientRect();
const cardRect = draggingCardEl.getBoundingClientRect();
const cardCenterX = cardRect.left + cardRect.width / 2;
const cardCenterY = cardRect.top + cardRect.height / 2;
// The drop zone for a tableau column is its entire area,
// but the card must attach to the *last* card or an empty space.
// We check if the center of the dragged card is over the column area.
if (cardCenterX > rect.left && cardCenterX < rect.right &&
cardCenterY > rect.top && cardCenterY < rect.bottom) {
dropTarget = { type: 'tableau', column: i, el: el };
break; // Found a tableau target
}
}
}
let moveSuccessful = false;
if (dropTarget) {
// Attempt the move
moveSuccessful = moveCard(draggedCard, draggedCardDataInfo, dropTarget.type, dropTarget);
}
if (!moveSuccessful) {
// If move failed or no valid target, snap back
cancelDrag();
} else {
// If successful, rendering is handled by moveCard, just reset drag state
draggingCardEl = null;
draggedStackEls = [];
draggedStackData = [];
}
}
});
// Helper to reset drag state and snap cards back visually
function cancelDrag() {
if (draggingCardEl) {
draggedStackEls.forEach(el => {
el.classList.remove('dragging');
el.style.position = 'absolute'; // Revert to absolute for normal flow within parent
el.style.left = ''; // Clear inline styles set during drag
el.style.top = '';
el.style.zIndex = ''; // Revert z-index
el.style.pointerEvents = ''; // Re-enable pointer events if they were disabled
});
// Re-render to get correct positions/z-indexes based on the game state (which didn't change)
renderGame(); // Simpler than manually repositioning each card element
draggingCardEl = null;
draggedStackEls = [];
draggedStackData = [];
}
}
// --- Event Handling: Auto-Move (Double Click) ---
document.addEventListener('dblclick', (e) => {
if (e.target.closest('.card')) {
const cardEl = e.target.closest('.card');
const cardDataInfo = getCardData(cardEl);
if (!cardDataInfo) return; // Should not happen
const card = cardDataInfo.card;
const location = cardDataInfo.location;
// Check if the card is the top of its pile/stack and face up
let isMovableTop = false;
if (location === 'waste' && cardDataInfo.index === waste.length - 1 && card.isFaceUp) {
isMovableTop = true;
} else if (location === 'tableau' && cardDataInfo.index === tableau[cardDataInfo.column].length - 1 && card.isFaceUp) {
isMovableTop = true;
}
// Note: Auto-move typically works for single cards only, not stacks.
if (isMovableTop) {
const target = findAutoMoveTarget(card);
if (target) {
let targetEl;
if (target.type === 'foundation') {
targetEl = foundationEls[target.suit];
} else if (target.type === 'tableau') {
targetEl = tableauEls[target.column];
}
if (targetEl) {
// Call moveCard function
moveCard(card, cardDataInfo, target.type, target);
// No need to manually update element position here, moveCard calls renderGame()
}
}
}
}
});
// --- Initialization ---
dealInitial();
renderGame();
</script>
</body>
</html>
代码解释:
-
HTML 结构:
- 设置了基本的 HTML5 骨架。
div.game-area 使用 CSS Grid 来定位不同的游戏区域(牌堆、废牌堆、地基区、排版区)。
- 每个区域(
.pile)都是一个 div,用于容纳牌卡。
- 牌卡使用
div.card 表示。
-
CSS 样式 (<style>):
- 设置了游戏区域的背景颜色和布局。
.pile 类为各个牌堆/区域提供了基本样式(虚线边框,相对定位)。
.card 类定义了牌卡的大小、边框、圆角、背景色等。
- 使用
flexbox 在牌卡内部居中显示花色和数字,并使用 transform: rotate(180deg) 翻转底部的花色和数字。
.red 和 .black 类设置了牌卡内容的颜色。
.face-down 类设置了牌背的样式(不同背景色,隐藏内容)。
.tableau-area .card 使用 position: absolute 和 top 属性来实现牌卡在列中的堆叠偏移效果。
.card.dragging 类用于拖拽时提升 Z-index 和添加阴影效果。
.card-stack-offset (在 JS 中计算,用于拖拽牌叠时调整位置)
-
JavaScript (<script>):
- 游戏状态: 定义了
suits, ranks, colors, suitEmojis 常量。deck, waste, foundations, tableau 数组和对象用于存储游戏状态。
- DOM 元素: 获取了各个游戏区域的 DOM 元素的引用。
createDeck(): 创建一副标准的 52 张牌,每张牌是一个包含 id, rank, suit, color, isFaceUp 的对象。
shuffleDeck(): 使用 Fisher-Yates 算法打乱牌堆。
createCardElement(card): 根据牌卡数据创建一个 DOM 元素,设置其类和数据属性 (data-*)。
updateCardElement(cardEl, card): 更新牌卡 DOM 元素的外观(翻面/正面,颜色,内容)。
renderGame(): 根据当前游戏状态(deck, waste, foundations, tableau 数组)清除并重新渲染所有的牌卡元素到对应的区域。注意在渲染时设置 tableau 牌卡的 top 偏移量和 Z-index。同时控制哪些牌卡可以交互(只有顶部的或翻开的牌)。
dealInitial(): 初始化游戏:创建并洗牌,然后按照 Solitaire 规则发牌到 tableau。
getCardData(cardEl): 根据牌卡 DOM 元素查找其对应的 JS 数据对象及其当前位置。
如何使用:
- 将上面的所有代码复制到一个名为
solitaire.html 的文件中。
- 用浏览器打开
solitaire.html 文件。
你现在应该能看到一个简单的 Solitaire 游戏界面。
游戏操作:
- 点击左上角的牌堆来抽牌。
- 拖拽废牌堆顶部的牌或 tableau 列中翻面的牌/牌叠来移动它们。
- 双击废牌堆顶部的牌或 tableau 列中顶部的翻面牌,游戏会自动尝试将它移动到最合适的位置(地基区优先)。
注意事项和可能的改进:
- 视觉效果: 牌卡堆叠的视觉效果比较基础,可以通过更精细的 CSS 调整
top 和 left 偏移量来实现更自然的层叠感。
- 拖拽性能: 对于非常多的牌卡元素,频繁更新
left/top 可能会有性能问题。更高级的实现可能会使用 CSS transform: translate() 或虚拟 DOM。
- 拖拽目标检测: 当前通过检测拖拽牌卡中心点是否在目标区域的矩形内来判断目标。这在某些情况下可能不够精确,特别是在密集的区域。可以改进为检测与目标区域(如 tableau 列最底部牌卡或空区域)的更精确的交叠。
- 移动动画: 成功移动和“弹回”的动画可以增加游戏的流畅感。
- 音效: 添加音效可以增强游戏体验。
- 胜利动画: 游戏胜利时可以添加更炫酷的动画效果。
- 撤销/重做: 添加撤销和重做功能。
- 更多 Solitaire 规则: 实现 Turn 3 模式,或者其他 Solitaire 变体。
- 触摸屏支持: 为触摸屏设备添加
touchstart, touchmove, touchend 事件支持。
- 代码组织: 将 JS 代码拆分成不同的文件(虽然要求是单文件,但在实际开发中拆分更好管理)。