2013-03-30 284 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]是訪問陣列中某個位置的正確方法。