`

j2se版俄罗斯方块

    博客分类:
  • J2SE
阅读更多
   1.图形界面
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ErsBlocksGame extends JFrame{
	public final static int PER_LINE_SCORE=100;
	public final static int PER_LEVEL_SCORE=PER_LINE_SCORE * 20;
	public final static int MAX_LEVEL=10;  //最大级数
	public final static int DEFAULT_LEVEL=5;
	private GameCanvas canva;
	private ErsBlock block;
	private ControlPanel pane;
	private boolean playing=false;
	private JMenuBar bar=new JMenuBar();
	private JMenu
	    m1=new JMenu("游戏"),m2=new JMenu("控制"),m3=new JMenu("窗口风格"),m4=new JMenu("帮助");
	private JMenuItem 
	    miNewGame=new JMenuItem("新游戏"),miSetBlockColor=new JMenuItem("设置方块颜色"),miSetBackColor=new JMenuItem("设置背景颜色"),
	    miTurnHarder=new JMenuItem("增加难度"),miTurnEasier=new JMenuItem("降低难度"),miExit=new JMenuItem("退出"),
	    miPlay=new JMenuItem("开始"),miPause=new JMenuItem("暂停"),miResume=new JMenuItem("继续"),miStop=new JMenuItem("停止"),
	    my11=new JMenuItem("作者:XXX"),my12=new JMenuItem("版本:1.0");
	 private JCheckBoxMenuItem 
	    miAsWindows=new JCheckBoxMenuItem("Windows"),
	    miAsMotif=new JCheckBoxMenuItem("Motif"),
	    miAsMetal=new JCheckBoxMenuItem("Metal",true); 
	    
	public ErsBlocksGame(String title){
		super(title);
		setSize(315,392);
		Dimension d=Toolkit.getDefaultToolkit().getScreenSize(); 
		setLocation((d.width-getSize().width)/2,(d.height-getSize().height)/2);
		
		createmenu();
		Container containe=getContentPane();
		containe.setLayout(new BorderLayout(6,0));
		canva=new GameCanvas(20,12);
		pane=new ControlPanel(this);
		containe.add(canva,BorderLayout.CENTER);
		containe.add(pane,BorderLayout.EAST);
		
		addWindowListener(new WindowAdapter(){
			public void windowClosing(WindowEvent we){
				stopGame();
				System.exit(0);
			}
			});
			
			/*增加构件的适配器*/
		addComponentListener(new ComponentAdapter(){
			public void componentResized(ComponentEvent ce){
				canva.fanning();
			}
		});
		setVisible(true);
		canva.fanning();
	}
			
			//让游戏复位
			 public void reset(){
			 	 pane.reset();
			 	 canva.reset();
			 }
			 
			 //判断游戏是否进行
			 public boolean isPlaying(){
			 	return playing;
			}
			
			public ErsBlock getCurBlock(){
				return block;
			}
			
			public GameCanvas getCanvas(){
				return canva;
			}
			
			public void playGame(){
				play();
				pane.setPlayButtonEnable(false);
				miPlay.setEnabled(false);
				pane.requestFocus();
			}
			
			public void pauseGame(){
				if(block !=null)  block.pauseMove();
				pane.setPauseButtonLabel(false);
				miPause.setEnabled(false);
				miResume.setEnabled(true);
			}
			
			public void resumeGame(){
				if(block !=null)  block.resumeMove();
				pane.setPauseButtonLabel(true);
				miPause.setEnabled(true);
				miResume.setEnabled(false);
				pane.requestFocus();
			}
			
			public void stopGame(){
				playing=false;
				if(block!=null) block.stopMove();
				miPlay.setEnabled(true);
				miPause.setEnabled(true);
				miResume.setEnabled(false);
				pane.setPlayButtonEnable(true);
				pane.setPauseButtonLabel(true);
			}
			
			public int getLevel(){
				return pane.getLevel();
			}
		
		public void setLevel(int level){
			if(level<11 && level>0)  pane.setLevel(level);
		}
		
		public int getScore(){
			if(canva !=null)  return canva.getScore();
			return 0;
		}
		
		public int getScoreForLevelUpdate(){
			if(canva !=null) return canva.getScoreForLevelUpdate();
			return 0;
		}
		
		public boolean levelUpdate(){
			int curLevel=getLevel();
			if (curLevel<MAX_LEVEL){
				setLevel(curLevel+1);
				canva.resetScoreForLevelUpdate();
				return true;
			}
			return false;
		}
		
		private void play(){
			reset();
			playing=true;
			Thread th=new Thread(new Game());
			th.start();
		}
		
		public void reportGameOver(){
			JOptionPane.showMessageDialog(this,"游戏结束!");
		}
		
		 private void createmenu(){
		bar.add(m1);
		bar.add(m2);
		bar.add(m3);
		bar.add(m4);
		m1.add(miNewGame);
		m1.addSeparator(); 
		m1.add(miSetBlockColor);
		m1.add(miSetBackColor);
		m1.addSeparator(); 
		m1.add(miTurnHarder);
		m1.add(miTurnEasier);
		m1.addSeparator();
		m1.add(miExit);
		m2.add(miPlay);
		m2.add(miPause);
		m2.add(miResume);
		m2.add(miStop);
		m3.add(miAsWindows);
		m3.add(miAsMotif); 
		m3.add(miAsMetal); 
		m4.add(my11); 
		m4.add(my12);
		setJMenuBar(bar);
		
		miPause.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,KeyEvent.CTRL_MASK));
		miResume.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0));
		miNewGame.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ 
			stopGame(); reset(); setLevel(DEFAULT_LEVEL); } }); 
		miSetBlockColor.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ 
			Color newFrontColor=JColorChooser.showDialog( ErsBlocksGame.this," 设置方块颜色", canva.getBlockColor()); 
			if(newFrontColor!=null) canva.setBlockColor(newFrontColor); } });
		miSetBackColor.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){
			 Color newBackColor=JColorChooser.showDialog( ErsBlocksGame.this," 设置方块颜色", canva.getBackgroundColor());
			  if(newBackColor!=null) canva.setBackgroundColor(newBackColor); } });
		miTurnHarder.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ int curLevel=getLevel(); 
			if(curLevel<MAX_LEVEL) setLevel(curLevel+1); } });
		miTurnEasier.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ int curLevel=getLevel(); 
			if(curLevel>1) setLevel(curLevel-1); } });
		miExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ System.exit(0); } }); 
    
    miPlay.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                playGame();   
            }   
        });
    miPause.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                pauseGame();   
            }   
        });       
    miResume.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                resumeGame();   
            }   
        });
    miStop.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                stopGame();   
            }   
        }); 
    miAsWindows.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";   
                setWindowStyle(plaf);   
                canva.fanning();   
                pane.fanning();   
                miAsWindows.setState(true);   
                miAsMetal.setState(false);   
                miAsMotif.setState(false);   
            }   
        }); 
     miAsMotif.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";   
                setWindowStyle(plaf);   
                canva.fanning();   
                pane.fanning();   
                miAsWindows.setState(false);   
                miAsMetal.setState(false);   
                miAsMotif.setState(true);   
            }   
        });
      miAsMetal.addActionListener(new ActionListener() {   
            public void actionPerformed(ActionEvent ae) {   
                String plaf = "javax.swing.plaf.metal.MetalLookAndFeel";   
                setWindowStyle(plaf);   
                canva.fanning();   
                pane.fanning();   
                miAsWindows.setState(false);   
                miAsMetal.setState(true);   
                miAsMotif.setState(false);   
            }   
        });      
    
	} 
	
	private void setWindowStyle(String plaf){
		try{
			UIManager.setLookAndFeel(plaf);  //设置用户外观
			SwingUtilities.updateComponentTreeUI(this);   //改变为当前外观 
		}
		catch(Exception e){}
	}  
	
	private class Game implements Runnable{
		public void run(){
			int col=(int)(Math.random() * (canva.getCols()-3)),
			style=ErsBlock.STYLES[(int)(Math.random()*7)][(int)(Math.random()*4)];
			while(playing){
				if(block !=null){
					if(block.isAlive()){
						try{
							Thread.currentThread().sleep(100);
						}
						catch(InterruptedException ie){
							ie.printStackTrace();
						}
						continue;
					}
				}
				
				checkFullLine();  //检查是否填满
				
				if(isGameOver()){
					miPlay.setEnabled(true);
					miPause.setEnabled(true);
					miResume.setEnabled(false);
					pane.setPlayButtonEnable(true);
					pane.setPauseButtonLabel(true);
					reportGameOver();
					return;
				}
				
				block=new ErsBlock(style,-1,col,getLevel(),canva);
				block.start();
				col=(int)(Math.random()*(canva.getCols()-3)); //初始列位置
				style=ErsBlock.STYLES[(int)(Math.random()*7)][(int)(Math.random()*4)];
				pane.setTipStyle(style);
			}
		}
		public void checkFullLine(){
			for (int i=0;i<canva.getRows();i++){
				int row=-1;
				boolean fulllinecolorbox=true;
				for(int j=0;j<canva.getCols();j++){
					if(!canva.getBox(i,j).isColorBox()){
						fulllinecolorbox=false;
						break;
					}
				}
				if (fulllinecolorbox){
					row=i--;
					canva.removeLine(row);  //移除已填满
				}
			}
		}
		
		private boolean isGameOver(){
			for(int i=0;i<canva.getCols();i++){
				ErsBox box=canva.getBox(0,i);
				if(box.isColorBox())  return true;
			}
			return false;
		}
	}
	
	public static void main(String args[]){
		new ErsBlocksGame("俄罗斯方块游戏");
	}
}
	

   2.画版
/**  
 * File: GameCanvas.java  
 * User: Administrator  
 * Date: Jan 15, 2003  
 * Describe: 俄罗斯方块的 Java 实现  
 */   
   
import javax.swing.*;   
import javax.swing.border.EtchedBorder;   
import java.awt.*;   
   
/**  
 * 画布类,内有<行数> * <列数>个方格类实例。  
 * 继承自JPanel类。  
 * ErsBlock线程类动态改变画布类的方格颜色,画布类通过  
 * 检查方格颜色来体现ErsBlock块的移动情况。  
 */   
class GameCanvas extends JPanel {   
    private Color backColor = Color.black, frontColor = Color.orange;   
    private int rows, cols, score = 0, scoreForLevelUpdate = 0;   
    private ErsBox[][] boxes;   
    private int boxWidth, boxHeight;   
   
    /**  
     * 画布类的构造函数  
     * @param rows int, 画布的行数  
     * @param cols int, 画布的列数  
     * 行数和列数决定着画布拥有方格的数目  
     */   
    public GameCanvas(int rows, int cols) {   
        this.rows = rows;   
        this.cols = cols;   
   
        boxes = new ErsBox[rows][cols];   
        for (int i = 0; i < boxes.length; i++) {   
            for (int j = 0; j < boxes[i].length; j++) {   
                boxes[i][j] = new ErsBox(false);   
            }   
        }   
   
        setBorder(new EtchedBorder(   
                EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)));   
    }   
   
    /**  
     * 画布类的构造函数  
     * @param rows 与public GameCanvas(int rows, int cols)同  
     * @param cols 与public GameCanvas(int rows, int cols)同  
     * @param backColor Color, 背景色  
     * @param frontColor Color, 前景色  
     */   
    public GameCanvas(int rows, int cols,   
                      Color backColor, Color frontColor) {   
        this(rows, cols);   
        this.backColor = backColor;   
        this.frontColor = frontColor;   
    }   
   
    /**  
     * 设置游戏背景色彩  
     * @param backColor Color, 背景色彩  
     */   
    public void setBackgroundColor(Color backColor) {   
        this.backColor = backColor;   
    }   
   
    /**  
     * 取得游戏背景色彩  
     * @return Color, 背景色彩  
     */   
    public Color getBackgroundColor() {   
        return backColor;   
    }   
   
    /**  
     * 设置游戏方块色彩  
     * @param frontColor Color, 方块色彩  
     */   
    public void setBlockColor(Color frontColor) {   
        this.frontColor = frontColor;   
    }   
   
    /**  
     * 取得游戏方块色彩  
     * @return Color, 方块色彩  
     */   
    public Color getBlockColor() {   
        return frontColor;   
    }   
   
    /**  
     * 取得画布中方格的行数  
     * @return int, 方格的行数  
     */   
    public int getRows() {   
        return rows;   
    }   
   
    /**  
     * 取得画布中方格的列数  
     * @return int, 方格的列数  
     */   
    public int getCols() {   
        return cols;   
    }   
   
    /**  
     * 取得游戏成绩  
     * @return int, 分数  
     */   
    public int getScore() {   
        return score;   
    }   
   
    /**  
     * 取得自上一次升级后的积分  
     * @return int, 上一次升级后的积分  
     */   
    public int getScoreForLevelUpdate() {   
        return scoreForLevelUpdate;   
    }   
   
    /**  
     * 升级后,将上一次升级以来的积分清0  
     */   
    public void resetScoreForLevelUpdate() {   
        scoreForLevelUpdate -= ErsBlocksGame.PER_LEVEL_SCORE;   
    }   
   
    /**  
     * 得到某一行某一列的方格引用。  
     * @param row int, 要引用的方格所在的行  
     * @param col int, 要引用的方格所在的列  
     * @return ErsBox, 在row行col列的方格的引用  
     */   
    public ErsBox getBox(int row, int col) {   
        if (row < 0 || row > boxes.length - 1   
                || col < 0 || col > boxes[0].length - 1)   
            return null;   
        return (boxes[row][col]);   
    }   
   
    /**  
     * 覆盖JComponent类的函数,画组件。  
     * @param g 图形设备环境  
     */   
    public void paintComponent(Graphics g) {   
        super.paintComponent(g);   
   
        g.setColor(frontColor);   
        for (int i = 0; i < boxes.length; i++) {   
            for (int j = 0; j < boxes[i].length; j++) {   
                g.setColor(boxes[i][j].isColorBox() ? frontColor : backColor);   
                g.fill3DRect(j * boxWidth, i * boxHeight,   
                        boxWidth, boxHeight, true);   
            }   
        }   
    }   
   
    /**  
     * 根据窗口的大小,自动调整方格的尺寸  
     */   
    public void fanning() {   
        boxWidth = getSize().width / cols;   
        boxHeight = getSize().height / rows;   
    }   
   
    /**  
     * 当一行被游戏者叠满后,将此行清除,并为游戏者加分  
     * @param row int, 要清除的行,是由ErsBoxesGame类计算的  
     */   
    public synchronized void removeLine(int row) {   
        for (int i = row; i > 0; i--) {   
            for (int j = 0; j < cols; j++)   
                boxes[i][j] = (ErsBox) boxes[i - 1][j].clone();   
        }   
   
        score += ErsBlocksGame.PER_LINE_SCORE;   
        scoreForLevelUpdate += ErsBlocksGame.PER_LINE_SCORE;   
        repaint();   
    }   
   
    /**  
     * 重置画布,置积分为0  
     */   
    public void reset() {   
        score = 0;   
        scoreForLevelUpdate = 0;   
        for (int i = 0; i < boxes.length; i++) {   
            for (int j = 0; j < boxes[i].length; j++)   
                boxes[i][j].setColor(false);   
        }   
   
        repaint();   
    }   
}   

   3.随机产生方块
class ErsBlock extends Thread{
	public final static int BOXES_ROWS=4;     //4行
	public final static int BOXES_COLS=4;     //4列
	public final static int LEVEL_FLATNESS_GENE=3;  //升级变化因子
	public final static int BETWEEN_LEVELS_DEGRESS_TIME=50;  //时间间隔
	public final static int BLOCK_KIND_NUMBER=7;   //方块样式为7
	public final static int BLOCK_STATUS_NUMBER=4;  //方块反转4种状态
	
	public final static int[][] STYLES={
	{0x0f00, 0x4444, 0x0f00, 0x4444}, //长条
	{0x04e0, 0x0464, 0x00e4, 0x04c4}, //T形
	{0x4620, 0x6c00, 0x4620, 0x6c00}, //反Z
	{0x2640, 0xc600, 0x2640, 0xc600}, //Z
	{0x6220, 0x1700, 0x2230, 0x0740}, //7
	{0x6440, 0x0e20, 0x44c0, 0x8e00}, //反7
	{0x0660, 0x0660, 0x0660, 0x0660}, //方块
  };
  
  private GameCanvas canva;
  private ErsBox[][] boxes=new ErsBox[BOXES_ROWS][BOXES_COLS];
  private int style,y,x,level;
  private boolean pausing=false,moving=true;
  
  public ErsBlock(int style,int y,int x,int level,GameCanvas canva){
  	this.style=style;
  	this.y=y;
  	this.x=x;
  	this.level=level;
  	this.canva=canva;
  	int key=0x8000;
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			boolean isColor=((style & key)!=0);
  			boxes[i][j]=new ErsBox(isColor);
  			key>>=1;
  		}
  	}
  	display();
  }
  
  /* 覆盖法*/
  public void run(){
  	while(moving){
  		try{
  			sleep(BETWEEN_LEVELS_DEGRESS_TIME * (ErsBlocksGame.MAX_LEVEL-level+LEVEL_FLATNESS_GENE));
  		}
  		catch(InterruptedException ie){
  			ie.printStackTrace();
  		}
  		if(!pausing) moving=(moveTo(y+1,x) && moving);
  	}
  }
  
  public void moveLeft(){
  	moveTo(y,x-1);
  }
  
   public void moveRight(){
  	moveTo(y,x+1);
  }
  
   public void moveDown(){
  	moveTo(y+1,x);
  }
  
   public void turnNext(){
  	for(int i=0;i<BLOCK_KIND_NUMBER;i++){
  		for(int j=0;j<BLOCK_STATUS_NUMBER;j++){
  			if(STYLES[i][j]==style){
  				int newStyle=STYLES[i][(j+1) % BLOCK_STATUS_NUMBER];
  				turnTo(newStyle);
  				return;
  			}
  		}
  	}
  }
  
  public void pauseMove(){
  	pausing=true;
  }
  
  public void resumeMove(){
  	pausing=false;
  }
  
  public void stopMove(){
  	moving=false;
  }
  
  /*将当前画布抹去,等下一次反映*/
  private void erase(){
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			if(boxes[i][j].isColorBox()){
  				ErsBox box=canva.getBox(i+y,j+x);
  				if(box==null) continue;
  				box.setColor(false);
  			}
  		}
  	}
  }
  
   /*将当前画布显示,等下一次看见*/
  private void display(){
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			if(boxes[i][j].isColorBox()){
  				ErsBox box=canva.getBox(y+i,x+j);
  				if(box==null) continue;
  				box.setColor(true);
  			}
  		}
  	}
  }
  
  private boolean isMoveAble(int newRow,int newCol){
  	erase();
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			if(boxes[i][j].isColorBox()){
  				ErsBox box=canva.getBox(newRow+i,newCol+j);
  				if(box==null || (box.isColorBox())){
  					display();
  					return false;
  				}
  			}
  		}
  	}
  	display();
  	return true;
  }
  
  private synchronized boolean moveTo(int newRow,int newCol){
  	if(!isMoveAble(newRow,newCol) || !moving)  return false;
  	erase();
  	y=newRow;
  	x=newCol;
  	display();
  	canva.repaint();
  	return true;
  }
  
  private boolean isTurnAble(int newStyle){
  	int key=0x8000;
  	erase();
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			if((newStyle & key)!=0){
  				ErsBox box=canva.getBox(y+i,x+j);
  				if(box==null || box.isColorBox()){
  					display();
  					return false;
  				}
  			}
  			key>>=1;
  		}
  	}
  	display();
  	return true;
  }
  
  private boolean turnTo(int newStyle){
  	if(!isTurnAble(newStyle) || !moving) return false;
  	erase();
  	int key=0x8000;
  	for(int i=0;i<boxes.length;i++){
  		for(int j=0;j<boxes[i].length;j++){
  			boolean isColor=((newStyle & key) !=0);
  			boxes[i][j].setColor(isColor);
  			key>>=1;
  				}
  			}
  	style=newStyle;
  	display();
  	canva.repaint();
  	return true;
  }
}

    4.实现克隆
import java.awt.*;   //复制方法
 class ErsBox implements Cloneable{
	private boolean iscolor;
	private Dimension size=new Dimension();
	
	public ErsBox(boolean iscolor){
		this.iscolor=iscolor;
	}
	
	public boolean isColorBox(){
		return iscolor;
	}
	
	public void setColor(boolean iscolor){
		this.iscolor=iscolor;
	}
	
	public Dimension getSize(){
		return size;
	}
	
	public void setSize(Dimension sizze){
		this.size=size;
	}
	
	/*实现克隆*/
	public Object clone(){
		Object cloned=null;
		try{
			cloned=super.clone();
		}
		catch(Exception ex){
			ex.printStackTrace();
		}
		return cloned;
	}
}	

    5.事件处理
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;  //EtchedBorder为swing突出或凹进的边框
 class ControlPanel extends JPanel{
	private JTextField
	  tflevel=new JTextField(""+ErsBlocksGame.DEFAULT_LEVEL),
	  tfscore=new JTextField("0");
	private JButton
	  btplay=new JButton("开始"),
	  btpause=new JButton("暂停"),
	  btstop=new JButton("停止"),
	  btturnup=new JButton("增加难度"),
	  btturndown=new JButton("降低难度");
	private JPanel plTip=new JPanel(new BorderLayout());
	private TipPanel pltipblock=new TipPanel(); 
	private JPanel plinfo=new JPanel(new GridLayout(4,1));
	private JPanel plbutton=new JPanel(new GridLayout(5,1));
	private Timer timer;
	private ErsBlocksGame game;
	private Border border=new EtchedBorder(EtchedBorder.RAISED,Color.white,new Color(148,145,140));
	
	public ControlPanel(final ErsBlocksGame game){
		setLayout(new GridLayout(3,1,0,4));
		this.game=game;
		plTip.add(new JLabel("下一块方块"),BorderLayout.NORTH);
		plTip.add(pltipblock);
		plTip.setBorder(border);
		
		plinfo.add(new JLabel("难度级别"));
		plinfo.add(tflevel);
		plinfo.add(new JLabel("得分"));
		plinfo.add(tfscore);
		plinfo.setBorder(border);
	 
	 	tflevel.setEditable(false);  //文本不可编辑
	 	tfscore.setEditable(false);
	 	
	 	plbutton.add(btplay);
	 	plbutton.add(btpause);
	 	plbutton.add(btstop);
	 	plbutton.add(btturnup);
	 	plbutton.add(btturndown);
	 	plbutton.setBorder(border);
	 	
	 	add(plTip);
	 	add(plinfo);
	 	add(plbutton);
	 	
	 	addKeyListener(new ControlKeyListener());   //增加键盘的监听器
	 	btplay.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				game.playGame();
			}
		});
		btpause.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				if(btpause.getText().equals(new String("暂停"))){
					game.pauseGame();
				}
				else{
					game.resumeGame();
				}
			}
		});
		btstop.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				game.stopGame();
			}
		});
		btturnup.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				try{
					int level=Integer.parseInt(tflevel.getText());
					if(level<ErsBlocksGame.MAX_LEVEL)
					   tflevel.setText(""+(level+1));
					 }
					 catch(NumberFormatException e) {}
					 requestFocus();
					}
				});
				btturndown.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent ae){
				try{
					int level=Integer.parseInt(tflevel.getText());
					if(level>1)
					   tflevel.setText(""+(level-1));
					 }
					 catch(NumberFormatException e) {}
					 requestFocus();
					}
				});
				addComponentListener(new ComponentAdapter(){
					public void componentResized(ComponentEvent ce){
						pltipblock.fanning();
					}
				});
				
				timer=new Timer(500,new ActionListener(){
					public void actionPerformed(ActionEvent ae){
						tfscore.setText(""+game.getScore());
						int sfu=game.getScoreForLevelUpdate();
						if (sfu>=ErsBlocksGame.PER_LEVEL_SCORE && sfu>0)
						game.levelUpdate();
					}
				});
				timer.start();
			}
		
		public void setTipStyle(int style){
			pltipblock.setStyle(style);
		}		
		public int getLevel(){
			int level=0;	
			try{
				level=Integer.parseInt(tflevel.getText());
			}
			catch(NumberFormatException e) {}
			return level;
		}
		public void setLevel(int level){
			 if(level>0 && level<11)
	       tflevel.setText(""+level);
	     }
	 
	 public void setPlayButtonEnable(boolean enable){
	 	btplay.setEnabled(enable);
	}
	
	 public void setPauseButtonLabel(boolean pause){
	 	btpause.setText(pause ? "暂停":"继续");
	} 
	
	public void reset(){
		 tfscore.setText("0");
		 pltipblock.setStyle(0);
		}
		
		public void fanning(){
			pltipblock.fanning(); //重计算
		}
		
		public class TipPanel extends JPanel{
			private Color bc=Color.darkGray,
			 fc=Color.lightGray;
		  private ErsBox[][] boxes=new ErsBox[ErsBlock.BOXES_ROWS][ErsBlock.BOXES_COLS];
		  private int style,boxwidth,boxheight;
		  private boolean isTiled=false;
		  
		  public TipPanel(){
		  	for(int i=0;i<boxes.length;i++){
		  		for(int j=0;j<boxes[i].length;j++)
		  	   boxes[i][j]=new ErsBox(false);
		  	 }
		  	}
		  
		 public TipPanel(Color bc,Color fc){
		  	this();
		  	this.bc=bc;
		  	this.fc=fc;
		  }
		  
		  public void setStyle(int style){
		  	this.style=style;
		  	repaint();
		  }
		  
		  public void paintComponent(Graphics g){
		  	super.paintComponent(g);
		  	if(!isTiled) fanning();
		  	int key=0x800;
		  	for(int i=0;i<boxes.length;i++){
		  		for(int j=0;j<boxes[i].length;j++){
		  			Color color=(((key & style)!=0)? fc:bc);
		  			g.setColor(color);
		  			g.fill3DRect(j*boxwidth,i*boxheight,boxwidth,boxheight,true);
		  			key>>=1;
		  		}
		  	}
		  }
		  
		  public void fanning(){
		  	boxwidth=getSize().width/ErsBlock.BOXES_COLS;
		  	boxheight=getSize().height/ErsBlock.BOXES_ROWS;
		  	isTiled=true;
		  }
		}
		
		private class ControlKeyListener extends KeyAdapter{
			public void keyPressed(KeyEvent ke){
				if(!game.isPlaying()) return;
				ErsBlock block=game.getCurBlock();
				switch(ke.getKeyCode()){
					case KeyEvent.VK_DOWN:
					block.moveDown();
					break;
					case KeyEvent.VK_LEFT:
					block.moveLeft();
					break;
					case KeyEvent.VK_RIGHT:
					block.moveRight();
					break;
					case KeyEvent.VK_UP:
					block.turnNext();
					break;
					default:
					break;
				}
			}
		}
	}		  			
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics