Creating 2048 GAME in java using only the console - java

I hope i find someone to help finish the game ( 2048 )., since I'm in a computing programmer for only 2 month it's been difficult for me to do it.
The basis of this game that the user can choose what ever dimension he wants, and i kind of figured it out but now I'm struggling in a question saying:
In the beginning of the game two ‘1’ tiles are added to two random cells in the grid. Every subsequent turn a ‘1’ tile is added to an unoccupied cell in the grid, at the end of every turn you should make a list of all free cells and randomly select a free cell using that list".
I tried my best best still didn't work.
Another question was challenging says:
After the user makes a move all number tiles should attempt to move in the selected direction. A tile should continue to move in the given direction until it either hits another tile with a different number and stops or hits a tile with the same name and merges with it. Make sure that the only reason a tile stopped moving is if there are no empty cells in the direction it is supposed to move, or that all tiles that were supposed to merge do merge.
My current code:
import java.util.*;
public class The1024Game {
public static void main(String[] args) {
// TODO Auto-generated method stub
// QEUSTION 1: Asking the user to choose the desired dimensions of the grid
Scanner in = new Scanner(System.in);
System.out.print("Enter board size (IT MUST BE BETWEEN 4 AND 10): ");
int Dimension = 0;
do {
Dimension = in.nextInt();
if ( Dimension>10 | Dimension<4) {
System.out.print("THE DIMENSION MUST BE BETWEEN 4 AND 10!! PLEASE TRY AGAIN: ");
}
}while (Dimension>10 | Dimension<4);
System.out.println("The dimension has been set correctly");
// QEUSTION 2 : The frame of the game
int [][] GameFrame = new int[Dimension][Dimension];
//System.out.println(GameFrame[0][0]);
//GameFrame[0][0]=1000;
for(int i = 0; i<Dimension; i++) {
System.out.print("|");
for (int j=0; j<Dimension; j++) {
System.out.print(GameFrame[i][j]);
if(GameFrame[i][j]>=100 & GameFrame[i][j]<1000) {
System.out.print(" ");
}
if(GameFrame[i][j]>=10 & GameFrame[i][j]<100) {
System.out.print(" ");
}if(GameFrame[i][j]>=0 & GameFrame[i][j]<10 ){
System.out.print(" ");
}if(GameFrame[i][j]>=1000) {
}
System.out.print("|");
}
System.out.println();
for(int k=0; k<Dimension; k++) {
System.out.print("| ");}
System.out.print("|");
System.out.println();
System.out.print(" ");
for(int k=0; k<Dimension; k++) {
System.out.print("-----");
}
//testing another methode:
//StringBuilder rowLine = new StringBuilder();
//for (int c = 0; c<Dimension; c++) {
// rowLine.append("+-----");
//}
//rowLine.append("+");
System.out.print("\n");
}
// question 3:
int [] Free_coordinates;
for (int i=0; i<Dimension; i++) {
int [] Coordinates={0,0};
for (int j=0; j<Dimension; j++) {
if (GameFrame[i][j]==0) {
Coordinates[0]=i;
Coordinates[1]=j;
}
}
}

Related

Trying to make a chessboard that takes simple string inputs and stores them in Java

I am still new to Java and have been working with 2D arrays recently. What I am trying to do is make a simple 2D grid array of a Chessboard that has the arrays from a1 all the way to h8. The first thing I tried to do is convert the array [8][8] so that the first 8 was characters and the second 8 was integers. What I am currently trying to do is prompt the user and ask them which coordinate they would like to choose (from a1 all the way to h8). When they choose one of the coordinates, I would like them to enter a string (which in the future will be my chess pieces) that will be stored on the board, so that, when I use another class to print these strings, it'll give me an output like "a5 - Lemon (As im not checking to see if the chess piece is a valid piece yet) or "h2 - Queen".
So, to clarify, the program asks the user "Please enter a coordinate (e.g. a5)". "Now, Please enter a piece to be placed on that coordinate" Which then gets stored in that coordinate. When the user types, for example, "Done" I would like all the coordinates that have pieces on them to be revealed as well as what piece was put on them.
Code:
import java.util.Scanner;
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
int[][] grid = new int [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int col = (int)(input.charAt(0) - 'a');
int row = (int)(input.charAt(1) - '0');
}
}
}
I have used a while loop to continuously prompt the user until they give a correct coordinate, but Im not sure how to prompt the user to enter a piece that gets stored in that coordinate?
Any help would be appreciated!
First of all, in order to store the piece name with the coordinates, you will need a 2D array of strings instead of integers.
After changing that, you take the user input again and then save the coordinates with the piece and save it in the 2d array at said column and row.
Also, the row is retrieved from the character (a-b-c-etc..) and the column from the number and not the way around.
public class ChessBoard
{
public static void main(String[] args)
{
char rows = 'a';
String spot;
Scanner scanner = new Scanner(System.in);
String[][] grid = new String [8][8];
for(int i = 0; i < grid.length; i++, rows++)
{
for(int col = 0; col < grid[i].length; col++)
{
System.out.print(rows + "" + (col + 1) + " ");
}
String input = null; // will be changed to a valid position
boolean validCoordinate = false; // will be true if position is valid
while ( ! validCoordinate) {
System.out.println("Enter a coordinate (for example, a5): ");
input = scanner.next();
validCoordinate = input.matches("[a-g][1-8]");
};
// now we now that the input is valid
int row = input.charAt(0) - 'a';
int col = input.charAt(1) - '1';
String temp = input + " - ";
System.out.println("Insert your piece:");
input = scanner.next();
grid[row][col] = temp + input;
}
System.out.println(Arrays.deepToString(grid));
}
}

