gpt4 book ai didi

java - map 旋转90度?

转载 作者:行者123 更新时间:2023-11-29 05:46:24 25 4
gpt4 key购买 nike

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

外观

The issue

它应该是什么样子

The 'fixed' version

我通过将 grid[x][y] 替换为 isWall() 内的 grid[y][x] 获得了“固定”版本(一种不整洁、不正确的方法)

这是 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,因为这不再是二维数组的正确格式。

最佳答案

我在您的代码中看到的问题是边界检查不正确。也就是说,这段代码:

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;
}

您当前的代码之所以有效,是因为尺寸相等( map 是方形的)。

您在 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] 指的是二维数组的索引 i 处的,而不是列。

关于java - map 旋转90度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15722973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com