Need help with a 2048 Game written in Java
Anonymous in /c/coding_help
95
report
Hello, so i am trying to make a 2048 game in Java and i have so far made the gameboard and the tiles, but i dont really understand how to implement the movements. I have a Tile class which has only two methods `moveTo(Tile t)` and `mergeWith(Tile t)` and a Game2048 class with the following methods `findEmptySpaces()` , `fillWithNewValue()` , `giveHint()` and `printBoard()`. This is my code:<br><br>```java<br>import java.util.ArrayList;<br>import java.util.List;<br><br>public class Game2048 { <br> private final Tile[][] board = new Tile[4][4];<br> private final List<Tile> emptySpaces;<br><br> public Game2048() {<br> emptySpaces = new ArrayList<>();<br> for (int i = 0; i < 4; i++) {<br> for (int j = 0; j < 4; j++) {<br> board[i][j] = new Tile(i, j, 0);<br> }<br> }<br> fillWithNewValue();<br> fillWithNewValue(); <br> }<br><br> public void printBoard() {<br> for (int i = 0; i < 4; i++) {<br> for (int j = 0; j < 4; j++) {<br> System.out.printf("%4d",board[i][j].getValue());<br> }<br> System.out.println();<br> }<br> }<br><br> public void giveHint() {<br> System.out.println("Available moves: ");<br> findEmptySpaces();<br> for (Tile t : emptySpaces) {<br> System.out.println("Row is " + t.getRow() + ", column is " + t.getCol() + ", value is " + t.getValue());<br> }<br> }<br><br> private void findEmptySpaces() {<br> emptySpaces.clear();<br> for (int i = 0; i < 4; i++) {<br> for (int j = 0; j < 4; j++) {<br> if (board[i][j].getValue() == 0) {<br> emptySpaces.add(board[i][j]);<br> }<br> }<br> }<br> }<br><br> private void fillWithNewValue() {<br> findEmptySpaces();<br> Tile emptyTile = (Tile) emptySpaces.get((int) (Math.random() * emptySpaces.size()));<br> emptyTile.setValue(2);<br> }<br>}<br>```<br><br>and <br><br>```java<br>public class Tile {<br> private final int row;<br> private final int column;<br> private int value;<br><br> public Tile(int row, int column, int value) {<br> this.row = row;<br> this.column = column;<br> this.value = value;<br> }<br><br> public int getValue() {<br> return value;<br> }<br><br> public int getRow() {<br> return row;<br> }<br><br> public int getCol() {<br> return column;<br> }<br><br> public void setValue(int val) {<br> value = val;<br> }<br><br> public void moveTo(Tile t) {<br> t.setValue(value);<br> setValue(0);<br> }<br><br> public void mergeWith(Tile t) {<br> t.setValue(value + t.getValue());<br> setValue(0);<br> }<br>}<br>```<br><br>I want to add the ability that when i press 'w', the tiles should move up, when i press 's', the tiles should move down and etc. But i cant seem to figure it out, can someone help? I am not sure where to start from as i am a beginner in Java.
Comments (3) 5411 👁️