How can I pair my user's input number in an array whose sum is equal to specified input number?

Here's my hard work code so far, we were asked to do it with GUI. Please help me on what approach should I do next to pair my user's input number in an array whose sum is equal to specified input number?
package josh;
import javax.swing.JOptionPane;
public class Sample {
public static void main (String args[]) {
int colInput,rowInput;
String user_col = JOptionPane.showInputDialog("Enter Column Of Array:");
colInput = Integer.parseInt(user_col);
String user_row = JOptionPane.showInputDialog("Enter Row Of Array:");
rowInput = Integer.parseInt(user_row);
int user_value;
for (int i = 0; i < colInput; i++) {
for (int j= 0; j < rowInput; j++) {
String values = JOptionPane.showInputDialog(null, "Enter Value "+(i+1));
user_value = Integer.parseInt(values);
final Integer [] value_arr = new Integer [user_value];
}
}
}
}
Here's the sample input and output
I would give you the basic logic that you can use.
// value_arr[] is the array where you have all the elements.
// sum is the number to be paired
Arrays.sort(value_arr);
int i=0,j=value_arr.length-1;
// now value_arr is sorted. we'll use two pointers i & j to move.. i moves in from left side towards centre and j moves from right side towards centre
while(i<j){
if(value_arr[i]+value_arr[j]>sum){
j--;
}
else if(value_arr[i]+value_arr[j]<sum){
i++;
}
else if(value_arr[i]+value_arr[j]==sum){
System.out.println(value_arr[i]+"+"+value_arr[j]+"="+sum);
}
}
Let me know if it helps

multidimensional array with no repeated numbers of the same row

