首页 > 解决方案 > 在地图中自动移动

问题描述

我有一张大小为 (10,10) 的地图。我用一个名为 的对象来表示它Map。我Monster在它的位置 (5,5) 上有一个。这个怪物必须在每个位置自动改变位置$turn并且依赖于$nbMove$nbMove是类的一个属性Monster你在构造函数中选择它Monster

$nbMove是他半转之前的移动次数

这是我想要的一个例子,当游戏开始时:

游戏处于循环中for($turn = 0; $turn<10; $turn++)

所以如果$nbMove是 2。怪物去箱子(5,6),下一个$turn,他去(5,7),下一个$turn他回到(5,6),下一个$turn(5,5)。下一个$turn(5,6),下一个$turn(5,7),下一个$turn(5,6)等等......

所以如果$nbMove是 3。怪物去箱子(5,6),下一个$turn,他去(5,7),下一个$turn他去(5,8),下一个$turn(5,7),下一个$turn(5,6),下一个$turn(5,5)等...

他应该只垂直。

这就像国际象棋的移动,但它是由计算机完成的,它总是做同样的事情。这是我的代码:

<?php 

class Monster { 
  public $horizontal;
  public $vertical;
  public $nbMove;

  function __construct($horizontal, $vertical, $nbMove) {
    $this->horizontal = $horizontal;
    $this->vertical = $vertical;
    $this->nbMove = $nbMove;
  } 
}

?>
<?php 

class Map { 
  public $width;
  public $height;

  function __construct($width, $height) {
    $this->width = $width;
    $this->height = $height;
  } 
}

?>
<?php

function moveMonster($turn, $monster, $map) {
  // The move 
  if(// I need a condition there but what condition ??) {
    $orc->vertical = $orc->vertical + 1;
  } else {
    $orc->vertical = $orc->vertical - 1;
  }
}

$map = new Map(10,10);
$firstMonster = new Monster(5,5,2);

for($turn = 0; $turn<10; $turn++){
  moveMonster($turn, $firstMonster, $map);
}

?>

我搜索如何移动我的怪物,但我没有找到任何解决方案。这就是为什么我问你我的问题的解决方案。我知道如何让它移动,但它应该取决于我认为$turn的数量。$firstMonster->nbMove

标签: phpalgorithmoop

解决方案


Monster不仅需要能够跟踪其当前位置,还需要能够在任一方向上走多远以及当前正在移动的方向。如果你没有办法保持那个状态,那么一旦你第一次移动它,你就失去了原来的 Y 位置,并且无法知道你是否在它的$nbMove移动范围内或是否你正在接近或远离它。

如果我们添加更多属性来Monster定义它们,并在构造函数中设置它们,那么它很容易在其定义的边界内移动并在到达边界边缘时改变方向。

class Monster {
    public $horizontal;
    public $vertical;
    public $nbMove;

    private $minY;
    private $maxY;
    private $direction;

    function __construct($horizontal, $vertical, $nbMove) {
        $this->horizontal = $horizontal;
        $this->vertical = $vertical;
        $this->nbMove = $nbMove;

        $this->minY = $vertical;
        $this->maxY = $vertical + $nbMove;
        $this->direction = 1;
    }

    function move() {
        // if at the top of the movement range, set the direction to down
        if ($this->vertical == $this->maxY) {
            $this->direction = -1;
        }
        // if at the bottom of the movement range, set the direction to up
        if ($this->vertical == $this->minY) {
            $this->direction = 1;
        }
        // then move
        $this->vertical += $this->direction;
    }
}

move()在这里展示了一种方法,Monster因为我认为它似乎更合适,因为移动是可以Monster做到的。如果你这样做,你会调用$firstMonster->move()循环而不是全局moveMonster()函数。

如果您需要使用,moveMonster()那么您可以将这些其他属性设置为公共并在该函数中使用相同的逻辑。


推荐阅读