让玩家在 2D 数组游戏网格上移动

发布于 2025-01-04 05:54:04 字数 1138 浏览 1 评论 0原文

我正在使用 10x10 2D 数组创建游戏。玩家从左上角标为“P”的地方开始,目标是让玩家避开障碍物,到达位于右下角标为“T”的宝藏。

我将如何使用上/下/左/右命令让玩家在网格上移动?

我会使用 for 循环来计算数组中的元素以指定移动吗?

这是我到目前为止所拥有的:

import java.util.Scanner;
import java.util.Random;

public class Adventure {

public static void main(String[] args) {
    char grid[][]= new char[10][10];
    Scanner move = new Scanner(System.in);
    System.out.println("Here is the current game board:");
    System.out.println("-------------------------------");

    for(int i=0; i<grid.length; i++) {          
        for(int j=0; j<grid.length; j++) {
            double random = Math.random();
            if(random <=.05) {
                grid[i][j]='*';
            }
            else if(random > .06 && random <= .15) {
                grid[i][j]='X';
            }
            else {
                grid[i][j]='.';
            }
            grid[0][0]='P';
            grid[9][9]='T';
            System.out.print(grid[i][j]);
        }
        System.out.println("");         
    }           
        System.out.print("Enter your move (U/D/L/R)>");
}
}

I am creating a game using a 10x10 2D array. The player starts at the top left hand corner indicated as "P" and the objective is to get the player to avoid obstacles to get to the treasure indicated as "T" located in the lower right corner.

How would I go about making the player move about the grid using commands Up/Down/Left/Right?

Would I use a for loop to count through the elements in the array to designate the move?

Here is what I have so far:

import java.util.Scanner;
import java.util.Random;

public class Adventure {

public static void main(String[] args) {
    char grid[][]= new char[10][10];
    Scanner move = new Scanner(System.in);
    System.out.println("Here is the current game board:");
    System.out.println("-------------------------------");

    for(int i=0; i<grid.length; i++) {          
        for(int j=0; j<grid.length; j++) {
            double random = Math.random();
            if(random <=.05) {
                grid[i][j]='*';
            }
            else if(random > .06 && random <= .15) {
                grid[i][j]='X';
            }
            else {
                grid[i][j]='.';
            }
            grid[0][0]='P';
            grid[9][9]='T';
            System.out.print(grid[i][j]);
        }
        System.out.println("");         
    }           
        System.out.print("Enter your move (U/D/L/R)>");
}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一袭白衣梦中忆 2025-01-11 05:54:04

您应该跟踪玩家的当前位置并更新这些变量。
正如你所说,初始值是 (0,0) 。

int px = 0;
int py = 0;

当进行移动时,相应地更新变量:

grid[px][py] = <empty cell>;
switch (move) {
  case 'u': py += 1; break;
  case 'r': px += 1; break;
  ...
}
grid[px][py] = 'P';

当然你不应该只是“盲目”地更新值,你应该插入一些验证逻辑来​​遵循游戏规则:

if (grid[px][py] != <obstacle> )
   // update player coordinates...

you should keep track of the current position of the player and just update those variables.
initial values would be (0,0) as you said.

int px = 0;
int py = 0;

when a move is made, update the variables accordingly:

grid[px][py] = <empty cell>;
switch (move) {
  case 'u': py += 1; break;
  case 'r': px += 1; break;
  ...
}
grid[px][py] = 'P';

of course you shouldn't just updated the values "blindly", you should insert some validation logic to follow the rules of the game:

if (grid[px][py] != <obstacle> )
   // update player coordinates...
陪我终i 2025-01-11 05:54:04

从电路板打印的方式来看,您似乎正在使用行优先排序。基于此,您需要执行以下操作:

  1. 首先,您需要将玩家的位置存储在某处。现在它被硬编码为 0,0。
  2. 其次,您需要读取玩家的动作。这必须在一个循环中发生,在该循环中,您进行移动,检查移动是否被允许,执行移动并显示结果。
  3. 第三,您需要能够根据移动计算新位置。向上表示row -= 1。右表示列+= 1。等等。
  4. 给定新坐标,您需要确保移动有效。至少,你必须阻止他们走下棋盘,但你也可能会阻止他们进入有障碍物的方格等。
  5. 一旦你知道移动是有效的,你就必须更新你正在做的变量。存储当前坐标。
  6. 在循环结束时,您需要重新绘制棋盘。

这就是它的基本要点。现在你正在 main() 中完成所有操作,这没关系,但如果是我,我会开始将事情分成单独的方法,例如 InitializeBoard()GetNextMove()CheckIfMoveIsValid(int r, int c) 等等。这样,main() 就成为游戏循环的高级视图,并且不同操作的内部被划分并且更容易处理。这将需要将游戏板之类的东西存储到类变量而不是局部变量中,这实际上应该使障碍物检测之类的事情比现在更容易。

Looks like you're using row-major ordering, judging from the way your board prints out. Based on that, here's what you'll need to do:

  1. First, you need to store the player's position somewhere. Right now it's hardcoded to 0,0.
  2. Second, you need to read in the player's move. That will have to happen in a loop, where you get a move, check if the move is allowed, perform the move, and display the results.
  3. Third, you need to be able to calculate the new position based on the move. Up means row -= 1. Right means column += 1. Etc.
  4. Given the new coordinates, you need to make sure the move is valid. At the very least, you have to stop them from walking off the board, but you may also prevent them from entering a square with an obstacle, etc.
  5. Once you know that the move is valid, you have to update the variables you're storing the current coordinates in.
  6. At the end of the loop, you'll need to redraw the board.

That's the basic gist of it. Right now you are doing everything in main(), and that's okay, but if it were me I would start to split things out into separate methods, like InitializeBoard(), GetNextMove(), CheckIfMoveIsValid(int r, int c), and so on. That way, main() becomes a high-level view of your game loop, and the guts of the different operations are compartmentalized and more easy to deal with. This will require storing off things like your game board into class variables rather than local variables, which should actually make things like obstacle detection easier than it would be currently.

瑾夏年华 2025-01-11 05:54:04

以上所有答案都很棒。以下是我提出的一些建议:

我将创建一个自定义对象,例如 Space,而不是 char 二维数组,并定义一个二维数组空间(例如,Space[][])。造成这种情况的原因有几个:

  1. 您可以通过多种方式定义空格(而不仅仅是 1 个字符)。例如,Space[i][j].hasTreasure() 可以返回一个布尔值,让您知道是否找到了宝藏。
  2. 如果您想稍后添加功能,只需向 Space 类添加属性即可。再次强调,您不限于这里的一个角色。

关于你的运动问题,我还会推荐一些东西。类似于 redneckjedi 对 CheckIfMoveIsValid() 方法的建议,我将传递网格和移动方向作为参数并返回一个布尔值。为了确保您不会遇到 ArrayIndexOutOfBounds 问题,我还建议在每一侧添加一排/一列墙。我会将网格扩大到 12x12,并在外侧放置一条障碍物类型的方块。这将确保您无法走出网格,因为在有效的移动中撞到墙壁将始终返回“false”。

All of the above answers are great. Here are a few suggestions I would make:

Instead of a char two-dimensional array, I would make a custom object, such as Space, and define a two-dimensional array of Spaces (eg, Space[][]). There are a few reasons for this:

  1. You can define a space in a variety of ways (rather than just 1 character). For example, Space[i][j].hasTreasure() can return a boolean to let you know whether or not you found the treasure.
  2. If you want to add functionality later, its as easy as adding an attribute to your Space class. Again, you are not limited to one character here.

More to your question of movement, I would also recommend a few things. Similar to redneckjedi's suggestion of a CheckIfMoveIsValid() method, I would pass the grid and move direction as parameters and return a boolean. To ensure that you do not end up with ArrayIndexOutOfBounds issues, I would also suggest adding a row/column of walls on each side. I would widen the grid out to 12x12 and put a strip of obstacle-type blocks around the outside. This will ensure that you cannot step outside of the grid as hitting a wall will always return 'false' on a valid move.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文