View Single Post
Old Mar 11th, 2008, 12:40 PM   #5
Cutiecutie
Newbie
 
Join Date: Mar 2008
Posts: 2
Rep Power: 0 Cutiecutie is on a distinguished road
Re: Need help in JAVA

import java.awt.Button;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


public class Game extends Object {
	protected javax.swing.Timer timer;
        protected long startTime;

    private SquareBoard board = null;

    private SquareBoard previewBoard = new SquareBoard(5, 5);


    private Figure[] figures = {
        new Figure(Figure.SQUARE_FIGURE),
        new Figure(Figure.LINE_FIGURE),
        new Figure(Figure.S_FIGURE),
        new Figure(Figure.Z_FIGURE),
        new Figure(Figure.RIGHT_ANGLE_FIGURE),
        new Figure(Figure.LEFT_ANGLE_FIGURE),
        new Figure(Figure.TRIANGLE_FIGURE)
    };


    private GamePanel component = null;

    private GameThread thread = null;


    private int level = 1;

    private int score = 0;


    private Figure figure = null;

    private Figure nextFigure = null;

    private int nextRotation = 0;


    private boolean preview = true;


    private boolean moveLock = false;

    public Game() {
        this(10, 20);
    }


    public Game(int width, int height) {
        board = new SquareBoard(width, height);
        board.setMessage("Press start");
        thread = new GameThread();
    }


    public void quit() {
        thread = null;
    }


    public Component getComponent() {
        if (component == null) {
            component = new GamePanel();
        }
        return component;
    }

    
    private void handleStart() {

        // Reset score and figures
        level = 1;
        score = 0;
        figure = null;
        nextFigure = randomFigure();
        nextFigure.rotateRandom();
        nextRotation = nextFigure.getRotation();  

        // Reset components
        board.setMessage(null);
        board.clear();
        previewBoard.clear();
        handleLevelModification();
        handleScoreModification();
        component.button.setLabel("Pause");

        // Start game thread
        thread.reset();
    }


    private void handleGameOver() {
        handleTimeModification();
        // Stop game thred
        thread.setPaused(true);

        // Reset figures
        if (figure != null) {
            figure.detach();
        }
        figure = null;
        if (nextFigure != null) {
            nextFigure.detach();
        }
        nextFigure = null;

        // Handle components
        board.setMessage("Game Over");
        component.button.setLabel("Start");
    }

    private void handlePause() {
        thread.setPaused(true);
        board.setMessage("Paused");
        component.button.setLabel("Resume");
    }

    private void handleResume() {
        board.setMessage(null);
        component.button.setLabel("Pause");
        thread.setPaused(false);
    }

    private void handleLevelModification() {
        component.levelLabel.setText("Level: " + level);
        thread.adjustSpeed();
  

    }
    
 
    private void handleScoreModification() {
        component.scoreLabel.setText("Score: " + score);
    }
    
    private void handleTimeModification () {
        long delta = (System.currentTimeMillis() - startTime)/10;
        component.timeLabel.setText("Time: " + Double.toString(delta/100.0) + " seconds");
    }

    private void handleFigureStart() {
        int  rotation;


        // Move next figure to current
        figure = nextFigure;
        moveLock = false;
        rotation = nextRotation;
        nextFigure = randomFigure();
        nextFigure.rotateRandom(); 
        nextRotation = nextFigure.getRotation(); 

        // Handle figure preview
        if (preview) {
            previewBoard.clear(); 
            nextFigure.attach(previewBoard, true);
            nextFigure.detach();
        }

        // Attach figure to game board
        figure.setRotation(rotation);
        if (!figure.attach(board, false)) {
            previewBoard.clear();
            figure.attach(previewBoard, true);
            figure.detach();
            handleGameOver();
        }
    }


    private void handleFigureLanded() {

        // Check and detach figure
        if (figure.isAllVisible()) {
            score += 10;
            handleScoreModification();
        } else {
            handleGameOver();
            return;
        }
        figure.detach();
        figure = null;

        // Check for full lines or create new figure
        if (board.hasFullLines()) {
            board.removeFullLines();
            if (level < 9 && board.getRemovedLines() / 20 > level) {
                level = board.getRemovedLines() / 20;
                handleLevelModification();
            }
        } else {
            handleFigureStart();
        }
    }


    private synchronized void handleTimer() {
        if (figure == null) {
            handleFigureStart();

        } else if (figure.hasLanded()) {
            handleFigureLanded();
        } else {
            figure.moveDown();
        }
    }


    private synchronized void handleButtonPressed() {
        if (nextFigure == null) {
            handleStart();
        } else if (thread.isPaused()) {
            handleResume();
        } else {
            handlePause();
        }
    }


    private synchronized void handleKeyEvent(KeyEvent e) {

        // Handle start, pause and resume
        if (e.getKeyCode() == KeyEvent.VK_P) {
            handleButtonPressed();
                                timer.start();
                    startTime = System.currentTimeMillis();
            return;
        }

        // Don't proceed if stopped or paused
        if (figure == null || moveLock || thread.isPaused()) {
            return;
        }

        // Handle remaining key events
        switch (e.getKeyCode()) {

        case KeyEvent.VK_LEFT:
            figure.moveLeft();
            break;

        case KeyEvent.VK_RIGHT:
            figure.moveRight();
            break;

        case KeyEvent.VK_DOWN:
            figure.moveAllWayDown();
            moveLock = true;
            break;

        case KeyEvent.VK_UP:
        case KeyEvent.VK_SPACE:
            if (e.isControlDown()) {
                figure.rotateRandom();  
            } else if (e.isShiftDown()) { 
                figure.rotateClockwise();
            } else {
                figure.rotateCounterClockwise();
            }
            break;

        case KeyEvent.VK_S:
            if (level < 9) {
                level++;
                handleLevelModification();
            }
            break;

        case KeyEvent.VK_N:
            preview = !preview;
            if (preview && figure != nextFigure) {
                nextFigure.attach(previewBoard, true);
                nextFigure.detach(); 
            } else {
                previewBoard.clear();
            }
            break;
        }
    }


