写PHP写一个情侣飞行棋源码
下面是一个基于PHP的情侣飞行棋的简单游戏源码:
<?php
class FlyingChessGame
{
private $players = array(); // 玩家数组
private $board = array(); // 棋盘数组
private $dice = array(1, 2, 3, 4, 5, 6); // 骰子数字数组
public function __construct($player1, $player2)
{
$this->players[] = $player1;
$this->players[] = $player2;
// 初始化棋盘
for ($i = 0; $i < 30; $i++) {
$this->board[$i] = 0; // 0代表空格
}
}
public function play()
{
$currentPlayer = 0; // 当前玩家的索引
$winner = -1; // 获胜者的索引
while ($winner == -1) {
$player = $this->players[$currentPlayer];
$diceNumber = $this->rollDice();
echo $player . " 掷骰子,点数为 " . $diceNumber . "<br>";
// 计算玩家移动后的位置
$newPosition = $this->getPlayerPosition($currentPlayer) + $diceNumber;
if ($newPosition < 30) {
// 更新玩家位置
$this->setPlayerPosition($currentPlayer, $newPosition);
// 检查是否踩到了对方,若是则返回起点
$otherPlayer = ($currentPlayer + 1) % 2;
if ($this->getPlayerPosition($otherPlayer) == $newPosition) {
$this->setPlayerPosition($otherPlayer, 0);
echo $player . " 踩到了 " . $this->players[$otherPlayer] . ",返回起点<br>";
}
echo $player . " 移动到了位置 " . $newPosition . "<br>";
// 检查是否到达终点
if ($newPosition == 29) {
$winner = $currentPlayer;
}
} else {
echo $player . " 没有移动<br>";
}
$currentPlayer = ($currentPlayer + 1) % 2;
}
echo $this->players[$winner] . " 获胜!";
}
private function rollDice()
{
return $this->dice[array_rand($this->dice)];
}
private function getPlayerPosition($playerIndex)
{
return $this->board[$playerIndex];
}
private function setPlayerPosition($playerIndex, $position)
{
$this->board[$playerIndex] = $position;
}
}
// 游戏开始
$player1 = "小明";
$player2 = "小红";
$game = new FlyingChessGame($player1, $player2);
$game->play();
?>
这个游戏使用了一个FlyingChessGame类来管理游戏的逻辑。构造函数接受两个玩家的名称,并初始化了棋盘数组。play()方法是游戏的主要逻辑,它会轮流让两个玩家掷骰子并移动棋子,直到有玩家到达终点。rollDice()方法随机返回一个骰子点数,getPlayerPosition()和setPlayerPosition()方法用于获取和设置玩家的位置。
在游戏开始时,创建一个FlyingChessGame实例,并调用play()方法开始游戏。游戏进行时,会输出每个玩家掷骰子的点数和移动后的位置,最后输出获胜者的名称。
原文地址: https://www.cveoy.top/t/topic/i84d 著作权归作者所有。请勿转载和采集!