int matrice2 [][] = new int [5][5];
for (int i=0;i<5;i++) {
System.out.println(" ");
for(int j=0;j<5;j++) {
matrice2[i][j] = (int)(Math.random()*10);
System.out.print(" "+matrice2[i][j]+" ");
}
}
System.out.println(" ");
System.out.println(" ");
for (int i=0;i<5;i++) {
System.out.println(" ");
for(int j=0;j<5;j++) {
for (int k=0;k<5;k++) {
if(j!=k) {
if (matrice2[i][j]==matrice2[i][k]) {
matrice2[i][k]=(int)(Math.random()*10);
}
}
}
System.out.print(" "+matrice2[i][j]+" ");
}
}
I wanted to make a multidimensional array without having any repeated numbers in the same row so the column doesn't matter if it has repeating numbers.
What I did here is generate 5x5 arrays formed in square.
Having index "j" as the one that gets compared with numbers in index "k" that checks the whole row if there are numbers that is equal to the number it contains in index "j".
So my only problem is that after detecting the number in "k" that is equal to the number in "j", the number in index "k" will generate a new number replacing the current number in "k" but the result in console shows that the original 5x5 array which is the first formed of the array before it gets changed has been changed but the numbers that have been replaced generated a numbers that already exist even it should keep changing until "k" cannot detect any repeated numbers.
I can think of other ways of doing it but I really want to know why it doesn't work even though I really think that it shouldn't give any problems but I might have missed something.
here's the example of the results that shouldn't have occured.
from
9 1 3 8 4
5 3 2 4 8
9 8 5 6 5
6 3 0 8 7
2 8 6 3 9
to
9 1 3 8 4
5 3 2 4 8
9 8 5 6 9
6 3 0 8 7
2 8 6 3 9
it shouldn't happen because "k" should have seen it since he starts from index 0 to 4.
while "j" is in index 4 and "k" is in index 0 it should have detected it immediately and change the number in "k" to something else random.
EDIT: I see the different ways you guys are showing but what Im asking is to provide maybe a better solution without using any imports. our teacher gave us this assignment telling us without using any of those imports which makes it more complicated but it's what we are asked for.
I tried it with while but still no changes happening.
I editted your code in a different way. I wrote some comment to code understand clearly. Try it please.
public class UniqueMatrix {
public static void main(String[] args) {
int matrix[][] = new int[5][5];
boolean uniqeMatrixFound = false;
while (!uniqeMatrixFound) {
//fill matrix until uniqe matrix found value is true
fillMatrix(matrix);
for (int i = 0; i < matrix.length; i++) {
HashSet<Integer> columnNumber = new HashSet<>();
for (int j = 0; j < matrix.length; j++) {
columnNumber.add(matrix[j][i]);
}
//if set size not equal to matrix size , create an new uniqe matrix with breaking false value
if (columnNumber.size() != matrix.length) {
uniqeMatrixFound = false;
break;
}
uniqeMatrixFound = true;
}
}
//print an array
for (int i = 0; i < matrix.length; i++) {
System.out.println(" ");
for (int j = 0; j < matrix.length; j++) {
System.out.print(" " + matrix[i][j] + " ");
}
}
}
//create a matrix with unique value in all rows.
private static void fillMatrix(int[][] matrice2) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
for (int i = 0; i < matrice2.length; i++) {
Collections.shuffle(list);
for (int j = 0; j < matrice2.length; j++) {
matrice2[i][j] = list.get(j);
}
}
}
}
Here is your code edited. I also commented inline what were the changes and why. You could have done it more easy but I think it suites you more to edit your example so you can understand. Only issue is that you should have stored the value on matrice2[i][j] = newValue (to let k go to the end of the line and check with all other values that your random is not an existing number)
Hope it helps.
public class UniqueMatrix {
public static void main (String[] args) {
int matrice2 [][] = new int [5][5];
for (int i=0;i<5;i++) {
System.out.println(" ");
for(int j=0;j<5;j++) {
matrice2[i][j] = (int)(Math.random()*10);
System.out.print(" "+matrice2[i][j]+" ");
}
}
System.out.println(" ");
System.out.println(" ");
for (int i=0;i<5;i++) {
System.out.println(" ");
for(int j=0;j<5;j++) {
for (int k=0;k<5;k++) {
if(j!=k) {
if (matrice2[i][j]==matrice2[i][k]) {
int newValue = (int)(Math.random()*10);
//store the newly found value in j for you have time to check with others till the end
matrice2[i][j] = newValue;
}
}
}
System.out.print(" "+matrice2[i][j]+" ");
}
}
}
}
Here is a different approach to the problem that uses a shuffled ArrayList instead of checking whether a value exists in the current row or not.
int matrice2[][] = new int[5][5];
ArrayList<Integer> sourceMatrix = new ArrayList<Integer>();
for (int i = 0; i < 10; i++)
sourceMatrix.add(i);
//generate random matrix using shuffled arraylist
for (int i = 0; i < matrice2.length; i++) {
Collections.shuffle(sourceMatrix);
for (int j = 0; j < matrice2[i].length; j++) {
matrice2[i][j] = sourceMatrix.get(j);
}
}
//print generated matrix
for (int i = 0; i < matrice2.length; i++) {
for (int j = 0; j < matrice2[i].length; j++) {
System.out.print(matrice2[i][j]);
}
System.out.println();
}
The way I read your logic is that when you find a duplicate you generate a new number and that new number will validated in the next iteration of the outer (j) loop. The problem is when j==k because that number will not be validated, normally this isn't a problem since j will increase and then that number will be validated with the exception of when j==4 since that is the last iteration.
So modify the rightmost column and that value will not be checked because 'j==k' will never be false.
The problem in your code was that after you detected the duplicate value, you assigned the new generated random number without checking if it is also a duplicate number. what i did here is that i detect duplicate and before assigning/replacing the new generated random number i will check whether it is also duplicate or not, if it is duplicate i will generate another otherwise i will assign it and move on.
(int)(Math.random()*10); // this code does not guarantee that new unique number is generated every time you call it.
the problem is in the code below , you are updating matrice2[i][k] with new (int)(Math.random()*10) with out checking whether it is same or different number.
if (matrice2[i][j]==matrice2[i][k]) {
matrice2[i][k]=(int)(Math.random()*10);
}

Combining conways code with the gui

