/** @see also scrabble.game.Game.getBestMove(String letters) */ private void getBestMove() { if (letters == null || letters.isEmpty()) { requestLettersInHand(); } SwingUtilities.invokeLater( () -> { game.getBestMove(UI.this, letters); }); }
/** Opens a dialogue and prompts the user to select a game to load. */ private void loadGame() { final int returnVal = fileChooser.showDialog(this, "Load"); if (returnVal == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); if (fileChooser.accept(file)) { IO.loadTiles(game.getBoard(), file); } } }
/** Constructs a new UI. */ public UI() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ignored) { } setTitle("ScrabbleBot"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fileChooser.setFileHidingEnabled(true); fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.setFileFilter(fileExtensionFilter); fileChooser.setAcceptAllFileFilterUsed(false); menuBar.setLayout(new GridLayout(1, 5)); bestMove.addActionListener(UI.this); bestMove.setFocusable(false); menuBar.add(bestMove); tilesInHand.addActionListener(UI.this); tilesInHand.setFocusable(false); menuBar.add(tilesInHand); newGame.addActionListener(UI.this); newGame.setFocusable(false); menuBar.add(newGame); loadGame.addActionListener(UI.this); loadGame.setFocusable(false); menuBar.add(loadGame); saveGame.addActionListener(UI.this); saveGame.setFocusable(false); menuBar.add(saveGame); setJMenuBar(menuBar); add(game.getBoard()); addWindowListener( new WindowAdapter() { @Override public void windowClosing(final WindowEvent e) { if (game.getBoard().hasValidContent()) { saveGame(); } } }); pack(); setLocationRelativeTo(getOwner()); setResizable(false); setVisible(true); }
@Override public void actionPerformed(final ActionEvent e) { if (e.getSource() instanceof JButton) { final JButton button = (JButton) e.getSource(); if (button == bestMove) { getBestMove(); } else if (button == tilesInHand) { requestLettersInHand(); } else if (button == newGame) { game.getBoard().clear(); } else if (button == loadGame) { loadGame(); } else if (button == saveGame) { saveGame(); } } }
/** Opens a dialogue and prompts the user to select a file to save the current game to. */ private void saveGame() { if (fileChooser.showDialog(this, "Save") == JFileChooser.APPROVE_OPTION) IO.saveTiles(game.getBoard(), fileChooser.getSelectedFile()); }