Php 地图中的自动移动
我有一张尺寸为(10,10)的地图。我用一个名为Php 地图中的自动移动,php,algorithm,oop,Php,Algorithm,Oop,我有一张尺寸为(10,10)的地图。我用一个名为Map的对象来表示它。我有一个怪物,在位置(5,5)上。该怪物必须在每次$turn时自动改变位置,并且取决于$nbMove$nbMove是类Monster的一个属性,您可以在Monster的构造函数中选择它 $nbMove是他半圈前的移动次数 下面是我想要的一个例子,当游戏开始时: 游戏处于($turn=0;$turn)的循环 我搜索如何移动我的怪物,但我没有找到任何解决方案。这就是为什么我问你我的问题的解决方案。我知道如何移动它,但它应该取决于
Map
的对象来表示它。我有一个怪物
,在位置(5,5)上。该怪物必须在每次$turn
时自动改变位置,并且取决于$nbMove
$nbMove
是类Monster
的一个属性,您可以在Monster
的构造函数中选择它
$nbMove
是他半圈前的移动次数
下面是我想要的一个例子,当游戏开始时:
游戏处于($turn=0;$turn)的循环
我搜索如何移动我的怪物,但我没有找到任何解决方案。这就是为什么我问你我的问题的解决方案。我知道如何移动它,但它应该取决于
$turn
和$firstMonster->nbMove
的数量。我认为怪物不仅需要跟踪它当前的位置如果你没有办法保持这种状态,那么一旦你第一次移动它,你就失去了原来的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()
然后,您可以将这些其他属性设置为公共属性,并在该函数中使用相同的逻辑。怪物不仅需要能够跟踪其当前位置,还需要能够跟踪其在任一方向上可以走多远以及当前移动的方向。如果您无法保持该状态,则当您第一次移动它时,您已经失去了原来的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()
,则可以将这些其他属性设置为public,并在该函数中使用相同的逻辑