Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Buffer new random tiles with direction information #12

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions 2048/2048/src/main/java/com/tpcstld/twozerogame/MainGame.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class MainGame {
public long highScore = 0;
public long lastScore = 0;
private long bufferScore = 0;
private Tile[] bufferTiles = new Tile[4];

public MainGame(Context context, MainView view) {
mContext = context;
Expand Down Expand Up @@ -76,19 +77,30 @@ public void newGame() {
private void addStartTiles() {
int startTiles = 2;
for (int xx = 0; xx < startTiles; xx++) {
this.addRandomTile();
spawnTile(getRandomTile());
}
}

private void addRandomTile() {
private Tile getRandomTile() {
if (grid.isCellsAvailable()) {
int value = Math.random() < 0.9 ? 2 : 4;
Tile tile = new Tile(grid.randomAvailableCell(), value);
spawnTile(tile);
return tile;
}
return null;
}

private Tile getBufferedRandomTile(int direction) {
if (bufferTiles[direction] == null) {
bufferTiles[direction] = getRandomTile();
}
return bufferTiles[direction];
}

private void spawnTile(Tile tile) {
if (tile == null) {
return;
}
grid.insertTile(tile);
aGrid.startAnimation(tile.getX(), tile.getY(), SPAWN_ANIMATION,
SPAWN_ANIMATION_TIME, MOVE_ANIMATION_TIME, null); //Direction: -1 = EXPANDING
Expand Down Expand Up @@ -124,6 +136,9 @@ private void moveTile(Tile tile, Cell cell) {

private void saveUndoState() {
grid.saveTiles();
if (canUndo) {
clearTileBuffer();
}
canUndo = true;
lastScore = bufferScore;
lastGameState = bufferGameState;
Expand All @@ -147,6 +162,12 @@ public void revertUndoState() {
}
}

private void clearTileBuffer() {
for (int i = 0; i < bufferTiles.length; i++) {
bufferTiles[i] = null;
}
}

public boolean gameWon() {
return (gameState > 0 && gameState % 2 != 0);
}
Expand Down Expand Up @@ -223,7 +244,7 @@ public void move(int direction) {

if (moved) {
saveUndoState();
addRandomTile();
spawnTile(getBufferedRandomTile(direction));
checkLose();
}
mView.resyncTime();
Expand Down