public void update() { welcomeLabel.setText("Welcome! You have " + credits + " credits."); if (game != null) { GameSquare gs = game.getGameSquareAt(leftClickRow, leftClickCol); if (game.getWinner() != -1) { gamePanel.add(returnToMenuButton); if (hasWon) gameInfo.setText("You won!"); else gameInfo.setText("You lost."); } else if (gs.hasOccupant()) { Occupant o = gs.getOccupant(); if (o instanceof Unit) { Unit u = (Unit) o; gameInfo.setText(u.getInfo()); } else gameInfo.setText(o.toString()); itemListModel.removeAllElements(); if (o instanceof Unit) { List<Item> list = ((Unit) o).getItemList(); for (Item i : list) { itemListModel.addElement(i); } } } else { gameInfo.setText("Empty"); } boardPanel.repaint(); } }
/** Starts the game running. */ private void startGame() { /* * Initialize everything we're going to be using. */ this.random = new Random(); this.snake = new LinkedList<>(); this.directions = new LinkedList<>(); this.logicTimer = new Clock(9.0f); this.isNewGame = true; // Set the timer to paused initially. logicTimer.setPaused(true); /* * This is the game loop. It will update and render the game and will * continue to run until the game window is closed. */ while (true) { // Get the current frame's start time. long start = System.nanoTime(); // Update the logic timer. logicTimer.update(); /* * If a cycle has elapsed on the logic timer, then update the game. */ if (logicTimer.hasElapsedCycle()) { updateGame(); } // Repaint the board and side panel with the new content. board.repaint(); side.repaint(); /* * Calculate the delta time between since the start of the frame * and sleep for the excess time to cap the frame rate. While not * incredibly accurate, it is sufficient for our purposes. */ long delta = (System.nanoTime() - start) / 1000000L; if (delta < FRAME_TIME) { try { Thread.sleep(FRAME_TIME - delta); } catch (Exception e) { e.printStackTrace(); } } } }
/** Draws the next frame, i.e. refreshes the scores and game. */ private void nextFrame() { boardPanel.repaint(); scorePanel.refresh(); }