我想制作一个 10x10 的网格并将机器人放在位置 (10,1)(左下)。我希望这个机器人能够向前移动、左转/右转以及拾取/将物体放入网格中。当放置在任何位置时,网格中应该有一个数字,显示该位置放置了多少个对象,如下所示:
..........
...1......
..2.......
....3.....
..........
..........
......9...
.....4....
.........1
..........
我们不会在网格中看到机器人。我有两个类。类机器人:
public class Robot {
private Area area;
private Robot rob;
public Robot(Area area){
this.area = area;
rob = new Robot(area);
}
public void Right(){
}
public void Left(){
}
public void Forward(){
}
public void Put(){
}
public void PickUp(){
}
public (?) getPosition(){ // should return robot's position
}
}
类(class)区域:
private int numberOfObjects;
private Robot robot;
private static final int X = 10;
private static final int Y = 10;
private Object [][] area; // grid
public Area(){ // defines a grid and robot
area = new Area[X][Y];
for(int a=0;a<X;a++){
for(int b=0;b<Y;b++)
area[a][b]=".";
}
numberOfObjects = 0; // grid is initially empty
Area ar = new Area();
robot = new Robot(ar);
}
public void Put(int x,int y){ // put the object to position (x,y)
area[x][y]=numberOfObjects++;
}
public void PickUp(int x,int y){ // pick up the object in position (x,y)
if(area[x][y]!=null){
area[x][y]=numberOfObjects--;
}
}
public void PrintAGrid(){
for(int r=0;r<X;r++){
for(int c=0;c<Y;c++)
System.out.print(area[r][c]+" ");
System.out.println();
}
System.out.println();
}
}
如何将机器人置于 (10,1) 位置?我如何声明和设置其方向(即在右侧)?我想编写其他方法会很容易,所以我不关注它。
最佳答案
您的代码存在几个问题。
- 为什么
Robot
类中有一个Robot
实例?您根本没有使用过该实例! private Object [][]区域;
应为int[][]区域
。你总是在其中保存int
,对吗?- 如果我正确理解了您的要求,那么您对
pick
和put
的实现是不正确的。
这里是如何解决问题的帮助。我不得不多次思考 Robot
是否应该在 Grid
中,或者应该是其他方式。我最终在 Robot
中得到了 Grid
。
可能 Grid
可能是一个单例。
这是我们的网格
public class Grid {
private int[][] numberOfObjects = new int[10][10];
public void put(int x, int y) {
numberOfObjects[y][x]++;
}
public void pick(int x, int y) {
numberOfObjects[y][x]--;
}
}
您可以将参数 int x, int y
替换为 Point
。
这是机器人
public class Robot {
private static final int NORTH = 0, EAST = 1, SOUTH = 2, WEST = 3;
private int direction;
private int x, y;
private Grid grid;
public Robot(Grid grid) {
this.x = 0;
this.y = 0;
this.grid = grid;
direction = NORTH;
}
public void right() {
direction++;
if (direction == 4) {
direction = 0;
}
}
public void left() {
direction--;
if (direction == -1) {
direction = 3;
}
}
public void forward() {
if (direction == NORTH) {
y--;
} else if (direction == SOUTH) {
y++;
} else if (direction == EAST) {
x++;
} else if (direction == WEST) {
x--;
}
}
public void put() {
grid.put(x, y);
}
public void pick() {
grid.pick(x, y);
}
}
关于java - 机器人在网格中的位置和方向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16637006/