OOP-Projects-Java

Log | Files | Refs | README

GUI.java (2103B)


      1 package game;
      2 
      3 import java.awt.Canvas;
      4 import java.awt.Color;
      5 import java.awt.Graphics;
      6 import java.awt.Graphics2D;
      7 import java.awt.event.KeyEvent;
      8 import java.awt.event.KeyListener;
      9 
     10 import javax.swing.JFrame;
     11 
     12 public class GUI extends JFrame implements KeyListener {
     13 	private Board board;
     14 	private JFrame frame;
     15 
     16 	/**
     17 	 * Instantiates the GUI and creates a JFrame / window on which the game is played.
     18 	 * @param board
     19 	 */
     20 	public GUI(Board board) {
     21 		this.board = board;
     22 		frame = new JFrame("Tetris");
     23 		frame.addKeyListener(this);
     24 		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     25 		frame.setSize(board.getSize());
     26 		frame.setResizable(false);
     27 
     28 		frame.add(board);
     29 
     30 		frame.setVisible(true);
     31 	}
     32 
     33 	@Override
     34 	public void keyTyped(KeyEvent e) {
     35 		// TODO Auto-generated method stub
     36 
     37 	}
     38 
     39 	/**
     40 	 * Handle all of the user input.
     41 	 */
     42 	@Override
     43 	public void keyPressed(KeyEvent e) {
     44 		switch (e.getKeyCode()) {
     45 		// instantly move the falling Poly to the lowest possible position.
     46 		// Spacebar.
     47 		case 32:
     48 			if (board.getFallingPoly() != null) {
     49 				board.instaFall(board.getFallingPoly());
     50 			}
     51 			break;
     52 		// move the currently falling poly to the left.
     53 		// left arrow key.
     54 		case 37:
     55 			movePoly(-1, 0);
     56 			break;
     57 		// move the currently falling poly to the right.
     58 		// right arrow key.
     59 		case 39:
     60 			movePoly(1, 0);
     61 			break;
     62 		// rotate the falling poly.
     63 		// up arrow key.
     64 		case 38:
     65 			if (board.getFallingPoly() != null) {
     66 				board.getFallingPoly().rotateRight();
     67 
     68 				// if the rotate is not legal, undo rotation.
     69 				if (!(board.isLegal(board.getFallingPoly(), 0, 0))) {
     70 					board.getFallingPoly().rotateLeft();
     71 				}
     72 			}
     73 			break;
     74 		// slow fall.
     75 		// down arrow key.
     76 		case 40:
     77 			movePoly(0, 1);
     78 			break;
     79 		}
     80 
     81 		board.repaint();
     82 	}
     83 
     84 	@Override
     85 	public void keyReleased(KeyEvent e) {
     86 		// TODO Auto-generated method stub
     87 
     88 	}
     89 	
     90 	/**
     91 	 * checks if there is a falling poly,
     92 	 * then moves it to the desired position.
     93 	 * @param x
     94 	 * @param y
     95 	 */
     96 	private void movePoly(int x, int y) {
     97 		if (board.getFallingPoly() != null) {
     98 			board.move(board.getFallingPoly(), x, y);
     99 		}
    100 	}
    101 }