我在创建用于游戏的表格时遇到问题。它需要有
- 3 个人类字符
@
, - 2 个怪物
#
, - 3 个宝箱
*
- 和 4 个障碍
O
。
表格需要是 10 x 10 的正方形,并且间隙应该用 填充。
它应该看起来像这样:
1 2 3 4 5 6 7 8 9 10 1 . @ . * . . . . . . 2 . . . . . # . . O . 3 . . . . . . . . . . 4 . . . . . . . . . . 5 . . . # . . @ . . . 6 . . O . . . . . . . 7 . . . . O . . . O . 8 . . . . . . * . . . 9 . * . . . . . . . . 10 . . . . . . . @ . .
I also need to be able to move the chapters in the end. This is my currant code. But I can only get it so that the .
and @
appear, otherwise I just get errors. Even when using else if
:
package test;
import java.util.Scanner;
public class Test {
public static void show(boolean[][] grid) {
String s = "";
for (boolean[] row : grid) {
for (boolean col : row)
if (col)
s += "@ ";
else
s += ". ";
s += "\n";
}
System.out.println(s);
}
public static boolean[][] gen() {
boolean[][] grid = new boolean[10][10];
for (int r = 0; r < 10; r++)
for (int c = 0; c < 10; c++)
if (Math.random() > 0.2)
grid[r][c] = true;
return grid;
}
public static void main(String[] args) {
boolean[][] world = gen();
show(world);
System.out.println();
world = nextGen(world);
show(world);
Scanner s = new Scanner(System.in);
while (s.nextLine().length() == 0) {
System.out.println();
world = nextGen(world);
show(world);
}
}
public static boolean[][] nextGen(boolean[][] world) {
boolean[][] newWorld
= new boolean[world.length][world[0].length];
int num;
for (int r = 0; r < world.length; r++) {
for (int c = 0; c < world[0].length; c++) {
num = numNeighbors(world, r, c);
if (occupiedNext(num, world[r][c]))
newWorld[r][c] = true;
}
}
return newWorld;
}
public static boolean occupiedNext(int numNeighbors, boolean occupied) {
if (occupied && (numNeighbors == 2 || numNeighbors == 3))
return true;
else if (!occupied && numNeighbors == 3)
return true;
else
return false;
}
private static int numNeighbors(boolean[][] world, int row, int col) {
int num = world[row][col] ? -1 : 0;
for (int r = row - 1; r <= row + 1; r++)
for (int c = col - 1; c <= col + 1; c++)
if (inbounds(world, r, c) && world[r][c])
num++;
return num;
}
private static boolean inbounds(boolean[][] world, int r, int c) {
return r >= 0 && r < world.length && c >= 0 &&
c < world[0].length;
}
}
有人知道如何帮助我输入所有符号吗?
最佳答案
您正在为网格使用 boolean 二维数组。所以每个条目只能有两个值。例如,如果将其切换为 int[][],则可以为可能居住在该单元格中的不同类型的对象指定不同的值。举例来说:
- 人类“@”
- 怪物“#”
- 宝箱“*”
- 障碍物“O”
也许可以使用 0 = 未占用的“.”,因为整数无论如何都默认为零。
关于java - Java 中的 Ascii 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29682821/