javaarrays2048

Filling 2D Array with 2 values from a random list (2048 Game)


I am trying to recreate the 2048 game and I have hit a brick wall and am stumped. I have made my grid with a 2d array and it seems to be working okay. I have then made a method to store an list of empty/free space in this grid/array so that the two starting numbers can be assigned to two random free spaces. My problem is that I cannot get the numbers to show inside the actual grid. I have my code below and would appreciate if anybody could show me where i am going wrong. Apologies if I explained this horribly, I am still quite new to Java.

import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;

public class Main {
    //Game Board Size Method - Getting User Number to use for dimension of game board
    public static int gameBoardSize() {
        int number = 0;
        int row = 0;
        Scanner in = new Scanner(System.in);
        System.out.println("Welcome to 1024");
        System.out.print("Please select a number between 4 & 8 to determine the size of your game board: "); //Prompt user to select number
        number = in.nextInt(); //Storing number in variable
        if (number >= 4 && number <= 8) { //If number is >= 4 and <= 8
            row = number; //Assign number to row variable
        } else {
            System.out.print("Error, please select a number between 4 & 8"); //Error print message
        }
        return row; //Return
    }

    //Display Game board method - Array for game board grid and to display the grid.
    public static void displayGameBoard(int[][] gameBoard, int gameBoardSize) {
        String divider;
        switch (gameBoardSize) {
            case 5:
                divider = "\n+-----+-----+-----+-----+-----+"; //User Number 5
                break;
            case 6:
                divider = "\n+-----+-----+-----+-----+-----+-----+"; //User Number 6
                break;
            case 7:
                divider = "\n+-----+-----+-----+-----+-----+-----+-----+"; //User Number 7
                break;
            case 8:
                divider = "\n+-----+-----+-----+-----+-----+-----+-----+-----+"; //User Number 8
                break;
            default:
                divider = "\n+----+-----+-----+----+"; //User Number 4
        }
        System.out.println(divider); //Printing Divider at top
        for (int i = 0; i < gameBoard.length; i++) {
            for (int j = 0; j < gameBoard[i].length; j++) {
                if (gameBoard[i][j] == 0) { //If both i & j is == 0
                    System.out.print("|     "); //Print this left border
                }
                if (j == gameBoard[j].length - 1) { //If 2nd array length -1 (end)
                    System.out.print("|"); //Print end border
                }
            }

            System.out.println(divider); //Printing Divider at bottom
        }
    }



    public static int[][] createGameBoard(int userRows) {
        return new int[userRows][userRows]; //Returning rows
    }


    //Method to loop through array to find empty space
    public static int[][] findEmptyCells(int[][] gameBoard)  {
        int freeCellCount = 0;
        int[][] emptyList = new int[gameBoard.length * gameBoard.length][2];
        for (int i = 0; i < gameBoard.length; i++) {
            for (int j = 0; j < gameBoard[i].length; j++) {
                if (gameBoard[i][j] == 0) {
                    emptyList[freeCellCount][0] = i;
                    emptyList[freeCellCount][1] = j;
                    freeCellCount++;
                }
                Random rnd = new Random();
                int rndPair = rnd.nextInt(freeCellCount);
                emptyList[rndPair][0] = i;
                emptyList[rndPair][1] = j;
            }
        }
        return emptyList;
    }

    //Use WASD: W for up, S for Down, A for Left and D for Right
    public static void instructions() {
        System.out.println("How to Play");
        System.out.println("Press W to move up");
        System.out.println("Press S to move down");
        System.out.println("Press A to move left");
        System.out.println("Press D to move right");
    }



    public static void main(String[] args) {
        int rows = gameBoardSize();
        int[][] gameBoard = createGameBoard(rows);
        displayGameBoard(gameBoard, rows);
        instructions();
        int[][] findEmptyCells = findEmptyCells(gameBoard);
    }
}

Solution

  • Unless you are required to create this game using printing to the console - I would abandon this method ASAP. Creating a game like 2048 in a space that is not designed to act like an animation pane is going to be very difficult and frustrating.

    Instead, I would have each tile be an object and do some research on swing and Graphics in Java.

    If you must do it this way, (by the way, check the way you set up the grid - it's not consistent spacing) you'll have to print the values between the "|" characters.

    What's a smart way to do that? Well, you could create a 2D int array, int[][], and store all the values on the game board. Then, you can loop over every element in the 2D array, and print it between your "|" characters. This example below will work for any size 2D array. Try changing the number of values you pass in and notice how it behaves.

    public class Test {
        private static int[][] temp = new int[][] {{0,2, 4},{4, 4,16}, {3, 0, 128}};
    
        public static void main(String[] args) {
            int rows = temp.length;
            int cols = temp[0].length;
    
            for (int i = 0; i < rows; i++) {
                // This will resize our row separator for each row
                for (int j = 0; j < cols; j++) {
                    System.out.print("+-----");
                }
    
                System.out.print("+\n");
    
                for (int j = 0; j < cols; j++) {
                    System.out.print("|");
    
                    // Here you have to deal with the spacing. You can see that this is ugly.
                    // There's definitely better ways to do this, such as using mod
                    if (temp[i][j] == 0) {System.out.print("     ");}
                    else if (temp[i][j] < 10) {System.out.print("  " + temp[i][j] + "  ");}
                    else if (temp[i][j] < 100) {System.out.print("  " + temp[i][j] + " ");}
                    else if (temp[i][j] < 1000) {System.out.print(" " + temp[i][j] + " ");}
                }
    
                System.out.print("|\n");
            }
    
            for (int j = 0; j < cols; j++) {
                System.out.print("+-----");
            }
    
            System.out.print("+\n");
        }
    }
    

    Output from the program above:

    +-----+-----+-----+
    |     |  2  |  4  |
    +-----+-----+-----+
    |  4  |  4  |  16 |
    +-----+-----+-----+
    |  3  |     | 128 |
    +-----+-----+-----+
    

    But then there is the problem of keeping your spacing correct. You need to account for the length of the number, because your have to have the right number of spaces printed if the number is blank. Or you'll have to use replace()... it sounds confusing.