/** Spawns a new fruit onto the board. */ private void spawnFruit() { // Reset the score for this fruit to 100. this.nextFruitScore = 100; /* * Get a random index based on the number of free spaces left on the board. */ int index = random.nextInt(BoardPanel.COL_COUNT * BoardPanel.ROW_COUNT - snake.size()); /* * While we could just as easily choose a random index on the board * and check it if it's free until we find an empty one, that method * tends to hang if the snake becomes very large. * * This method simply loops through until it finds the nth free index * and selects uses that. This means that the game will be able to * locate an index at a relatively constant rate regardless of the * size of the snake. */ int freeFound = -1; for (int x = 0; x < BoardPanel.COL_COUNT; x++) { for (int y = 0; y < BoardPanel.ROW_COUNT; y++) { TileType type = board.getTile(x, y); if (type == null || type == TileType.Fruit) { if (++freeFound == index) { board.setTile(x, y, TileType.Fruit); break; } } } } }
/** Resets the game's variables to their default states and starts a new game. */ private void resetGame() { /* * Reset the score statistics. (Note that nextFruitPoints is reset in * the spawnFruit function later on). */ this.score = 0; this.fruitsEaten = 0; /* * Reset both the new game and game over flags. */ this.isNewGame = false; this.isGameOver = false; /* * Create the head at the center of the board. */ Point head = new Point(BoardPanel.COL_COUNT / 2, BoardPanel.ROW_COUNT / 2); /* * Clear the snake list and add the head. */ snake.clear(); snake.add(head); /* * Clear the board and add the head. */ board.clearBoard(); board.setTile(head, TileType.SnakeHead); /* * Clear the directions and add north as the * default direction. */ directions.clear(); directions.add(Direction.North); /* * Reset the logic timer. */ logicTimer.reset(); /* * Spawn a new fruit. */ spawnFruit(); }
/* * (non-Javadoc) * * @see org.ozsoft.texasholdem.Client#act(java.util.Set) */ public Action act(Set<Action> allowedActions) { boardPanel.setMessage("Please select an action."); Action action = controlPanel.getUserInput(allowedActions); controlPanel.waitForUserInput(); this.pack(); return action; }
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(); } }
@Override public void playerActed(Player player) { String name = player.getName(); PlayerPanel playerPanel = playerPanels.get(name); if (playerPanel != null) { playerPanel.update(player); Action action = player.getAction(); if (action != null) { boardPanel.setMessage(String.format("%s %s.", name, action.getVerb())); if (player.getClient() != this) { boardPanel.waitForUserInput(); } } } else { throw new IllegalStateException(String.format("No PlayerPanel found for player '%s'", name)); } }
/* * (non-Javadoc) * * @see * org.ozsoft.texasholdem.Client#playerActed(org.ozsoft.texasholdem.Player) */ public void playerActed(Player player) { String name = player.getName(); PlayerPanel playerPanel = playerPanels.get(name); if (playerPanel != null) { playerPanel.update(player); Action action = player.getAction(); if (action != null) { boardPanel.setMessage(String.format("%s %s.", name, action.getVerb())); // FIXME: Determine whether actor is the human player (not by // name). if (!name.equals(thisPlayer)) { boardPanel.waitForUserInput(); this.pack(); } } } else { throw new IllegalStateException(String.format("No PlayerPanel found for player '%s'", name)); } }
public MainWindow() { initComponents(); bp = new BoardPanel(mainBoard.getSize(), this); javax.swing.GroupLayout mainBoardLayout = new javax.swing.GroupLayout(bp); bp.setLayout(mainBoardLayout); mainBoard.setLayout(new GridLayout(1, 1)); mainBoard.add(bp); // bp.setPreferredSize(mainBoard.getSize()); mainBoard.repaint(); // }
@Test public void testButtonsPlacedOnPanel() { CardButton[] buttons = boardPanel.getButtons(); assertEquals("board panel contain 5 components", 5, buttons.length); assertEquals( "1-st component on hand panel is card button", CardLargeButton.class, buttons[0].getClass()); assertEquals( "last component on hand panel is card button", CardLargeButton.class, buttons[buttons.length - 1].getClass()); }
/** 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(); } } } }
/** Change the currently displayed board. Pass -1 for no board displayed. */ protected void setCurrentBoard(int index) { if (moveList.getSelectedIndex() != index) { moveList.setSelectedIndex(index); moveList.ensureIndexIsVisible(index); } // If a move was requested, but we're changing from the // last board, cancel the request if (userMoveRequested && index != boardHistory.size() - 1) { boardPanel.cancelMoveRequest(); userMoveRequested = false; } if (currentBoard != index) { currentBoard = index; // Might be no board, index -1 if (index < 0) { boardPanel.setCurrentBoard(null); fromHereAction.setEnabled(false); } else { Board b = (Board) boardHistory.get(index); // Might be the last board, in which case there is no // matching board in the list if (b == null) b = (Board) boardHistory.get(boardHistory.size() - 1); boardPanel.setCurrentBoard(b); fromHereAction.setEnabled( b != null && b.getWinner() == Board.NOBODY && b.getTurnsPlayed() > 0 && server == null); } backAction.setEnabled(index > 0); firstAction.setEnabled(index > 0); fwdAction.setEnabled(index < boardHistory.size() - 1); lastAction.setEnabled(index < boardHistory.size() - 1); } // If we need a move, and this is the last board, request it if (userMoveNeeded && index == boardHistory.size() - 1 && !userMoveRequested) { boardPanel.requestMove(this); userMoveRequested = true; } }
@Test public void testBoardCardContainLargeIconOfCard() { CardButton[] buttons = boardPanel.getButtons(); cardButton = buttons[0]; Card card = cardButton.getCard(); String path = cardButton.getIconPath() + (card.getRevertedName() + ".gif"); java.net.URL imgURL = getClass().getResource(path); ImageIcon icon = new ImageIcon(imgURL, card.toString()); assertTrue( "button have large image icon", ((ImageIcon) cardButton.getIcon()).getImage().equals(icon.getImage())); }
/** Called by server on game start */ void gameStarted(Board b, int gameID, String[] players) { clearData(); getContentPane().remove(boardPanel); boardPanel = b.createBoardPanel(); boardPanel.setPreferredSize(new Dimension(BOARD_SIZE, BOARD_SIZE)); getContentPane().add(boardPanel, BorderLayout.CENTER); pack(); repaint(); StringBuffer title = new StringBuffer("Game " + gameID + ": "); for (int i = 0; i < players.length; i++) title.append(players[i] + (i < players.length - 1 ? " vs. " : "")); this.setTitle(title.toString()); this.board = b; boardUpdated(b, null); setCurrentBoard(0); enableLaunchActions(false); enableServerActions(false); openAction.setEnabled(false); closeAction.setEnabled(false); killServerAction.setEnabled(true); statusLabel.setText("Game in progress, " + board.getNameForID(board.getTurn()) + " to play."); }
public ServerGUI() { // This constructor just builds the GUI, nothing // very interresting here... super("Board Game"); currentBoard = -1; this.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // Define some menu/toolbar actions firstAction = new AbstractAction("First move", new ImageIcon("image/first.png")) { public void actionPerformed(ActionEvent arg0) { setCurrentBoard(0); } }; backAction = new AbstractAction("Prev. move", new ImageIcon("image/prev.png")) { public void actionPerformed(ActionEvent arg0) { setCurrentBoard(currentBoard - 1); } }; fwdAction = new AbstractAction("Next move", new ImageIcon("image/next.png")) { public void actionPerformed(ActionEvent arg0) { setCurrentBoard(currentBoard + 1); } }; lastAction = new AbstractAction("Last move", new ImageIcon("image/last.png")) { public void actionPerformed(ActionEvent arg0) { setCurrentBoard(boardHistory.size() - 1); } }; openAction = new AbstractAction("Open log...") { public void actionPerformed(ActionEvent ev) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(Server.LOG_DIR)); chooser.setFileFilter( new FileFilter() { public boolean accept(File arg0) { return arg0.isDirectory() || arg0.getName().endsWith(".log"); } public String getDescription() { return "Board game log files"; } }); int returnVal = chooser.showOpenDialog(theFrame); if (returnVal == JFileChooser.APPROVE_OPTION) { try { clearData(); loadLogFile(chooser.getSelectedFile().getAbsolutePath()); } catch (Exception e) { JOptionPane.showMessageDialog(theFrame, e, "Load Error", JOptionPane.ERROR_MESSAGE); } } } }; closeAction = new AbstractAction("Close log") { public void actionPerformed(ActionEvent ev) { clearData(); } }; lastAction.setEnabled(false); firstAction.setEnabled(false); backAction.setEnabled(false); fwdAction.setEnabled(false); closeAction.setEnabled(false); // An action to launch a human player playAsAction = new AbstractAction("Launch human player") { public void actionPerformed(ActionEvent arg0) { // Diable this action enableLaunchActions(false); // Create and lauch a new client Client c = new Client(theHumanPlayer, server.getHostName(), server.getPort()); (new Thread(c)).start(); } }; // An action to terminate the server killServerAction = new AbstractAction("End game") { public void actionPerformed(ActionEvent e) { server.killServer(); } }; killServerAction.setEnabled(false); // An action to start a server JMenu launchMenu = new JMenu("Launch"); launchMenu.add(playAsAction); launchMenu.addSeparator(); clientActions = new AbstractAction[PLAYER_CLASSES.length]; for (int i = 0; i < PLAYER_CLASSES.length; i++) { clientActions[i] = new LaunchClientAction(PLAYER_CLASSES[i]); clientActions[i].setEnabled(false); launchMenu.add(clientActions[i]); } launchMenu.addSeparator(); serverActions = new AbstractAction[BOARD_CLASSES.length]; for (int i = 0; i < BOARD_CLASSES.length; i++) { serverActions[i] = new LaunchServerAction(BOARD_CLASSES[i]); launchMenu.add(serverActions[i]); } launchMenu.addSeparator(); fromHereAction = new AbstractAction("Launch server from current position") { public void actionPerformed(ActionEvent arg0) { try { Board bd = (Board) boardHistory.get(currentBoard); int currentMove = currentBoard; // The current move might be the special 'null' at the // end of the list used to display the outcome if (currentMove == moveHistory.size() - 1 && moveHistory.get(currentMove) == null) currentMove--; if (bd == null || currentMove < 1 || bd.getWinner() != Board.NOBODY) throw new IllegalStateException("Can't start game from move " + currentMove); Object[] h = moveHistory.subList(1, currentMove + 1).toArray(); Move[] hist = new Move[h.length]; for (int i = 0; i < h.length; i++) hist[i] = (Move) h[i]; clearData(); ; java.lang.reflect.Constructor co = bd.getClass().getConstructor(new Class[0]); Board b = (Board) co.newInstance(new Object[0]); Server svr = new Server(b, false, true, Server.DEFAULT_PORT, Server.DEFAULT_TIMEOUT); svr.setHistory(hist); setServer(svr); svr.setGUI(theFrame); (new Thread(svr)).start(); } catch (Exception ex) { System.err.println("Error launching server:"); ex.printStackTrace(); } } }; fromHereAction.setEnabled(false); launchMenu.add(fromHereAction); launchMenu.addSeparator(); launchMenu.add(killServerAction); enableLaunchActions(false); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.add(openAction); fileMenu.add(closeAction); menuBar.add(fileMenu); JMenu histMenu = new JMenu("History"); histMenu.add(firstAction); histMenu.add(backAction); histMenu.add(fwdAction); histMenu.add(lastAction); menuBar.add(histMenu); menuBar.add(launchMenu); JToolBar toolBar = new JToolBar("History"); toolBar.add(firstAction); toolBar.add(backAction); toolBar.add(fwdAction); toolBar.add(lastAction); toolBar.setFloatable(false); this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.getContentPane().add(toolBar, BorderLayout.NORTH); boardPanel.setPreferredSize(new Dimension(BOARD_SIZE, BOARD_SIZE)); this.getContentPane().add(boardPanel, BorderLayout.CENTER); moveList = new JList(moveListModel); moveList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); moveList.addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { int idx = moveList.getSelectedIndex(); if (idx >= 0 && idx < moveHistory.size() && idx != currentBoard) setCurrentBoard(idx); } }); JScrollPane movePane = new JScrollPane(moveList); movePane.setPreferredSize(new Dimension(LIST_WIDTH, BOARD_SIZE)); this.getContentPane().add(movePane, BorderLayout.EAST); statusLabel = new JLabel("GUI Loaded"); this.getContentPane().add(statusLabel, BorderLayout.SOUTH); }
@Override public Action act(int minBet, int currentBet, Set<Action> allowedActions) { boardPanel.setMessage("Please select an action:"); return controlPanel.getUserInput(minBet, humanPlayer.getCash(), allowedActions); }
private void jMenuItem2ActionPerformed( java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItem2ActionPerformed bp.playSolo(); } // GEN-LAST:event_jMenuItem2ActionPerformed
private void mainBoardMouseClicked( java.awt.event.MouseEvent evt) { // GEN-FIRST:event_mainBoardMouseClicked bp.mouseClicked(evt); } // GEN-LAST:event_mainBoardMouseClicked
public GUI() { super(); try { sprites = ImageIO.read(new File("Sprites2.png")); } catch (IOException e) { e.printStackTrace(); } lowerPane.setPreferredSize(new Dimension(384, 130)); gameInfo.setEditable(false); boardPanel.setPreferredSize(new Dimension(384, 384)); boardPanel.addMouseListener(new gameMouseListener()); boardPanel.setBackground(Color.cyan); itemList.setPreferredSize(new Dimension(384, 80)); gamePanel.setPreferredSize(new Dimension(400, 700)); gamePanel.add(boardPanel); lowerPane.add("Info", gameInfo); chatPanel.setLayout(new BorderLayout()); chatPanel.add(chatScrollPane, BorderLayout.CENTER); chatScrollPane.setVerticalScrollBar(new JScrollBar()); chatArea.setEditable(false); chatPanel.add(chatField, BorderLayout.SOUTH); lowerPane.add("Chat", chatPanel); gamePanel.add(lowerPane); gamePanel.add(endTurnButton); gamePanel.add(itemList); gamePanel.add(useItemButton); gamePanel.add(surrenderButton); // login panel newAccountButton.addActionListener(new CreateAccountListener()); failedLoginPanel.add(tryNewUser); failedLoginPanel.add(newAccountButton); loginButton.addActionListener(new LoginListener()); loginPanel.setLayout(new GridLayout(2, 2)); usernameHere.setEditable(false); passwordHere.setEditable(false); loginPanel.add(usernameHere); loginPanel.add(username); loginPanel.add(passwordHere); loginPanel.add(password); logisticsPanel.setPreferredSize(new Dimension(350, 300)); loginButtonPanel.add(loginButton); logisticsPanel.add(loginPanel); logisticsPanel.add(loginButtonPanel); logisticsPanel.add(failedLoginPanel); mainPanel.add(logisticsPanel); possibleUnitList.setPreferredSize(new Dimension(200, 104)); userUnitList.setPreferredSize(new Dimension(200, 87)); setuploadoutPanel(); setupGameRoomLobby(); setupMainOptionsPanel(); setUpUserInfoPanel(); mainFrame.setResizable(false); mainFrame.add(mainPanel); mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); mainFrame.setSize(800, 800); mainFrame.setVisible(true); setListeners(); }
public void updateSize() { height = myBoardPanel.getHeight() / myBoardPanel.squaresInColumn; width = myBoardPanel.getWidth() / myBoardPanel.squaresInRow; startY = column * height; startX = row * width; }
/** * Updates the snake's position and size. * * @return Tile tile that the head moved into. */ private TileType updateSnake() { /* * Here we peek at the next direction rather than polling it. While * not game breaking, polling the direction here causes a small bug * where the snake's direction will change after a game over (though * it will not move). */ Direction direction = directions.peekFirst(); /* * Here we calculate the new point that the snake's head will be at * after the update. */ Point head = new Point(snake.peekFirst()); switch (direction) { case North: head.y--; break; case South: head.y++; break; case West: head.x--; break; case East: head.x++; break; } /* * If the snake has moved out of bounds ('hit' a wall), we can just * return that it's collided with itself, as both cases are handled * identically. */ if (head.x < 0 || head.x >= BoardPanel.COL_COUNT || head.y < 0 || head.y >= BoardPanel.ROW_COUNT) { return TileType.SnakeBody; // Pretend we collided with our body. } /* * Here we get the tile that was located at the new head position and * remove the tail from of the snake and the board if the snake is * long enough, and the tile it moved onto is not a fruit. * * If the tail was removed, we need to retrieve the old tile again * incase the tile we hit was the tail piece that was just removed * to prevent a false game over. */ TileType old = board.getTile(head.x, head.y); if (old != TileType.Fruit && snake.size() > MIN_SNAKE_LENGTH) { Point tail = snake.removeLast(); board.setTile(tail, null); old = board.getTile(head.x, head.y); } /* * Update the snake's position on the board if we didn't collide with * our tail: * * 1. Set the old head position to a body tile. * 2. Add the new head to the snake. * 3. Set the new head position to a head tile. * * If more than one direction is in the queue, poll it to read new * input. */ if (old != TileType.SnakeBody) { board.setTile(snake.peekFirst(), TileType.SnakeBody); snake.push(head); board.setTile(head, TileType.SnakeHead); if (directions.size() > 1) { directions.poll(); } } return old; }
public void messageReceived(String message) { boardPanel.setMessage(message); boardPanel.waitForUserInput(); }
/* * (non-Javadoc) * * @see org.ozsoft.texasholdem.Client#boardUpdated(java.util.List, int, int) */ public void boardUpdated(List<Card> cards, int bet, int pot) { boardPanel.update(cards, bet, pot); }
/** Draws the next frame, i.e. refreshes the scores and game. */ private void nextFrame() { boardPanel.repaint(); scorePanel.refresh(); }