You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP游戏原型开发求助:实现指定游戏场的显示方法

实现PHP游戏原型并生成指定游戏场

需求背景

需要补全缺失的House、Tree、Lawn、Flower类及Game类的核心方法,让给定代码正常运行,并输出注释中所示的带坐标游戏场布局。

实现思路

  • 让所有地形类(House/Tree/Lawn/Flower)继承Tile基类,每个子类定义自身对应的显示图标。
  • Game类负责管理所有Tile实例,自动去重重复坐标的Tile(比如两个Lawn(0,3)只保留一个)。
  • 给Game类添加渲染方法:先计算游戏场的最大X、Y坐标确定范围,再按行遍历,逐列匹配对应坐标的Tile图标,无Tile的位置留空。

完整代码实现

class Tile
{
    public int $x;
    public int $y;
    public string $icon;

    public function __construct(int $x, int $y)
    {
        $this->x = $x;
        $this->y = $y;
    }
}

// 各类地形子类,继承Tile并定义专属图标
class House extends Tile
{
    public string $icon = '🏠';
}

class Tree extends Tile
{
    public string $icon = '🌳';
}

class Lawn extends Tile
{
    public string $icon = '🌿';
}

class Flower extends Tile
{
    public string $icon = '🌼';
}

class Game
{
    /** @var Tile[] 以"x,y"为键的Tile集合,用于坐标去重 */
    private array $tiles = [];

    public function __construct(array $tiles)
    {
        foreach ($tiles as $tile) {
            $key = "{$tile->x},{$tile->y}";
            // 重复坐标仅保留第一个实例(若要覆盖则移除判断直接赋值即可)
            if (!isset($this->tiles[$key])) {
                $this->tiles[$key] = $tile;
            }
        }
    }

    // 渲染游戏场的核心方法
    public function render(): void
    {
        // 计算游戏场的最大X、Y坐标,确定布局范围
        $maxX = 0;
        $maxY = 0;
        foreach ($this->tiles as $tile) {
            if ($tile->x > $maxX) $maxX = $tile->x;
            if ($tile->y > $maxY) $maxY = $tile->y;
        }

        // 打印顶部坐标表头
        echo '   ';
        for ($x = 0; $x <= $maxX; $x++) {
            echo $x . ' ';
        }
        echo PHP_EOL;

        // 逐行渲染每一列的内容
        for ($y = 0; $y <= $maxY; $y++) {
            // 打印行号
            echo $y . '  ';
            // 逐列检查对应坐标是否有Tile
            for ($x = 0; $x <= $maxX; $x++) {
                $key = "{$x},{$y}";
                echo isset($this->tiles[$key]) ? $this->tiles[$key]->icon . ' ' : '  ';
            }
            echo PHP_EOL;
        }
    }
}

// 初始化游戏并执行渲染
$game = new Game([
    new House(0,0), //house
    new Tree(1,0), //tree
    new Tree(2,0), //tree
    new Lawn(0,1), //lawn
    new Lawn(0,2), //lawn
    new Lawn(0,3), //lawn
    new Lawn(0,3), //lawn
    new Flower(3,0), //flower
    new Flower(1,3), //flower
]);

$game->render();

运行效果

执行代码后会输出与需求一致的游戏场:

0 1 2 3 
0  🏠 🌳 🌳 🌼 
1  🌿       
2  🌿       
3  🌿 🌼     

内容的提问来源于stack exchange,提问作者YPower

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:31:23