斗牛游戏核心逻辑直接相关的代码段提取,包括洗牌、发牌、计算牛、更新分数以及游戏流程控制等部分:
洗牌函数 (shuffleCards
)
javascript
const shuffleCards = () => { const shuffledCards = []; while (cards.length > 0) { const randomIndex = Math.floor(Math.random() * cards.length); shuffledCards.push(cards[randomIndex]); cards.splice(randomIndex, 1); } return shuffledCards; };
牌面转换数值 (cardValue
)
javascript
const cardValue = (card) => { if (['J', 'Q', 'K'].includes(card)) return 10; if (card === 'A') return 1; return parseInt(card, 10); };
计算是否有牛及牛的点数 (calculateNiupai
)
const calculateNiupai = (hand) => {
console.log(`正在计算手牌 ${hand} 的牛情况...`);
// 先找出所有可能的三张牌组合
for (let i = 0; i < hand.length - 2; i++) {
for (let j = i + 1; j < hand.length - 1; j++) {
for (let k = j + 1; k < hand.length; k++) {
const sum = cardValue(hand[i]) + cardValue(hand[j]) + cardValue(hand[k]);
console.log(`检查组合 [${hand[i]}, ${hand[j]}, ${hand[k]}]: 总和为 ${sum}`);
// 判断和是否为10的倍数,即是否有牛
if (sum % 10 === 0) {
// 剩余两张牌之和的个位数作为牛的点数
const remainingCards = hand.filter((_, index) => ![i, j, k].includes(index));
const niuPointSum = remainingCards.reduce((acc, cur) => acc + cardValue(cur), 0);
const niuPoint = niuPointSum % 10;
console.log(`发现牛!剩余牌 [${remainingCards}], 总和 ${niuPointSum}, 牛点数为 ${niuPoint}`);
return { hasNiupai: true, niuPoint };
}
}
}
}
console.log("此手牌未发现牛。");
return { hasNiupai: false, niuPoint: null };
};
// 增加简单的动画效果提示
const showScoreAnimation = (newScore, type) => {
// 这里可以使用CSS动画或其他库实现动画效果
console.log(`${type}得分更新至${newScore}`);
};
// 修改游戏逻辑函数,添加动画反馈
const playGame = async () => {
setRoundCount(prevCount => prevCount + 1);
dealCardsWithAnimation(); // 添加这一行来调用发牌动画函数
const playerResult = calculateNiupai(playerCards);
setPlayerNiupai(playerResult.niuPoint);
const computerResult = calculateNiupai(computerCards);
setComputerNiupai(computerResult.niuPoint);
// 更新分数,并加入动画反馈
if (playerResult.hasNiupai && !computerResult.hasNiupai) {
showScoreAnimation(playerScore + 1, "玩家");
setPlayerScore(prevScore => prevScore + 1);
} else if (!playerResult.hasNiupai && computerResult.hasNiupai) {
showScoreAnimation(computerScore + 1, "电脑");
setComputerScore(prevScore => prevScore + 1);
} else if (playerResult.hasNiupai && computerResult.hasNiupai) {
if (playerResult.niuPoint > computerResult.niuPoint) {
showScoreAnimation(playerScore + 1, "玩家");
setPlayerScore(prevScore => prevScore + 1);
} else if (playerResult.niuPoint < computerResult.niuPoint) {
showScoreAnimation(computerScore + 1, "电脑");
setComputerScore(prevScore => prevScore + 1);
}
}
// 在游戏结束后保存结果
await saveMatchResult(userid, playerScore, computerScore);
};
// 添加useEffect进行轮次结束后的判断
useEffect(() => {
if (roundCount === 10) {
if (playerScore > computerScore) {
alert("玩家获胜!");
} else if (playerScore < computerScore) {
alert("电脑获胜!");
} else {
alert("平局!");
}
// 重置游戏状态
setPlayerScore(0);
setComputerScore(0);
setRoundCount(0);
}
}, [playerScore, computerScore, roundCount]);
以上代码片段覆盖了斗牛游戏的主要逻辑,包括洗牌、发牌、计算牛、更新分数、游戏流程控制以及轮次结束的处理。请注意,实际应用中还需考虑错误处理、用户交互细节及性能优化等方面。