Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- public class JBrainTetris extends JTetris {
- private JCheckBox brainMode;
- private Brain brain;
- private Piece lastPiece;
- private Brain.Move move;
- private JLabel status;
- private JPanel little;
- private JSlider adversary;
- /**
- * Creates a new JTetris where each tetris square
- * is drawn with the given number of pixels.
- *
- * @param pixels
- */
- JBrainTetris(int pixels) {
- super(pixels);
- this.brain = new DefaultBrain();
- this.lastPiece = null;
- }
- @Override
- public JComponent createControlPanel() {
- JPanel panel = (JPanel) super.createControlPanel();
- // Brain checkbox
- panel.add(new JLabel("Brain:"));
- brainMode = new JCheckBox("Brain active");
- panel.add(brainMode);
- // make a little panel, put a JSlider in it. JSlider responds to getValue()
- little = new JPanel();
- little.add(new JLabel("Adversary:"));
- adversary = new JSlider(0, 100, 0); // min, max, current
- adversary.setPreferredSize(new Dimension(100, 15));
- little.add(adversary);
- // now add little to panel of controls
- panel.add(little);
- // Status label
- status = new JLabel("OK");
- panel.add(status);
- return panel;
- }
- @Override
- public Piece pickNextPiece() {
- int randVal = 1 + random.nextInt(99);
- if (adversary.getValue() <= randVal) {
- status.setText("OK");
- return super.pickNextPiece();
- }
- double score = Integer.MIN_VALUE;
- Piece resPiece = null;
- for (Piece piece : super.pieces) {
- board.undo();
- Brain.Move testMove = brain.bestMove(this.board, piece, board.getHeight(), null);
- if (testMove.score > score) {
- score = testMove.score;
- resPiece = piece;
- }
- }
- status.setText("*OK*");
- return resPiece;
- }
- @Override
- public void tick(int verb) {
- if (brainMode.isSelected()) {
- if (this.currentPiece != lastPiece) {
- board.undo();
- move = brain.bestMove(this.board, this.currentPiece, board.getHeight(), null);
- lastPiece = this.currentPiece;
- }
- if (move != null) {
- if (!move.piece.equals(this.currentPiece)) {
- super.tick(ROTATE);
- }
- int dx = move.x - this.currentX;
- if (dx != 0) {
- super.tick((dx > 0) ? RIGHT : LEFT);
- }
- }
- }
- super.tick(verb);
- }
- public static void main(String[] args) {
- // Set GUI Look And Feel Boilerplate.
- // Do this incantation at the start of main() to tell Swing
- // to use the GUI LookAndFeel of the native platform. It's ok
- // to ignore the exception.
- try {
- UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
- } catch (Exception ignored) {
- }
- JTetris tetris = new JBrainTetris(16);
- JFrame frame = JTetris.createFrame(tetris);
- frame.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement