PHP 怎么PHP五子棋

wen PHP项目 1

本文目录导读:

PHP 怎么PHP五子棋

  1. 方式一:纯PHP控制台版本
  2. 方式二:Web版本(HTML + PHP)
  3. 使用方法
  4. 主要功能

我来帮你实现一个PHP五子棋游戏,这里提供两种实现方式:

纯PHP控制台版本

<?php
class GomokuGame {
    private $board = [];
    private $size = 15;
    private $currentPlayer = 1; // 1=黑棋, 2=白棋
    public function __construct() {
        $this->initBoard();
    }
    // 初始化棋盘
    private function initBoard() {
        for ($i = 0; $i < $this->size; $i++) {
            for ($j = 0; $j < $this->size; $j++) {
                $this->board[$i][$j] = 0;
            }
        }
    }
    // 下棋
    public function placePiece($row, $col) {
        if ($row < 0 || $row >= $this->size || $col < 0 || $col >= $this->size) {
            return false;
        }
        if ($this->board[$row][$col] != 0) {
            return false;
        }
        $this->board[$row][$col] = $this->currentPlayer;
        // 检查是否胜利
        if ($this->checkWin($row, $col)) {
            return "玩家 " . ($this->currentPlayer == 1 ? "黑棋" : "白棋") . " 获胜!";
        }
        // 切换玩家
        $this->currentPlayer = $this->currentPlayer == 1 ? 2 : 1;
        return true;
    }
    // 检查胜利条件
    private function checkWin($row, $col) {
        $directions = [
            [0, 1],  // 水平
            [1, 0],  // 垂直
            [1, 1],  // 对角线
            [1, -1]  // 反对角线
        ];
        foreach ($directions as $dir) {
            $count = 1;
            // 正方向
            for ($i = 1; $i < 5; $i++) {
                $newRow = $row + $dir[0] * $i;
                $newCol = $col + $dir[1] * $i;
                if ($this->isValidPos($newRow, $newCol) && 
                    $this->board[$newRow][$newCol] == $this->currentPlayer) {
                    $count++;
                } else {
                    break;
                }
            }
            // 反方向
            for ($i = 1; $i < 5; $i++) {
                $newRow = $row - $dir[0] * $i;
                $newCol = $col - $dir[1] * $i;
                if ($this->isValidPos($newRow, $newCol) && 
                    $this->board[$newRow][$newCol] == $this->currentPlayer) {
                    $count++;
                } else {
                    break;
                }
            }
            if ($count >= 5) {
                return true;
            }
        }
        return false;
    }
    // 检查位置是否有效
    private function isValidPos($row, $col) {
        return $row >= 0 && $row < $this->size && 
               $col >= 0 && $col < $this->size;
    }
    // 显示棋盘
    public function displayBoard() {
        echo "  ";
        for ($i = 0; $i < $this->size; $i++) {
            printf("%2d ", $i);
        }
        echo "\n";
        for ($i = 0; $i < $this->size; $i++) {
            printf("%2d ", $i);
            for ($j = 0; $j < $this->size; $j++) {
                $piece = $this->board[$i][$j];
                if ($piece == 1) {
                    echo "● ";
                } elseif ($piece == 2) {
                    echo "○ ";
                } else {
                    echo "· ";
                }
            }
            echo "\n";
        }
    }
    // 获取当前玩家
    public function getCurrentPlayer() {
        return $this->currentPlayer;
    }
    // 检查棋盘是否已满
    public function isBoardFull() {
        for ($i = 0; $i < $this->size; $i++) {
            for ($j = 0; $j < $this->size; $j++) {
                if ($this->board[$i][$j] == 0) {
                    return false;
                }
            }
        }
        return true;
    }
}
// 游戏主循环(控制台版本)
function playConsoleGame() {
    $game = new GomokuGame();
    echo "=== PHP五子棋游戏 ===\n";
    echo "输入行列坐标(如:7 7),q退出\n\n";
    while (true) {
        $game->displayBoard();
        $player = $game->getCurrentPlayer();
        echo "\n当前玩家:" . ($player == 1 ? "黑棋(●)" : "白棋(○)") . "\n";
        echo "请输入坐标:";
        $input = trim(fgets(STDIN));
        if ($input == 'q' || $input == 'Q') {
            echo "游戏结束\n";
            break;
        }
        $coords = explode(' ', $input);
        if (count($coords) != 2) {
            echo "输入格式错误,请输入两个数字\n";
            continue;
        }
        $row = (int)$coords[0];
        $col = (int)$coords[1];
        $result = $game->placePiece($row, $col);
        if ($result === false) {
            echo "无效位置,请重新输入\n";
        } elseif (is_string($result)) {
            $game->displayBoard();
            echo "\n" . $result . "\n";
            echo "游戏结束!\n";
            break;
        }
        if ($game->isBoardFull()) {
            echo "棋盘已满,平局!\n";
            break;
        }
    }
}
// 运行控制台版本
// playConsoleGame();
?>

Web版本(HTML + PHP)

