用PHP实现五子棋游戏

PHP实现五子棋游戏的核心逻辑

五子棋游戏的核心逻辑包括棋盘初始化、玩家落子、胜负判断以及AI自动落子(可选)。以下是一个基础实现框架:

class GomokuGame {
    private $board;
    private $size;
    private $currentPlayer;

    public function __construct($size = 15) {
        $this->size = $size;
        $this->initBoard();
        $this->currentPlayer = 1; // 1表示黑棋,2表示白棋
    }

    private function initBoard() {
        $this->board = array_fill(0, $this->size, 
            array_fill(0, $this->size, 0));
    }
}

棋盘渲染与HTML交互

将棋盘渲染为HTML表格,并处理玩家点击事件:

public function renderBoard() {
    echo '<table border="1">';
    for ($i = 0; $i < $this->size; $i++) {
        echo '<tr>';
        for ($j = 0; $j < $this->size; $j++) {
            $cell = $this->board[$i][$j];
            $color = $cell == 1 ? 'black' : ($cell == 2 ? 'white' : 'transparent');
            echo '<td style="width:30px;height:30px;background-color:'.$color.'" 
                  onclick="makeMove('.$i.','.$j.')"></td>';
        }
        echo '</tr>';
    }
    echo '</table>';
}

落子逻辑实现

处理玩家落子并切换当前玩家:

public function makeMove($row, $col) {
    if ($this->isValidMove($row, $col)) {
        $this->board[$row][$col] = $this->currentPlayer;
        if ($this->checkWin($row, $col)) {
            echo "Player ".$this->currentPlayer." wins!";
            return;
        }
        $this->currentPlayer = $this->currentPlayer == 1 ? 2 : 1;
    }
}

private function isValidMove($row, $col) {
    return $row >= 0 && $row < $this->size && 
           $col >= 0 && $col < $this->size && 
           $this->board[$row][$col] == 0;
}

胜负判断算法

检查四个方向(水平、垂直、对角线)是否有五子连珠:

private function checkWin($row, $col) {
    $directions = [
        [[0,1], [0,-1]],   // 水平
        [[1,0], [-1,0]],   // 垂直
        [[1,1], [-1,-1]],  // 主对角线
        [[1,-1], [-1,1]]   // 副对角线
    ];
    
    $player = $this->board[$row][$col];
    
    foreach ($directions as $direction) {
        $count = 1;
        foreach ($direction as $d) {
            $r = $row + $d[0];
            $c = $col + $d[1];
            while ($r >= 0 && $r < $this->size && 
                   $c >= 0 && $c < $this->size && 
                   $this->board[$r][$c] == $player) {
                $count++;
                $r += $d[0];
                $c += $d[1];
            }
        }
        if ($count >= 5) return true;
    }
    return false;
}

简单AI实现

实现一个随机落子的AI对手:

public function makeAIMove() {
    $emptyCells = [];
    for ($i = 0; $i < $this->size; $i++) {
        for ($j = 0; $j < $this->size; $j++) {
            if ($this->board[$i][$j] == 0) {
                $emptyCells[] = [$i, $j];
            }
        }
    }
    
    if (!empty($emptyCells)) {
        $move = $emptyCells[array_rand($emptyCells)];
        $this->makeMove($move[0], $move[1]);
    }
}

完整游戏流程控制

结合HTML表单处理游戏流程:

session_start();

if (!isset($_SESSION['game'])) {
    $_SESSION['game'] = new GomokuGame();
}

$game = $_SESSION['game'];

if (isset($_GET['move'])) {
    list($row, $col) = explode(',', $_GET['move']);
    $game->makeMove($row, $col);
    $game->makeAIMove(); // 如果是人机对战
}

$game->renderBoard();

前端交互增强

使用AJAX实现无刷新落子:

function makeMove(row, col) {
    fetch('game.php?move='+row+','+col')
        .then(response => response.text())
        .then(html => {
            document.getElementById('board').innerHTML = html;
        });
}

性能优化建议

对于大型棋盘或复杂AI算法,可以考虑以下优化:

// 使用位运算存储棋盘状态
private $bitboardBlack;
private $bitboardWhite;

// 快速检查连珠
private function fastCheckWin($bitboard) {
    // 检查水平、垂直和对角线的5个连续1
    $directions = [1, 15, 16, 17];
    foreach ($directions as $shift) {
        if (($bitboard & ($bitboard >> $shift) & 
             ($bitboard >> (2*$shift)) & 
             ($bitboard >> (3*$shift)) & 
             ($bitboard >> (4*$shift))) != 0) {
            return true;
        }
    }
    return false;
}

以上代码展示了用PHP实现五子棋游戏的核心组件。实际开发中还需要考虑会话管理、错误处理、样式美化等细节。这个基础框架可以扩展加入更智能的AI算法、游戏回放、多人联网对战等功能。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值