diff --git a/2048/2048/src/main/java/com/tpcstld/twozerogame/MainGame.java b/2048/2048/src/main/java/com/tpcstld/twozerogame/MainGame.java index ff729af..05ab144 100644 --- a/2048/2048/src/main/java/com/tpcstld/twozerogame/MainGame.java +++ b/2048/2048/src/main/java/com/tpcstld/twozerogame/MainGame.java @@ -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; @@ -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 @@ -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; @@ -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); } @@ -223,7 +244,7 @@ public void move(int direction) { if (moved) { saveUndoState(); - addRandomTile(); + spawnTile(getBufferedRandomTile(direction)); checkLose(); } mView.resyncTime();