java - 2048 game Java:如何根据用户输入打印游戏板?
问题描述
我正在尝试创建游戏 2048,但有点不同。我不想显示通常为 4x4 的网格,而是希望根据用户的喜好显示网格。例如,如果用户输入数字 6,则游戏板应该是 6x6。我这里的代码用于显示 4x4 网格,但我一直在试图弄清楚如何显示任何网格。我已经坚持了几个小时。
如何解决此问题以根据用户的输入显示游戏板?
String rowDashes = "----------------";
for ( int i = 0; i < board.length; i++) {
System.out.println(rowDashes);
System.out.print("|");
for (int j =0; j < board[i].length;j++) {
String number = "";
if (board[i][j] != 0)
{
number = board[i][j] + "";
}
System.out.print(" " + number + "|");
}
System.out.println();
}
System.out.println(rowDashes);
解决方案
编辑:我读错了。我添加了像100, 1800, 45这样的虚拟值。您可以随机删除值或初始化它们。
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter board size: ");
int boardSize = scanner.nextInt();
StringBuilder rowLine = new StringBuilder();
for (int i = 0; i < boardSize; i++) {
rowLine.append("+-----");
}
rowLine.append("+");
int[][] board = new int[boardSize][boardSize];
board[0][2] = 100;
board[1][3] = 1800;
board[1][2] = 45;
System.out.println(rowLine);
for (int i = 0; i < board.length; i++) {
System.out.print("|");
for (int j = 0; j < board[i].length; j++) {
int value = board[i][j];
if (value > 0) {
System.out.printf("%5d", board[i][j]);
} else {
System.out.print(" "); // 5 characters
}
System.out.print("|");
}
System.out.println();
System.out.println(rowLine);
}
}
}
输出:
Enter board size: 6
+-----+-----+-----+-----+-----+-----+
| | | 100| | | |
+-----+-----+-----+-----+-----+-----+
| | | 45| 1800| | |
+-----+-----+-----+-----+-----+-----+
| | | | | | |
+-----+-----+-----+-----+-----+-----+
| | | | | | |
+-----+-----+-----+-----+-----+-----+
| | | | | | |
+-----+-----+-----+-----+-----+-----+
| | | | | | |
+-----+-----+-----+-----+-----+-----+
推荐阅读
- spring-boot - 带有两个 Spring Boot 应用程序的 Docker Compose 得到“消息”:“对 \”http://127.0.0.1:8010/...的 GET 请求出现 I/O 错误:连接被拒绝”
- vue.js - Apexcharts:是否可以显示给定系列的子集?默认情况下,我只需要关注一个系列的最后 5 个元素......而不是整个系列
- excel - 如何更改 ListBox 中的显示值?行源
- java - Spring @Async 中的默认值是什么?
- excel - 在 EXCEL 中将日期时间 (yyyy-mm-dd hh:mm:ss) 格式转换为秒
- hibernate - 两个表中带有休眠的主键
- angular - 之后如何解决推送值及其替换的问题?
- sql - 将多个表关联到一个表 [SQL - Oracle 12c]
- postgresql - 为什么 docker-compose 失败并且 docker run 使用 postgresql 成功?
- python - Checking if a certain key is being pressed