php实现麻将
PHP实现麻将游戏的基本思路
麻将游戏的实现涉及多个模块,包括牌局初始化、玩家操作、胡牌判定等。以下是关键实现步骤:
麻将牌的初始化与洗牌
使用数组表示麻将牌,包含万、条、筒、风牌等类型。洗牌通过随机打乱数组实现:

$tiles = [
// 万子
'1万', '1万', '1万', '1万',
'2万', '2万', '2万', '2万',
// ...其他牌型
'白板', '白板', '白板', '白板'
];
shuffle($tiles); // 随机洗牌
玩家发牌逻辑
初始化四个玩家,每人13张牌(庄家14张):
$players = [
['hand' => [], 'discarded' => []],
['hand' => [], 'discarded' => []],
['hand' => [], 'discarded' => []],
['hand' => [], 'discarded' => []]
];
// 发牌
for ($i = 0; $i < 13; $i++) {
foreach ($players as &$player) {
$player['hand'][] = array_pop($tiles);
}
}
$players[0]['hand'][] = array_pop($tiles); // 庄家多一张
吃碰杠判定
实现基本的吃、碰、杠操作检测:

function checkPong($playerHand, $discardedTile) {
$count = 0;
foreach ($playerHand as $tile) {
if ($tile === $discardedTile) $count++;
}
return $count >= 2; // 已有两张相同牌可碰
}
function checkKong($playerHand, $discardedTile = null) {
if ($discardedTile) {
// 明杠
$count = 0;
foreach ($playerHand as $tile) {
if ($tile === $discardedTile) $count++;
}
return $count === 3;
} else {
// 暗杠
$tileCounts = array_count_values($playerHand);
return in_array(4, $tileCounts);
}
}
胡牌算法
实现基本胡牌判定(简化版):
function isWin($hand) {
// 转换为数字便于计算
$numericHand = convertTilesToNumbers($hand);
// 检查七对特殊牌型
if (checkSevenPairs($numericHand)) return true;
// 常规胡牌检查
return checkNormalWin($numericHand);
}
function checkNormalWin($tiles) {
if (count($tiles) === 0) return true;
// 尝试找将牌
$counts = array_count_values($tiles);
foreach ($counts as $tile => $count) {
if ($count >= 2) {
$newTiles = $tiles;
// 移除将牌
removePair($newTiles, $tile);
// 检查剩余牌是否能组成顺子或刻子
if (checkMelds($newTiles)) return true;
}
}
return false;
}
游戏流程控制
实现基本的游戏循环:
$currentPlayer = 0; // 庄家开始
$wall = $tiles; // 剩余牌墙
while (true) {
// 玩家摸牌
$drawnTile = array_pop($wall);
$players[$currentPlayer]['hand'][] = $drawnTile;
// 检查胡牌
if (isWin($players[$currentPlayer]['hand'])) {
echo "Player $currentPlayer wins!";
break;
}
// 玩家出牌逻辑(简化)
$discardedTile = chooseDiscard($players[$currentPlayer]['hand']);
$players[$currentPlayer]['discarded'][] = $discardedTile;
// 其他玩家可吃碰杠
// ...
// 轮转玩家
$currentPlayer = ($currentPlayer + 1) % 4;
}
注意事项
- 实际实现需要考虑更复杂的规则,如花牌、杠上开花等特殊规则
- 胡牌算法需要完善,考虑所有可能的牌型组合
- 多人联机版本需要加入网络通信模块
- 前端显示建议使用HTML/CSS或游戏引擎渲染牌面
完整实现需要数千行代码,建议参考开源麻将项目如php-mahjong获取更完整的实现方案。






