gpt4 book ai didi

java - 如何使用坐标移动数组中的符号?

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:38 24 4
gpt4 key购买 nike

我正在尝试制作一个简单的程序(现在对java没有太多经验,仍在学习),在数组中的“位置”之间移动符号,因此输出看起来像这样

“向东走”

[ ] [O] [ ]

[ ] [ ] [O]

我现在有一种方法可以做到这一点,我为每个变体编写一个 If 语句,例如

if (map[0][2] == 'X') {//if I am in this room
if (dir.equalsIgnoreCase("north")) {
System.out.println("You can't go that way");
} else if (dir.equalsIgnoreCase("south")) {
System.out.println("You go south");
map[0][2] = ' ';//moving from one room
map[1][2] = 'X';//to the other

这意味着如果我有多个房间,该方法就会变得非常长。我确信有一种方法可以通过创建两个全局变量(例如代表它在数组中的位置的 X 和 Y)为符号提供一个坐标来缩短这个时间,并且通过更改这些变量我可以更改它的位置,这只需要几行,因为它只需要一个变体,但我无法弄清楚如何将坐标链接到数组移动。任何帮助将不胜感激!

编辑:未能澄清某些事情。每个 map 坐标都设置为一个名为“房间”的类,该类为其提供描述和名称

最佳答案

您应该有两个名为 currentXcurrentY 的变量:

int currentX = 0;
int currentY = 0;

这些将存储X的位置。然后你可以通过执行以下操作来访问当前位置:

map[currentX][currentY]

这意味着您只有四种情况(四个方向)需要处理:

if (dir.equalsIgnoresCase("south")) {
if (isValidCoordinate(currentX, currentY + 1)) {
map[currentX][currentY] = ' ';
map[currentX][currentY + 1] = 'X';
currentY += 1;
} else {
// you can't go this way
}
} else if (dir.equalsIgnoresCase("east")) {
if (isValidCoordinate(currentX + 1, currentY)) {
map[currentX][currentY] = ' ';
map[currentX][currentY] = 'X';
currentX += 1;
} else {
// you can't go this way
}
} else if ...

其中 isValidCooperative 是您必须实现的方法,如果您可以转到该坐标,则返回 true。

private boolean isValidCoordinate(int x, int y) {
// ...
}

关于java - 如何使用坐标移动数组中的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53677478/

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