<?php
session_start();
class GomokuWeb {
    private $size = 15;
    public function initBoard() {
        if (!isset($_SESSION['board']) || isset($_POST['new_game'])) {
            $_SESSION['board'] = array_fill(0, $this->size, array_fill(0, $this->size, 0));
            $_SESSION['current_player'] = 1;
            $_SESSION['game_over'] = false;
            $_SESSION['winner'] = null;
        }
    }
    public function playMove($row, $col) {
        if ($_SESSION['game_over']) {
            return false;
        }
        $board = $_SESSION['board'];
        if ($board[$row][$col] != 0) {
            return false;
        }
        $board[$row][$col] = $_SESSION['current_player'];
        $_SESSION['board'] = $board;
        if ($this->checkWin($board, $row, $col, $_SESSION['current_player'])) {
            $_SESSION['game_over'] = true;
            $_SESSION['winner'] = $_SESSION['current_player'];
        } else {
            $_SESSION['current_player'] = $_SESSION['current_player'] == 1 ? 2 : 1;
        }
        return true;
    }
    private function checkWin($board, $row, $col, $player) {
        $directions = [[0,1], [1,0], [1,1], [1,-1]];
        foreach ($directions as $dir) {
            $count = 1;
            for ($i = 1; $i < 5; $i++) {
                $r = $row + $dir[0] * $i;
                $c = $col + $dir[1] * $i;
                if ($r >= 0 && $r < 15 && $c >= 0 && $c < 15 && $board[$r][$c] == $player) {
                    $count++;
                } else break;
            }
            for ($i = 1; $i < 5; $i++) {
                $r = $row - $dir[0] * $i;
                $c = $col - $dir[1] * $i;
                if ($r >= 0 && $r < 15 && $c >= 0 && $c < 15 && $board[$r][$c] == $player) {
                    $count++;
                } else break;
            }
            if ($count >= 5) return true;
        }
        return false;
    }
    public function renderBoard() {
        $board = $_SESSION['board'];
        echo "<table class='board'>";
        for ($i = 0; $i < 15; $i++) {
            echo "<tr>";
            for ($j = 0; $j < 15; $j++) {
                $piece = $board[$i][$j];
                $class = $piece == 1 ? 'black' : ($piece == 2 ? 'white' : 'empty');
                echo "<td class='cell {$class}' onclick='playMove({$i}, {$j})'>";
                if ($piece != 0) {
                    echo $piece == 1 ? '●' : '○';
                }
                echo "</td>";
            }
            echo "</tr>";
        }
        echo "</table>";
    }
}
// 初始化游戏
$game = new GomokuWeb();
$game->initBoard();
// 处理移动
if (isset($_POST['move']) && !$_SESSION['game_over']) {
    $row = (int)$_POST['row'];
    $col = (int)$_POST['col'];
    $game->playMove($row, $col);
}
// 处理新游戏
if (isset($_POST['new_game'])) {
    $game->initBoard();
}
?>
<!DOCTYPE html>
<html>
<head>PHP五子棋</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0;
        }
        .game-container {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            text-align: center;
        }
        h1 {
            color: #333;
            margin-bottom: 20px;
        }
        .player-info {
            margin-bottom: 15px;
            font-size: 18px;
            font-weight: bold;
        }
        .board {
            border-collapse: collapse;
            margin: 20px auto;
            background: #DEB887;
            border: 3px solid #333;
        }
        .cell {
            width: 35px;
            height: 35px;
            border: 1px solid #888;
            text-align: center;
            font-size: 24px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .cell:hover {
            background: rgba(255,255,255,0.3);
        }
        .black {
            color: #000;
        }
        .white {
            color: #ccc;
        }
        .empty {
            color: transparent;
        }
        .btn {
            background: #667eea;
            color: white;
            border: none;
            padding: 10px 30px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s;
        }
        .btn:hover {
            background: #764ba2;
        }
        .message {
            margin: 15px 0;
            padding: 10px;
            border-radius: 5px;
            background: #f9f9f9;
            font-size: 20px;
            font-weight: bold;
        }
        .winner {
            color: #4CAF50;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>🀄 PHP五子棋</h1>
        <?php if ($_SESSION['game_over']): ?>
            <div class="message winner">
                🎉 玩家 <?= $_SESSION['winner'] == 1 ? '黑棋' : '白棋' ?> 获胜!
            </div>
        <?php else: ?>
            <div class="player-info">
                当前玩家:<?= $_SESSION['current_player'] == 1 ? '黑棋(●)' : '白棋(○)' ?>
            </div>
        <?php endif; ?>
        <form method="POST">
            <?php $game->renderBoard(); ?>
            <br>
            <button type="submit" name="new_game" class="btn">开始新游戏</button>
        </form>
        <form id="moveForm" method="POST" hidden>
            <input type="hidden" name="row" id="moveRow">
            <input type="hidden" name="col" id="moveCol">
        </form>
    </div>
    <script>
        function playMove(row, col) {
            if (<?= $_SESSION['game_over'] ? 'true' : 'false' ?>) return;
            document.getElementById('moveRow').value = row;
            document.getElementById('moveCol').value = col;
            // 添加下棋动画
            const cells = document.querySelectorAll('.cell');
            const index = row * 15 + col;
            cells[index].style.transform = 'scale(1.2)';
            setTimeout(() => {
                document.getElementById('moveForm').submit();
            }, 200);
        }
    </script>
</body>
</html>

使用方法

控制台版本:

php gomoku_console.php

Web版本:

  1. 将代码保存为 gomoku.php
  2. 放到你的Web服务器(Apache/Nginx)目录
  3. 浏览器访问该文件

主要功能

基础功能:

  • 15×15的标准棋盘
  • 黑白棋对战
  • 自动判断胜负
  • 玩家轮流下棋

增强功能:

  • 简单的界面优化
  • 会话管理(可以保存游戏状态)
  • 重新开始功能
  • 胜负提示

这个实现包含了五子棋的核心逻辑,包括落子、胜负判断和玩家轮换,你可以根据需要进一步扩展,比如添加AI对战、悔棋功能、在线对战等。

抱歉,评论功能暂时关闭!