⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ass3.java

📁 TetrisGame java.One of my assignments.Hope it can help some students.
💻 JAVA
字号:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import TetrisBean.*;

/**
 * This class is a GUI for the Tetris Bean.
 * 
 * @author Scott Clee
 */
public class ass3 implements KeyListener
{
    
	final int MAX_LEVEL = 9;
	final int MIN_LEVEL = 0; 
	private int fLevel = 0;
    private int column;
    private int row;
    private int width;
    private int height;
	//config file name
	private final String PROGRAM_CONFIG="tetris.ini";
    final JLabel         fLevelLabel  = new JLabel("Level: " + (fLevel+1));
    final JButton        fHelpButton = new JButton("?"); 
    final JButton        fPlusButton = new JButton("+");
    final JButton        fMinusButton = new JButton("-"); 

	
	private TetrisGame     fGame        = null;
    private TetrisBoardGUI fBoardGUI    = null;
    final JFrame         fFrame       = new JFrame("CP5504 assignment3");
    final JButton        fStartButton = new JButton("Start");
    final JLabel         fScoreLabel  = new JLabel("Score:");

    /**
     * Create in instance of Scottris.
     */
    @SuppressWarnings("deprecation")
	public ass3()
    {   loadParameter();
        //set the size of the new game with loaded variables
    	fGame = new TetrisGame(column,row);
        fBoardGUI  = new TetrisBoardGUI(width,height);
    	buildPanels();

    	//add new listener for levelevent
        fGame.addLevelListener(new LevelListener(){
        	public void levelChange(LevelEvent e)
        	{
        		fLevelLabel.setText("Level: " + (e.getLevel()+1));
        		fFrame.repaint();
        		
        	}
        });

        fGame.addScoreListener(new ScoreListener()
        {
            public void scoreChange(ScoreEvent e)
            {
                fScoreLabel.setText("Score: " + e.getScore());
            }
        });

        fFrame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            }
        });

        fGame.addBoardListener(fBoardGUI);
        fFrame.addKeyListener(this);
        fFrame.pack();
        fFrame.show();
        
    }
    
    
    
    private void buildPanels()
    {
            final Container pane = fFrame.getContentPane();
            
            pane.setLayout(new BorderLayout());
       		JPanel northPanel = new JPanel();
           //populate the controls to northPanel
       		northPanel.add(fScoreLabel);
       		northPanel.add(fLevelLabel);
            northPanel.add(fPlusButton);
            northPanel.add(fMinusButton);
            northPanel.add(fHelpButton);
            fPlusButton.addActionListener(new ActionListener()
             {
                		public void actionPerformed(ActionEvent e)
                		{
    				//update the fLevel and fLevelLabel
                	if(fLevel<MAX_LEVEL)
                		fLevel=fLevel+1;
    				fGame.setLevel(fLevel);
    		 		fFrame.requestFocus();	
    		 	}
    		 	 	
            	});
              fMinusButton.addActionListener(new ActionListener()
            		{
                		public void actionPerformed(ActionEvent e)
                		{
    				//update the fLevel and fLevelLabel
                	if(fLevel>MIN_LEVEL)
                	fLevel=fLevel-1;
    				fGame.setLevel(fLevel);
     				fFrame.requestFocus();	
     				
    		 	}
    		 	 	
            	});

    		fHelpButton.addActionListener(new ActionListener()
            		{
                		public void actionPerformed(ActionEvent e)
                		{
                			//instructions
                    JOptionPane.showMessageDialog(null, 
                    		"<html><p>Up arrwo for rotation<br/>right arrow" +
                    		" - RIGHT<br/>left arrow - LEFT<br/>Down arrow - down "
                    		,"How to play",JOptionPane.PLAIN_MESSAGE);

    		 		fFrame.requestFocus();	
    		 	}
    		 	 	
            	});
     
            pane.add(northPanel, BorderLayout.NORTH);
            pane.add(fBoardGUI, BorderLayout.CENTER);
            pane.add(fStartButton, BorderLayout.SOUTH);
            
         fStartButton.addActionListener(new ActionListener()
            	{
                		public void actionPerformed(ActionEvent e)
                		{   
                			//the level start from 0 but actually displayed from 1
                			fLevelLabel.setText("Level: " + (fLevel+1));
                			fGame.setLevel(fLevel);
     				        fGame.startGame();
                 			fFrame.requestFocus();

                			
                		}
                		
            	});
    		
    }//buildPanels

    
    
    
    
    public void keyPressed(KeyEvent e)
    {
    	switch (e.getKeyCode()) 
    	{
        	case KeyEvent.VK_LEFT  : fGame.move(TetrisPiece.LEFT);
        	                         break;
        	case KeyEvent.VK_RIGHT : fGame.move(TetrisPiece.RIGHT);
        	                         break;
        	case KeyEvent.VK_UP    : fGame.move(TetrisPiece.ROTATE);
        	                         break;
        	case KeyEvent.VK_DOWN  : fGame.move(TetrisPiece.DOWN);
        	                         break;
            case KeyEvent.VK_SHIFT : fGame.move(TetrisPiece.FALL);
    	}
    }
    
    public void keyReleased(KeyEvent e) {}
    
    public void keyTyped(KeyEvent e) {}



    /**
     * This class gives a graphical representation of
     * a TetrisBoard GUI
     */
    public class TetrisBoardGUI extends JPanel implements BoardListener
    {    
    	private TetrisBoard fBoard;
    	private int boardWidth;
    	private int boardHeight;
    	TetrisBoardGUI(int width, int height)
    	{
    	boardWidth = width;
    	boardHeight = height;
    	}

		   public Dimension getPreferredSize()
	        {
	            return new Dimension(200, 600);
	        }

		public void boardChange(BoardEvent e)
        {
    	    fBoard = (TetrisBoard)e.getSource();   
            repaint();
        }
    
        public void paintComponent(Graphics graphics)
        {
        	final int width   = getBounds().width;
        	final int height  = getBounds().height;	
            
        	// Set up double buffering.
        	final Image    image = createImage(width, height);
            final Graphics g     = image.getGraphics();           
    
        
        	// Draw the board pieces if board not null.
        	if (fBoard != null) 
        	{
                final int numCols = fBoard.getColumns();
                final int numRows = fBoard.getRows();
    
        	    for (int cols = 0; cols < numCols; cols++) 
        	    {
            		for (int rows = 0; rows < numRows; rows++) 
            		{
            		    final int piece = fBoard.getPieceAt(cols, rows);
            
            		    if (piece != TetrisBoard.EMPTY_BLOCK) 
            		    {
                			g.setColor(getPieceColor(piece));
                            drawBlock(g, (cols * width / numCols) + 1, (rows * height / numRows) + 1, (width / numCols) - 1, (height / numRows) - 1);    		    }
            		}
        	    }    
        	}	
            
            g.setColor(Color.blue);
            g.drawRect(0, 0, width - 1, height - 1);
            graphics.drawImage(image, 0, 0, width, height, null);
        }
    
        private void drawBlock(Graphics g, int x, int y, int width, int height)
        {
            g.fillRect(x, y, width, height);
            g.setColor(Color.black);
            g.drawRect(x, y, width, height);
        }
    
    
        private Color getPieceColor(int color)
        {
        	Color result = null;
        
        	switch (color) 
        	{
            	case TetrisPiece.L_PIECE : result = new Color(24, 105, 198);  // turquoise
            	                           break;
            	case TetrisPiece.J_PIECE : result = new Color(206, 56, 173);  // purple
                                           break;
            	case TetrisPiece.I_PIECE : result = new Color(41, 40, 206);   // blue
            	                           break;
            	case TetrisPiece.Z_PIECE : result = new Color(212, 0, 0);     // red
            	                           break;
            	case TetrisPiece.S_PIECE : result = new Color(82, 154, 16);   // green
            	                           break;
            	case TetrisPiece.O_PIECE : result = new Color(123, 121, 123); // gray
            	                           break;
            	case TetrisPiece.T_PIECE : result = new Color(156, 142, 8);   // yellow
            	                           break;
        	}
        
        	return result;
        }
    }
    
    
    //load parameters from the file
    private void loadParameter()
    {
    	
    	String fileConfig;

    	try {
			BufferedReader br=new BufferedReader(new FileReader(PROGRAM_CONFIG));
			try {
				    //read parameters and assign them to the variables
					try
					{
						if((fileConfig=br.readLine())!=null)
						 column=Integer.parseInt(fileConfig);
						if((fileConfig=br.readLine())!=null)
						row=Integer.parseInt(fileConfig);
						if((fileConfig=br.readLine())!=null)
						width=Integer.parseInt(fileConfig);
						if((fileConfig=br.readLine())!=null)
						height=Integer.parseInt(fileConfig);
					}catch(NumberFormatException e)
					{
						e.printStackTrace();
					}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

    	// FileNotFoundException, NumberFormatException, IOException
    }//loadParameter

    public static void main(String[] args)
    {
        new ass3();
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -