php实现 小游戏
以下是一些用PHP实现小游戏的常见方法和示例:
猜数字游戏
$target = rand(1, 100);
$guess = $_POST['guess'] ?? 0;
if ($guess > $target) {
echo "Too high!";
} elseif ($guess < $target) {
echo "Too low!";
} else {
echo "You got it!";
}
井字棋游戏
session_start();
if (!isset($_SESSION['board'])) {
$_SESSION['board'] = array_fill(0, 9, '');
}
if (isset($_GET['move'])) {
$pos = $_GET['move'];
if ($_SESSION['board'][$pos] === '') {
$_SESSION['board'][$pos] = 'X';
// AI move
$empty = array_keys($_SESSION['board'], '');
if (!empty($empty)) {
$_SESSION['board'][$empty[array_rand($empty)]] = 'O';
}
}
}
function checkWinner($board) {
$wins = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];
foreach ($wins as $win) {
if ($board[$win[0]] && $board[$win[0]] === $board[$win[1]] && $board[$win[0]] === $board[$win[2]]) {
return $board[$win[0]];
}
}
return false;
}
记忆卡牌游戏
$cards = ['A','A','B','B','C','C','D','D'];
shuffle($cards);
if (isset($_POST['card1']) && isset($_POST['card2'])) {
if ($cards[$_POST['card1']] === $cards[$_POST['card2']]) {
echo "Match found!";
} else {
echo "Try again";
}
}
贪吃蛇游戏基础
session_start();
if (!isset($_SESSION['snake'])) {
$_SESSION['snake'] = [[5,5]];
$_SESSION['direction'] = 'right';
$_SESSION['food'] = [rand(0,9), rand(0,9)];
}
if (isset($_GET['dir'])) {
$_SESSION['direction'] = $_GET['dir'];
}
// Move snake
$head = $_SESSION['snake'][0];
switch ($_SESSION['direction']) {
case 'up': $new = [$head[0], $head[1]-1]; break;
case 'down': $new = [$head[0], $head[1]+1]; break;
case 'left': $new = [$head[0]-1, $head[1]]; break;
case 'right': $new = [$head[0]+1, $head[1]]; break;
}
array_unshift($_SESSION['snake'], $new);
// Check collision
if ($head[0] < 0 || $head[0] > 9 || $head[1] < 0 || $head[1] > 9) {
session_destroy();
echo "Game Over";
}
注意事项
PHP主要用于服务器端逻辑,复杂的图形游戏需要结合HTML5 Canvas或JavaScript

游戏状态可以通过SESSION保存

考虑使用AJAX实现实时更新而不刷新页面
安全考虑:验证所有用户输入,防止XSS和CSRF攻击
这些示例展示了PHP实现简单游戏的核心逻辑,可以根据需要扩展功能






