首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >2048游戏Java:如何根据用户的输入打印游戏板?

2048游戏Java:如何根据用户的输入打印游戏板?
EN

Stack Overflow用户
提问于 2020-12-15 22:03:03
回答 1查看 342关注 0票数 0

我正在尝试创建2048年的游戏,但有点不同。与其显示通常为4x4的网格,我希望根据用户的需要显示网格。例如,如果用户输入数字6,游戏板应该是6x6。我这里的代码是用来显示网格4x4的,但是我一直在试图弄清楚如何显示任何网格。我被困在这上面已经好几个小时了。

如何根据用户的输入来修复这个问题以显示游戏板?

代码语言:javascript
复制
    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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-15 22:16:59

编辑:,我看错了。我添加了像100,1800,45这样的虚拟值。您可以删除值或随机初始化它们。

代码语言:javascript
复制
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);
        }
    }
}

输出:

代码语言:javascript
复制
Enter board size: 6
+-----+-----+-----+-----+-----+-----+
|     |     |  100|     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |   45| 1800|     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |     |
+-----+-----+-----+-----+-----+-----+
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65314335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档