    private Figure randomFigure() {
        return figures[(int) (Math.random() * figures.length)];
    }



    private class GameThread extends Thread {

        private boolean paused = true;


        private int sleepTime = 500;

   
        public GameThread() {
        }


        public void reset() {
            adjustSpeed();
            setPaused(false);
            if (!isAlive()) {
                this.start();
            }
        }


        public boolean isPaused() {
            return paused;
        }


        public void setPaused(boolean paused) {
            this.paused = paused;
        }


        public void adjustSpeed() {
            sleepTime = 4500 / (level + 5) - 250;
            if (sleepTime < 50) {
                sleepTime = 50;
            }
        }

        public void run() {
            while (thread == this) {
                // Make the time step
                handleTimer();

                // Sleep for some time
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException ignore) {
                    // Do nothing
                }

                // Sleep if paused
                while (paused && thread == this) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException ignore) {
                        // Do nothing
                    }
                }
            }
        }
    }



    private class GamePanel extends Container {
        

        private Dimension  size = null;

 
        private Label scoreLabel = new Label("Score: 0");

    
        private Label levelLabel = new Label("Level: 1");
        
        private Label timeLabel = new Label("Time: ");

   
        private Button button = new Button("Start");


        public GamePanel() {
            super();
            initComponents();
        }


        public void paint(Graphics g) {
            Rectangle  rect = g.getClipBounds();

            if (size == null || !size.equals(getSize())) {
                size = getSize();
                resizeComponents();
            }
            g.setColor(getBackground());
            g.fillRect(rect.x, rect.y, rect.width, rect.height);
            super.paint(g);
        }
        

        private void initComponents() {
            GridBagConstraints  c;

            // Set layout manager and background
            setLayout(new GridBagLayout());
            setBackground(Configuration.getColor("background", "#d4d0c8"));

            // Add game board
            c = new GridBagConstraints();
            c.gridx = 0;
            c.gridy = 0;
            c.gridheight = 4;
            c.weightx = 1.0;
            c.weighty = 1.0;
            c.fill = GridBagConstraints.BOTH;
            this.add(board.getComponent(), c);

            // Add next figure board
            c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 0;
            c.weightx = 0.2;
            c.weighty = 0.18;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(15, 15, 0, 15);
            this.add(previewBoard.getComponent(), c);

            // Add score label
            scoreLabel.setForeground(Configuration.getColor("label", 
                                                            "#000000"));
            scoreLabel.setAlignment(Label.CENTER);
            c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 1;
            c.weightx = 0.3;
            c.weighty = 0.05;
            c.anchor = GridBagConstraints.CENTER;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 15, 0, 15);
            this.add(scoreLabel, c);

            // Add level label
            levelLabel.setForeground(Configuration.getColor("label", 
                                                            "#000000"));
            levelLabel.setAlignment(Label.CENTER);
            c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 2;
            c.weightx = 0.3;
            c.weighty = 0.05;
            c.anchor = GridBagConstraints.CENTER;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 15, 0, 15);
            this.add(levelLabel, c);
            
            // Add time label
            timeLabel.setForeground(Configuration.getColor("label", 
                                                            "#000000"));
            timeLabel.setAlignment(Label.CENTER);
            c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 5;
            c.weightx = 0.3;
            c.weighty = 0.05;
            c.anchor = GridBagConstraints.CENTER;
            c.fill = GridBagConstraints.BOTH;
            c.insets = new Insets(0, 15, 0, 15);
            this.add(timeLabel, c);

            // Add generic button
            button.setBackground(Configuration.getColor("button", "#d4d0c8"));
            c = new GridBagConstraints();
            c.gridx = 1;
            c.gridy = 3;
            c.weightx = 0.3;
            c.weighty = 1.0;
            c.anchor = GridBagConstraints.NORTH;
            c.fill = GridBagConstraints.HORIZONTAL;
            c.insets = new Insets(15, 15, 15, 15);
            this.add(button, c);

            // Add event handling            
            enableEvents(KeyEvent.KEY_EVENT_MASK);
            this.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent e) {
                    handleKeyEvent(e);
                }
            });
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    handleButtonPressed();
                    component.requestFocus();
                }
            });
        }
        

        private void resizeComponents() {
            Dimension  size = scoreLabel.getSize();
            Font       font;
            int        unitSize;
            
            // Calculate the unit size
            size = board.getComponent().getSize();
            size.width /= board.getBoardWidth();
            size.height /= board.getBoardHeight();
            if (size.width > size.height) {
                unitSize = size.height;
            } else {
                unitSize = size.width;
            }

            // Adjust font sizes
            font = new Font("SansSerif", 
                            Font.BOLD, 
                            3 + (int) (unitSize / 1.8));
            scoreLabel.setFont(font);
            levelLabel.setFont(font);
            timeLabel.setFont(font);
            font = new Font("SansSerif", 
                            Font.PLAIN, 
                            2 + unitSize / 2);
            button.setFont(font);
            
            // Invalidate layout
            scoreLabel.invalidate();
            levelLabel.invalidate();
            timeLabel.invalidate();
            button.invalidate();
        }
    }
}

After I added the timer into this game, the total time that player played before the game over is 1.20525530456E9 seconds. It's so weird... And also after I enlarged the application and resize, there are some problems with the interface. Hope to get some help with these... Thanks
Cutiecutie is offline   Reply With Quote