我有一个班级Grid
,它管理所有地图功能。问题是,pacman地图逆时针旋转了90度。
看起来如何
它应该如何看待
我通过在grid[x][y]
内将grid[y][x]
换成isWall()
来获得'固定'版本(一种不整齐,不正确的方法)
以下是Grid
类的完整代码;
package com.jackwilsdon.pacman.game;
import org.newdawn.slick.Graphics;
public class Grid {
public static final int BLOCK_SIZE = 20;
public int[][] grid = null;
public Grid()
{
grid = new int[][] { {0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0},
{0,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,0,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,0,1,0},
{0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0},
{0,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1,0},
{0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0},
{0,0,0,0,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,0,0},
{0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0},
{0,0,0,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,0,0,0},
{0,0,0,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,0,0,0},
{0,1,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,1,0},
{0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0},
{0,1,0,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,0,1,0},
{0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0},
{0,1,1,0,1,0,1,0,1,1,1,1,1,0,1,0,1,0,1,1,0},
{0,1,0,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,1,0},
{0,1,0,1,1,1,1,1,1,0,1,0,1,1,1,1,1,1,0,1,0},
{0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0} };
}
public boolean isWall(int x, int y)
{
if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length)
{
return grid[y][x] == 1;
}
return true;
}
public void draw(Graphics g)
{
for (int cX = 0; cX < grid.length; cX++)
{
for (int cY = 0; cY < grid[cX].length; cY++)
{
if (this.isWall(cX, cY))
{
g.fillRect(cX*Grid.BLOCK_SIZE, cY*Grid.BLOCK_SIZE, Grid.BLOCK_SIZE, Grid.BLOCK_SIZE);
}
}
}
}
}
我在代码中犯了一个愚蠢的错误吗?
我不想切换x和y,因为它不再是2d数组的正确格式。
答案 0 :(得分:2)
我在代码中看到的问题是边界检查不正确。换句话说,这段代码:
if (x >= 0 && x < grid.length && y >= 0 && y < grid[0].length)
{
return grid[y][x] == 1;
}
实际应该是
if (x >= 0 && x < grid[0].length && y >= 0 && y < grid.length)
{
return grid[y][x] == 1;
}
您当前的代码仅适用于尺寸相等(地图为方形)。
draw
函数中存在相同的错误。换句话说,它应该是
for (int cY = 0; cY < grid.length; cY++)
{
for (int cX = 0; cX < grid[cY].length; cX++)
{
if (this.isWall(cX, cY))
{
g.fillRect(cX*Grid.BLOCK_SIZE, cY*Grid.BLOCK_SIZE, Grid.BLOCK_SIZE, Grid.BLOCK_SIZE);
}
}
}
在任何情况下,grid[y][x]
都是正确的,而不是grid[x][y]
,因为grid[i]
指的是2D数组的索引i
处的行,不是专栏。
答案 1 :(得分:1)
这只是grid[i][j]
引用j
子数组中i
个元素的事实的一个症状,实际上是j
的位置第列和格式化网格中的i
行。
由于您希望x
代表该列,y
代表该行,grid[y][x]
是访问数组中某个位置的正确方法。