php - 在地图中自动移动
问题描述
我有一张大小为 (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
解决方案
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()
那么您可以将这些其他属性设置为公共并在该函数中使用相同的逻辑。
推荐阅读
- python - Django - 通过 id 获取对象并克隆它
- angular6 - 未捕获的错误:无法解析组件的所有参数:([object Object]?)
- tensorflow - 如何在张量流对象检测中使用指数学习率?
- r - 在 R 中确定列表组件的类
- c++ - 无法获取进程 ID 4 (ntoskrnl.exe) 的可执行路径
- swift - Segue 删除 tabBarItem.badgeValue
- python - 使用 Python 获取隐藏文件的文件统计信息(大小、创建时间...)
- matlab - 线性回归码
- angularjs - 如何根据AngularJS中的按钮选择显示重复下拉
- java - int 数据类型如何存储 oracle 的 NUMBER(10) 字段?