gpt4 book ai didi

java - 在预先绘制的底座之间插入 x

转载 作者:行者123 更新时间:2023-12-01 13:10:42 24 4
gpt4 key购买 nike

我想在第一个 | 之间初始化一个 x |并随着用户输入左、右、下、上移动它。我想我主要需要帮助将 x 放在第一位。大概可以根据答案找出剩下的部分。

public class dimensions {
public static void main(String[] args) {
System.out.println("Select the size of the world widthxheight: ");
Scanner sc = new Scanner(System. in );
String input = sc.nextLine();
String[] parts = input.split("x");
String part1 = parts[0];
String part2 = parts[1];
int sx = 1;
int sy = 0;
int width = Integer.parseInt(part1);
int height = Integer.parseInt(part2);
for (int h = height - 1; h >= 0; h--) {
for (int w = width - 1; w >= 0; w--) {
if (w == width - 1) {
System.out.print("| |");
} else {
System.out.print(" |");
}
}
System.out.print("\n");
}
}
}

最佳答案

您可以使用以下代码在第一个字段中添加 X:

    [...]

int width = Integer.parseInt(part1);
int height = Integer.parseInt(part2);

int playerPosX = 0;
int playerPosY = 0;

for (int h = 0; h < height; h++) {
for (int w = 0; w < width; w++) {
String temp = " |";
if (w == 0) {
temp = "| |";
}
if (playerPosX == w && playerPosY == h) {
temp = temp.replace(' ', 'X');
}
System.out.print(temp);
}
System.out.println();
}

}

}

您还可以使用变量 playerPosXplayerPosY 分别指定玩家的位置,即 X 的位置。

但是,移动玩家而不在每次移动后绘制整个 map 是不可能的,因为 System.out 从技术上讲是一个流,并且不可能操纵已经发送到流的数据。

我建议您创建自己的窗口,在其中添加文本字段并在其上打印 map 。

Tutorial for creating Swing windows.

Tutorial for creating text areas.

关于java - 在预先绘制的底座之间插入 x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22891660/

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