2013-03-30 214 views
1

我有一个类Grid,它管理所有的地图功能。问题是,pacman地图逆时针旋转90度。地图旋转了90度?

它的外观

The issue

应该如何看待

The 'fixed' version

我通过交换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数组的正确格式。

回答

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

这仅仅是一个的那grid[i][j]i个子阵列,这实际上是在j列在格式化网格i第i行的位置,并在第j元件的事实症状。

由于您希望x代表该列,而y代表该行,因此grid[y][x]是访问阵列中某个位置的正确方法。