首页 > 解决方案 > 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);

标签: java

解决方案


编辑:我读错了。我添加了像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|     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+

推荐阅读