📄 jcontrolpanel.java
字号:
package cs111.tetris.gui;import java.awt.Dimension;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Box;import javax.swing.BoxLayout;import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JSlider;import javax.swing.KeyStroke;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;import cs111.tetris.brain.Brain;import cs111.tetris.brain.LameBrain;import cs111.tetris.brain.Brain.Move;import cs111.tetris.data.Game;import cs111.tetris.data.GameListener;/** * A JControlPanel instance represents the Control panel that controls * an instance of JGame (a tetris board/game). * It calls methods on the JBoard class to make the * game piece move down left, right etc. */public class JControlPanel extends JPanel implements GameListener { // The UI component that draws the tetris board. private Game game; // State of the game private long startTime; // used to measure elapsed time // Controls private JLabel countLabel; private JLabel timeLabel; private JButton startButton; private JButton stopButton; private JButton pauseButton = null; private javax.swing.Timer timer; private JSlider speed; private JLabel brainVersionLabel; private JCheckBox brainOnCheckBox; // The (optional) Brain and some related state private Move target = null; private Brain brain = new LameBrain(); private final int DELAY = 400; // milliseconds per tick /** * Create a JTetrisController for a given tetris game. * * @param aGame The object representing the state the tetris game. */ public JControlPanel(Game aGame) { super(); this.game = aGame; boolean testing = game.isTestMode(); /* Register key handlers that call game.doMove with the appropriate constant. e.g. 'j' and '4' call game.doMove(LEFT) */ // LEFT registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_LEFT); } }, "left", KeyStroke.getKeyStroke('4'), WHEN_IN_FOCUSED_WINDOW ); registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_LEFT); } }, "left", KeyStroke.getKeyStroke('j'), WHEN_IN_FOCUSED_WINDOW ); // RIGHT registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_RIGHT); } }, "right", KeyStroke.getKeyStroke('6'), WHEN_IN_FOCUSED_WINDOW ); registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_RIGHT); } }, "right", KeyStroke.getKeyStroke('l'), WHEN_IN_FOCUSED_WINDOW ); // ROTATE registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_ROTATE); } }, "rotate", KeyStroke.getKeyStroke('5'), WHEN_IN_FOCUSED_WINDOW ); registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_ROTATE); } }, "rotate", KeyStroke.getKeyStroke('k'), WHEN_IN_FOCUSED_WINDOW ); // DROP registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_DROP); } }, "drop", KeyStroke.getKeyStroke('0'), WHEN_IN_FOCUSED_WINDOW ); registerKeyboardAction( new ActionListener() { public void actionPerformed(ActionEvent e) { game.doMove(Game.VERB_DROP); } }, "drop", KeyStroke.getKeyStroke('n'), WHEN_IN_FOCUSED_WINDOW ); // Create the Timer object and have it call // game.doMove(DOWN) periodically. timer = new javax.swing.Timer(DELAY, new ActionListener() { public void actionPerformed(ActionEvent e) { brainActivity(); // If the AI is active... let it do something here. game.doMove(Game.VERB_DOWN); } }); createControlPanel(testing); game.addListener(this); } private void brainActivity() { if (target!=null && target.y<game.getCurrentY()) { if (target.piece!=game.getCurrentPiece()) game.doMove(Game.VERB_ROTATE); else if (target.x<game.getCurrentX()) game.doMove(Game.VERB_LEFT); else if (target.x>game.getCurrentX()) { game.doMove(Game.VERB_RIGHT); } else game.doMove(Game.VERB_DROP); } } private void brainSetNewTarget() { if (!isBrainActive() || game.getCurrentPiece()==null) { target = null; return; } target = brain.bestMove(game.getBoard(), game.getCurrentPiece(), game.getHeight(), target); } private boolean isBrainActive() { return brainOnCheckBox.isSelected(); } /** Sets the internal state and starts the timer so the game is happening. */ public void startGame() { game.startGame(); } /** Sets the internal state and starts the timer so the game is happening. */ public void pauseOrResumeGame() { if (timer.isRunning()) timer.stop(); else timer.start(); } /** Sets the enabling of the start/stop buttons based on the gameOn state. */ private void enableButtons() { startButton.setEnabled(!game.isGameOn()); stopButton.setEnabled(game.isGameOn()); if (pauseButton!=null) { pauseButton.setEnabled(game.isGameOn()); } } /** Stops the game. */ public void stopGame() { game.stopGame(); } /** Updates the timer to reflect the current setting of the speed slider. */ public void updateTimer() { double value = ((double)speed.getValue())/speed.getMaximum(); timer.setDelay((int)(DELAY - value*DELAY)); } /** Sets up the panel of UI controls. Creates all buttons, slider etc. */ private void createControlPanel(boolean testMode) { this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS)); /////////////////////////// // COUNT countLabel = new JLabel("0000000"); add(countLabel); /////////////////////////// // TIME timeLabel = new JLabel("Time will be displayed here"); add(timeLabel); add(Box.createVerticalStrut(12)); /////////////////////////// // START button startButton = new JButton("Start"); add(startButton); startButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { startGame(); } }); /////////////////////////// // STOP button stopButton = new JButton("Stop"); add(stopButton); stopButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { stopGame(); } }); /////////////////////////// // PAUSE button if (game.isTestMode()) { pauseButton = new JButton("Pause/Resume"); add(pauseButton); pauseButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { pauseOrResumeGame(); } }); } enableButtons(); /////////////////////////// // SPEED slider add(Box.createVerticalStrut(12)); JPanel row = new JPanel(); row.add(new JLabel("Speed:")); speed = new JSlider(0, 200, 75); // min, max, current speed.setPreferredSize(new Dimension(100,15)); if (testMode) speed.setValue(200); // max for test mode updateTimer(); row.add(speed); add(row); speed.addChangeListener( new ChangeListener() { // when the slider changes, sync the timer to its value public void stateChanged(ChangeEvent e) { updateTimer(); } }); //////////////////////////// // BRAIN ON checkbox // add(Box.createVerticalStrut(12)); brainOnCheckBox = new JCheckBox("Brain active"); brainOnCheckBox.setSelected(testMode); add(brainOnCheckBox); brainOnCheckBox.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { if (isBrainActive()) { brainSetNewTarget(); } else { target = null; } } }); ///////////////////////////// // BRAIN VERSION info label add(Box.createVerticalStrut(12)); brainVersionLabel = new JLabel(brain.getVersionInfo()); add(brainVersionLabel); add(Box.createVerticalStrut(12)); } /** * Replace the default brain with one of your own choice. * * @param brain */ public void setBrain(Brain brain) { this.brain = brain; brainVersionLabel.setText(brain.getVersionInfo()); } //////////////////////////////////////////////////////////////////////// /// Listener methods below (they implement the GameListener interface) /// /// These methods get called by the game (cs111.tetris.data.Game instance) /// /** * This method is called when the contents of the board changed. */ public void boardChanged() { //Controller doesn't care: do nothing } /** * This method is called when the number pieces in the gamestate * has changed. Typically this means a new piece came into play. */ public void countChanged() { countLabel.setText(""+game.getCount()); // update the text field // that displays the count on the screen. brainSetNewTarget(); // Robot player has to compute the "best move" to // play the new piece. } public void gameOnChanged() { enableButtons(); if (game.isGameOn()) { // game was started startTime = System.currentTimeMillis(); timer.start(); timeLabel.setText(""); } else { // game was ended timer.stop(); long delta = (System.currentTimeMillis() - startTime)/10; timeLabel.setText(Double.toString(delta/100.0) + " seconds"); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -