/** * This method is called repeatedly so that the game can update its state. * * @param lastKey The most recent keystroke. */ @Override public void gameUpdate(final int lastKey) throws GameOverException { updateDirection(lastKey); // Erase the previous position. GameUtils.setGameboardState(this.collectorPos, BLANK_TILE, this.board); // Change collector position. this.collectorPos = getNextCollectorPos(); if (isOutOfBounds(this.collectorPos)) { throw new GameOverException(this.score); } // Draw collector at new position. GameUtils.setGameboardState(this.collectorPos, COLLECTOR_TILE, this.board); // Remove the coin at the new collector position (if any) if (this.coins.remove(this.collectorPos)) { this.score++; } // Check if all coins are found if (this.coins.isEmpty()) { throw new GameOverException(this.score + 5); } // Remove one of the coins Position oldCoinPos = this.coins.get(0); this.coins.remove(0); GameUtils.setGameboardState(oldCoinPos, BLANK_TILE, this.board); // Add a new coin (simulating moving one coin) addCoin(); }
/** Create a new model for the gold game. */ public GoldModel() { Dimension size = GameUtils.getGameboardSize(); // create a new gameboard and fill it with BLANK_TILE board = new GameTile[size.width][size.height]; GameUtils.fillBoard(board, BLANK_TILE); // Insert the collector in the middle of the gameboard. this.collectorPos = new Position(size.width / 2, size.height / 2); GameUtils.setGameboardState(collectorPos, COLLECTOR_TILE, board); // Insert coins into the gameboard. for (int i = 0; i < COIN_START_AMOUNT; i++) { addCoin(); } // TODO remove System.out.println("GoldModel in orig2011.v3"); }
/** Insert another coin into the gameboard. */ private void addCoin() { Position newCoinPos; Dimension size = Constants.getGameSize(); // Loop until a blank position is found and ... do { newCoinPos = new Position((int) (Math.random() * size.width), (int) (Math.random() * size.height)); } while (!isPositionEmpty(newCoinPos)); // ... add a new coin to the empty tile. GameUtils.setGameboardState(newCoinPos, COIN_TILE, board); this.coins.add(newCoinPos); }