public void actionPerformed(ActionEvent e){
grid=new JButton[length+20][width+20];
grid1=new JButton[length+20][width+20];
for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid1[i][j]=grid[i][j];
}
}
for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
//final int row = i;
//final int col = j;
int count=0;
if(grid[i][j-1].getBackground() == Color.BLACK);
count++;
if(grid[i][j+1].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j-1].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j].getBackground()==Color.BLACK)
count++;
if(grid[i-1][j+1].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j-1].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j].getBackground()==Color.BLACK)
count++;
if(grid[i+1][j+1].getBackground()==Color.BLACK)
count++;
if(count==3) // exactly three neighbors
{
if(grid[i][j].getBackground()==Color.WHITE)
{
grid1[i][j].setBackground(Color.BLACK); // birth cell
}
}
if(count==2 || count==3) // 2 or 3 neighbors
{
if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.BLACK); // survives
}
}
if(count>=4 || count<=1) //4 or more neighbors, or 1 or less neighbor
{
if(grid[i][j].getBackground()==Color.BLACK)
{
grid1[i][j].setBackground(Color.WHITE); // dies from over-population or isolation
}
}
}
}
for(int i=0;i<length+2;i++)
{
for(int j=0;j<width+2;j++)
{
grid[i][j]=grid1[i][j];
}
}
for(int i=1;i<length+1;i++)
{
for(int j=1;j<width+1;j++)
{
System.out.print(grid[i][j]);
}
System.out.println("\n");
}
}
I am getting a nullpointer exception when I try to display the next generation of conway game of life using a GUI. Please suggest whats wrong with my code. The action performed method is executed when a start button is clicked
The cause of the NullPointerException is this:
grid = new JButton[length+20][width+20];
grid1 = new JButton[length+20][width+20];
This way, you have a 2D-array of JButtons, but it is still full of null values. You have to initialize the individual "cells" in the array:
for (int i = 0; i < length+20; i++) {
for(int j = 0; j < width+20; j++) {
grid1[i][j] = new JButton();
}
}
Also, is the size of the array intentional, or should it be length+2 x width+2 instead, as in your for-loop?
But this is not your actual problem: You create a new buttons-array, and then check the background colors of those newly created buttons. Assuming that grid represents the current state of the game, you are erasing the game state before doing the update. More likely, you have to drop the line grid = new JButton[length+20][width+20]; entirely.
And even this will not work correctly, as the two arrays grid and grid1 will hold the same buttons, so when you change the background color of one, you also change the background color in the backup. With grid1[i][j]=grid[i][j] you just copy the reference to the button to the other array, but do not create a new button. And even if you did, you would have the problem that that new button would not be in the GUI at all.
Instead of storing your game state in the GUI elements, you should rather use two 2D-arrays of booleans (one for the current state, one as backup of the previous state during the state update) and set the background color of the buttons based on those booleans.

How can i specify where o board ends?

i have a board([17][17]) and i place words in it giving the row and the column.I want if the position of the word given is bigger than the board,then a message is shown and you should give the row and column again.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
for (int i = 0; i < word.length(); i++)
{
if (y + i >= board[x].length)
{
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
}
else {
board[x][y + i] = word.charAt(i);
}
}
When i give a=3 and r=5 it still prints me "The board is smaller!!" and want to give new values again.Does anyone know how to fix this?
Edit
**main()**
board b=new board();
String s="abc";
int x=2,y=20;
b.placeWord(Board, s, x, y);
for(int i=0;i<Board.length;i++)//prints the board
{
System.out.println(Board[i]);
}
From a=3 and r=5 I suspect you already failed for placing the word in the first place and entered a new row/column.
In this case the "old" for loop has not finished yet and will continue to place letters (as long as there are some remaining) after the call to b.placeWord(...);.
One way to circumvent this is to break the loop by a simple break; statement after the call to b.placeWord(...);.
Note: the second time you are filling the word into your newly created board b which you discard afterwards (it is never accessed anywhere in the code you showed us). Additionally you might first test if the word fits (can actually be done without a loop: y+word.length()<=board[x].length()) and then fill in the letters. Otherwise the remainders of the failed attempt will stay on the board.
**Board class**
......
public void placeWord(char[][] board, String word, int x, int y)
if (y + word.length() >= board[x].length)
{
// don't loop, ask for another position to put word
System.out.println("The board is smaller!!");
Board b=new Board();
int a,r;
System.out.println("Give row and column again");
a=in.nextInt();
r=in.nextInt();
b.placeWord(board, word, a, r);
} else
{
// already done the checking, don't need to worry here
for (int i = 0; i < word.length(); i++)
{
board[x][y + i] = word.charAt(i);
}
}

Categories

Resources