俄羅斯方塊java源代碼完美版

package russia;java

/www.quzhuanpan.com 轉載請告知/
/*canvas

  • 控制面板類
    */windows

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;dom

public class ControlPanel extends JPanel
{
private TipBlockPanel tipBlockPanel;
private JPanel tipPanel,InfoPanel,buttonPanel;
private final JTextField levelField,scoreField;
private JButton playButton,pauseButton,stopButton,函數

turnHarderButton,turnEasilyButton;

private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;this

private RussiaBlocksGame game;
private Timer timer;
/www.quzhuanpan.com 轉載請告知/
public ControlPanel(final RussiaBlocksGame game)
{
this.game = game;
/*
*圖形界面部分
*/
setLayout(new GridLayout(3,1,0,4));線程

tipBlockPanel = new TipBlockPanel();
tipPanel = new JPanel( new BorderLayout() );
tipPanel.add( new JLabel("Next Block:") , BorderLayout.NORTH );
tipPanel.add( tipBlockPanel , BorderLayout.CENTER );
tipPanel.setBorder(border);code

InfoPanel = new JPanel( new GridLayout(4,1,0,0) );
levelField = new JTextField(""+RussiaBlocksGame.DEFAULT_LEVEL);
levelField.setEditable(false);
scoreField = new JTextField("0");
scoreField.setEditable(false);
InfoPanel.add(new JLabel("Level:"));
InfoPanel.add(levelField);
InfoPanel.add(new JLabel("Score:"));
InfoPanel.add(scoreField);
InfoPanel.setBorder(border);
/www.quzhuanpan.com 轉載請告知/
buttonPanel = new JPanel(new GridLayout(5,1,0,0));
playButton = new JButton("Play");
pauseButton = new JButton("Pause");
stopButton = new JButton("Stop");
turnHarderButton = new JButton("Turn harder");
turnEasilyButton = new JButton("Turn easily");component

buttonPanel.add(playButton);
buttonPanel.add(pauseButton);
buttonPanel.add(stopButton);
buttonPanel.add(turnHarderButton);
buttonPanel.add(turnEasilyButton);
buttonPanel.setBorder(border);orm

addKeyListener(new ControlKeyListener());//添加

add(tipPanel);
add(InfoPanel);
add(buttonPanel);
/*
*添加事件監聽器
*/
playButton.addActionListener(
new ActionListener()
{

public void actionPerformed(ActionEvent event)
{
 game.playGame();
 requestFocus();//讓ControlPanel從新得到焦點以響應鍵盤事件
}
});
/*www.quzhuanpan.com 轉載請告知*/
pauseButton.addActionListener(
new ActionListener()
{
 public void actionPerformed(ActionEvent event)
 {
  if(pauseButton.getText().equals("Pause"))
    game.pauseGame();
  else
    game.resumeGame(); 
  requestFocus();//讓ControlPanel從新得到焦點以響應鍵盤事件
 }
}
);
stopButton.addActionListener(
new ActionListener()
{
 public void actionPerformed(ActionEvent event)
 {
  game.stopGame();
  requestFocus();//讓ControlPanel從新得到焦點以響應鍵盤事件
 }
});

turnHarderButton.addActionListener(
new ActionListener()
{

public void actionPerformed(ActionEvent event)
 {
   int level = 0;
   try{
       level = Integer.parseInt(levelField.getText());
       setLevel(level + 1);
      }catch(NumberFormatException e)
      {
       e.printStackTrace();
      }
   requestFocus();//讓ControlPanel從新得到焦點以響應鍵盤事件
 }

});
turnEasilyButton.addActionListener(
new ActionListener()
{

public void actionPerformed(ActionEvent event)
 {
   int level = 0;
   try{
       level = Integer.parseInt(levelField.getText());
       setLevel(level - 1); 
      }catch(NumberFormatException e)
      {
       e.printStackTrace();
      }
  requestFocus();//讓ControlPanel從新得到焦點以響應鍵盤事件
 }

});

/*
*  時間驅動程序,每格500毫秒對level,score值進行更新
*/

timer = new Timer(500,
new ActionListener()
{

public void actionPerformed(ActionEvent event)
{
 scoreField.setText(""+game.getScore());
 game.levelUpdate();
}

}
);
timer.start();
}
/*

  • 設置預顯方塊的樣式
    */

public void setBlockStyle(int style)
{
tipBlockPanel.setStyle(style);
tipBlockPanel.repaint();
}
/*

  • 重置,將全部數據恢復到最初值
    */

public void reset()
{
levelField.setText(""+RussiaBlocksGame.DEFAULT_LEVEL);
scoreField.setText("0");
setPlayButtonEnabled(true);
setPauseButtonLabel(true);
tipBlockPanel.setStyle(0);
}

/*
*設置playButton是否可用
*/
public void setPlayButtonEnabled(boolean enable)
{
playButton.setEnabled(enable);
}

/*
*設置pauseButton的文本
*/
public void setPauseButtonLabel(boolean pause)
{
pauseButton.setText( pause ? "Pause" : "Rusume" );
}

/*
*設置方塊的大小,改變窗體大小時調用可自動調整方塊到合適的尺寸
*/
public void fanning()
{
tipBlockPanel.fanning();
}
/*
*根據level文本域的值返回當前的級別
*/
public int getLevel()
{

int level = 0;
 try
 {
  level=Integer.parseInt(levelField.getText());
 }catch(NumberFormatException e)
 {
   e.printStackTrace();
 }
 return level;

}
/*

  • 設置level文本域的值
    */

public void setLevel(int level)
{

if(level > 0 && level <= RussiaBlocksGame.MAX_LEVEL)
   levelField.setText("" + level);

}
/*

  • 內部類 爲預顯方塊的顯示區域
    */

private class TipBlockPanel extends JPanel
{

private Color bgColor = Color.darkGray, 
              blockColor = Color.lightGray;              
private RussiaBox [][]boxes = new RussiaBox[RussiaBlock.ROWS][RussiaBlock.COLS];
private int boxWidth, boxHeight,style;
private boolean isTiled = false;

/*
 * 構造函數
 */

public TipBlockPanel()
{

for(int i = 0; i < boxes.length; i ++)
   for(int j = 0; j < boxes[i].length; j ++)
     {
      boxes[i][j]=new RussiaBox(false);
     }
     style = 0x0000;

}
/*

* 構造函數
*/

public TipBlockPanel(Color bgColor, Color blockColor)
{

this();
this.bgColor = bgColor;
this.blockColor = blockColor;

}

/*
 * 設置方塊的風格
 */
public void setStyle(int style)
{
 this.style = style;
 repaint();
}

/*
 * 繪製預顯方塊
 */

public void paintComponent(Graphics g)
{

super.paintComponent(g);

int key = 0x8000;

if(!isTiled)
   fanning();
for(int i = 0; i < boxes.length; i ++)
  for(int j = 0; j<boxes[i].length ;j ++)
   {
     Color color = (style & key) != 0  ?  blockColor : bgColor;
     g.setColor(color);
     g.fill3DRect(j * boxWidth, i * boxHeight, boxWidth, boxHeight, true);  
     key >>=1;
   }

}
/*

*設置方塊的大小,改變窗體大小時調用可自動調整方塊到合適的尺寸
*/

public void fanning()
{

boxWidth = getSize().width / RussiaBlock.COLS;
boxHeight = getSize().height /RussiaBlock.ROWS;
isTiled=true;

}
}
/*
*內部類 鍵盤鍵聽器,響應鍵盤事件
*/
class ControlKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent ke)
{
if (!game.isPlaying()) return;

RussiaBlock 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;
case KeyEvent.VK_SPACE://一鍵到底
  while(block.moveDown())
  {  
  }
  break;
default:
 break;

}
}
}
}
package russia;
/www.tengxunyun.me 轉載請告知/
/*

  • 遊戲中方塊顯示的畫布類
    */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class GameCanvas extends JPanel
{
private RussiaBox [][]boxes;
private int rows = 20 , cols = 12;
private static GameCanvas canvas=null;
private int boxWidth, boxHeight;//默認爲零須要調用fanning函數設置
private Color blockColor = Color.RED, bgColor = new Color(0,204,204);
private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;

/*
*採用單件模式,構造函數私有
*/
private GameCanvas()
{
boxes = new RussiaBoxrows;

for(int i = 0; i < boxes.length; i ++)

for(int j = 0; j<boxes[i].length; j ++)
      boxes[i][j] = new RussiaBox(false);

setBorder(border);
}
/*
*得到GameCanvas實例
*/
public static GameCanvas getCanvasInstance()
{
if(canvas == null)

canvas = new GameCanvas();
 
return canvas;

}
/*
*設置畫布的背景色
*/
public void setBgColor(Color bgColor)
{

this.bgColor = bgColor;

}
/*

  • 得到畫布的背景色
    */

public Color getBgColor()
{

return bgColor;

}
/*
*設置方塊的顏色
*/
public void setBlockColor(Color blockColor)
{

this.blockColor = blockColor;

}
/*
*方塊的顏色
*/
public Color getBlockColor()
{

return blockColor;

}
/*
*設置畫布中方塊的行數
*/
public void setRows(int rows)
{

this.rows = rows;

}
/*
*獲得畫布中方塊的行數
*/
public int getRows()
{

return rows;

}
/*
*設置畫布中方塊的列數
*/
public void setCols(int cols)
{

this.cols = cols;

}
/*
*獲得畫布中方塊的列數
*/
public int getCols()
{

return cols;

}
/*
*獲得row行,col列的方格
*/
public RussiaBox getBox(int row, int col)
{
if(row >= 0 && row < rows && col >= 0 && col < cols)

return boxes[row][col];

else

return null;

}
/*
*在畫布中繪製方塊
*/
public void paintComponent(Graphics g)
{
super.paintComponent(g);

fanning();
for(int i = 0; i < boxes.length; i ++)

for(int j = 0; j < boxes[i].length; j ++)
    {
      Color color = boxes[i][j].isColorBox() ? blockColor : bgColor;
      g.setColor(color);
      g.fill3DRect(j * boxWidth, i * boxHeight , boxWidth , boxHeight , true);
    }

}
/*
*清除第row行
*/
public void removeLine(int row)
{
for(int i = row; i > 0; i --)

for(int j = 0; j < cols; j ++)
{ 
      boxes[i][j] = (RussiaBox)boxes[i-1][j].clone();
 }

}
/*
*重置 爲初始時的狀態
*/
public void reset()
{
for(int i = 0; i < boxes.length; i++)

for(int j = 0 ;j < boxes[i].length; j++)
   {
     boxes[i][j].setColor(false);
   }
repaint();

}
/*

  • 根據窗體的大小自動調整方格的大小
    */

public void fanning()
{
boxWidth = getSize().width / cols;
boxHeight = getSize().height / rows;
}

}
package russia;

/*

  • 方塊類
    */

public class RussiaBlock extends Thread
{
private int style,y,x,level;
private boolean moving,pausing;
private RussiaBox boxes[][];
private GameCanvas canvas;

public final static int ROWS = 4;
public final static int COLS = 4;
public final static int BLOCK_KIND_NUMBER = 7;
public final static int BLOCK_STATUS_NUMBER = 4;
public final static int BETWEEN_LEVELS_TIME = 50;
public final static int LEVEL_FLATNESS_GENE = 3;

/*
*方塊的全部風格及其不一樣的狀態
*/
public final static int[][] STYLES = {// 共28種狀態
{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}, // 方塊的四種狀態
};
/*
*構造函數
*/
/www.tengxunyun.me 轉載請告知/
public RussiaBlock(int y,int x,int level,int style)
{

this.y = y;
this.x = x;
this.level = level;
moving = true;
pausing = false;
this.style = style;

canvas = GameCanvas.getCanvasInstance();

boxes = new RussiaBoxROWS;
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 RussiaBox(isColor);
   key >>= 1;
 }
display();

}
/*
*線程的 run方法控制放塊的下落及下落速度
*/
public void run()
{
while(moving)
{
try
{

sleep( BETWEEN_LEVELS_TIME * (RussiaBlocksGame.MAX_LEVEL - level + LEVEL_FLATNESS_GENE) );
 if(!pausing)
     moving = ( moveTo(y + 1,x) &&  moving );

}catch(InterruptedException e)
{

e.printStackTrace();

}
}
}
/*
*暫停移動
*/
public void pauseMove()
{
pausing = true;
}
/*
*從暫停狀態恢復
*/
public void resumeMove()
{
pausing = false;
}

/*
*中止移動
*/
public void stopMove()
{
moving = false;
}
/*
*向左移一格
*/
public void moveLeft()
{
moveTo(y , x - 1);
}
/*
*向右移一格
*/
public void moveRight()
{
moveTo(y , x + 1);
}
/*
*向下移一格,返回與其餘幾個不一樣,爲了一鍵到底
*/
public boolean moveDown()
{
if(moveTo(y + 1, x))

return true;

else

return false;

}
/*
*移到newRow,newCol位置
*/
public synchronized boolean moveTo(int newRow, int newCol)
{

//erase();//必須在判斷前進行擦除,不然isMoveable將產生錯誤行爲

if(!moving || !isMoveable(newRow,newCol))
{
   display();
    return false;
}
y = newRow;
x = newCol;
display();
canvas.repaint();
return true;

}
/*
*判斷可否移到newRow,newCol位置
*/
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() )
      {
        RussiaBox box = canvas.getBox(newRow + i, newCol + j);
        if(box == null || box.isColorBox())
            return false;
      }          
    }
   return true;

}
/*
*經過旋轉變爲下一種狀態
*/
public void turnNext()
{
int newStyle = 0;
for(int i = 0; i < STYLES.length; i ++)

for(int j = 0 ;j < STYLES[i].length; j++)
  {
   if(style == STYLES[i][j])
   {
        newStyle = STYLES[i][(j + 1)%BLOCK_STATUS_NUMBER];
        break;
    }
  }
  turnTo(newStyle);

}
/*
*經過旋轉變可否變爲newStyle狀態
*/
private synchronized boolean turnTo(int newStyle)
{
//erase();//擦除以後在判斷isTurnNextAble
if(!moving || !isTurnable(newStyle))
{

display();
     return false;

}

style=newStyle;
int key = 0x8000;

for(int i = 0; i < boxes.length; i ++)

for(int j = 0 ;j < boxes[i].length; j++)
  {
   boolean isColor = ((key & style) != 0 );
   boxes[i][j].setColor(isColor);
   key >>=1;
  }
  display();
  canvas.repaint();
  return true;

}
/*
*判斷經過旋轉可否變爲下一種狀態
*/
private boolean isTurnable(int newStyle)
{
erase();
int key = 0x8000;
for(int i = 0; i< boxes.length; i++)

for(int j=0; j<boxes[i].length; j++)
    {
     if((key & newStyle) != 0)
      {
        RussiaBox box = canvas.getBox(y + i, x + j);
        if(box == null || box.isColorBox())
            return false;
      }
      key >>= 1;
    }
    return true;

}
/*
*擦除當前方塊(只是設置isColor屬性,顏色並無清除,爲了判斷可否移動之用)
*/
/www.tengxunyun.me 轉載請告知/
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() )
      {
         RussiaBox box = canvas.getBox( y + i, x + j);
         if(box != null)
         box.setColor(false);
       }
     }

}
/*
*顯示當前方塊(其實只是設置Color屬性,在調用repaint方法時才真正顯示)
*/
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())
     {
      RussiaBox box = canvas.getBox( y + i, x + j);
      if(box != null)
       box.setColor( true );
     }
  }

}
}
package russia;

/*

  • 主遊戲類
    */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RussiaBlocksGame 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 DEFAULT_LEVEL = 5;//默認級別
public final static int MAX_LEVEL = 10;//最高級別
private int score=0,curLevelScore = 0;//總分和本級得分

private GameCanvas canvas;
private ControlPanel controlPanel;
private RussiaBlock block;

private int style = 0;
boolean playing = false;

private JMenuBar bar;
private JMenu gameMenu,controlMenu,windowStyleMenu,informationMenu;
private JMenuItem newGameItem,setBlockColorItem,setBgColorItem,

turnHardItem,turnEasyItem,exitItem;

private JMenuItem playItem,pauseItem,resumeItem,stopItem;
private JRadioButtonMenuItem windowsRadioItem,motifRadioItem,metalRadioItem;
private JMenuItem authorItem,helpItem;
private ButtonGroup buttonGroup;
/*

  • 構造函數
    */

public RussiaBlocksGame(String title)
{
super(title);

setSize(300,400);
Dimension scrSize=Toolkit.getDefaultToolkit().getScreenSize();
setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);

createMenu();
Container container=getContentPane();
container.setLayout(new BorderLayout());

canvas = GameCanvas.getCanvasInstance();
controlPanel = new ControlPanel(this);

container.add(canvas,BorderLayout.CENTER);
container.add(controlPanel,BorderLayout.EAST);

addWindowListener(
new WindowAdapter()
{

public void windowClosing(WindowEvent event)
{
 stopGame();
 System.exit(0);
}

}
);

addComponentListener(
new ComponentAdapter()
{

public void componentResized(ComponentEvent event)
{
 canvas.fanning();
}

}
);
canvas.fanning();
setVisible(true);
}
/*

  • 判斷遊戲是否正在進行
    */

public boolean isPlaying()
{

return playing;

}
/*

* 開始遊戲並設置按鈕和菜單項的可用性
*/

public void playGame()
{

play();
controlPanel.setPlayButtonEnabled(false);
playItem.setEnabled(false);

}
/*

* 暫停遊戲
*/

public void pauseGame()
{

if(block != null) block.pauseMove();
 controlPanel.setPauseButtonLabel(false);
 pauseItem.setEnabled(false);
 resumeItem.setEnabled(true);

}
/*

* 從暫停中恢復遊戲
*/

public void resumeGame()
{

if(block != null) block.resumeMove();
controlPanel.setPauseButtonLabel(true);
pauseItem.setEnabled(true);
resumeItem.setEnabled(false);

}
/*

* 中止遊戲
*/

public void stopGame()
{

if(block != null) block.stopMove();
playing = false;
controlPanel.setPlayButtonEnabled(true);
controlPanel.setPauseButtonLabel(true);
            playItem.setEnabled(true);

}
/*

* 獲得當前級別
*/

public int getLevel()
{

return controlPanel.getLevel();

}
/*

* 設置當前級別,並更新控制面板的顯示
*/

public void setLevel(int level)
{

if(level>0&&level<11)
controlPanel.setLevel(level);

}
/*

* 獲得當前總分數
*/

public int getScore()
{

if(canvas != null)
    return score;
 return 0;

}
/*

* 獲得本級得分
*/

public int getCurLevelScore()
{

if(canvas != null)
    return curLevelScore;
 return 0;

}
/*

* 更新等級
*/

public void levelUpdate()
{

int curLevel = getLevel();
if(curLevel < MAX_LEVEL && curLevelScore >= PER_LEVEL_SCORE)
{
  setLevel(curLevel + 1);
  curLevelScore -= PER_LEVEL_SCORE;
}

}
/*

* 得到當前得方塊
*/

public RussiaBlock getCurBlock() {

return block;

}
/*

* 開始遊戲
*/

private void play()
{

playing=true;
Thread thread = new Thread(new Game());
thread.start();
reset();

}
/*

* 重置
 */
 private void reset()
 {
  controlPanel.reset();
  canvas.reset();
            score = 0;
            curLevelScore = 0;
 }
/*
 * 宣告遊戲結束
 */

private void reportGameOver()
{

JOptionPane.showMessageDialog(this,"Game over!");

}
/*

* 建立菜單
*/

private void createMenu()
{
gameMenu = new JMenu("Game");
newGameItem = new JMenuItem("New Game");
setBlockColorItem = new JMenuItem("Set Block Color...");
setBgColorItem = new JMenuItem("Set BackGround Color...");
turnHardItem = new JMenuItem("Turn Harder");
turnEasyItem = new JMenuItem("Turn Easily");
exitItem = new JMenuItem("Exit");
gameMenu.add(newGameItem);

gameMenu.add(setBlockColorItem);
gameMenu.add(setBgColorItem);
gameMenu.add(turnHardItem);
gameMenu.add(turnEasyItem);
gameMenu.add(exitItem);   
/*www.panmum.com 轉載請告知*/

controlMenu = new JMenu("Control");

playItem = new JMenuItem("Play");
pauseItem = new JMenuItem("Pause");
resumeItem = new JMenuItem("Resume");
stopItem = new JMenuItem("Stop");
controlMenu.add(playItem);
controlMenu.add(pauseItem);
controlMenu.add(resumeItem);
controlMenu.add(stopItem);

windowStyleMenu = new JMenu("WindowStyle");
buttonGroup = new ButtonGroup();
windowsRadioItem = new JRadioButtonMenuItem("Windows");
motifRadioItem = new JRadioButtonMenuItem("Motif");
metalRadioItem = new JRadioButtonMenuItem("Mentel",true);
windowStyleMenu.add(windowsRadioItem);
buttonGroup.add(windowsRadioItem);
windowStyleMenu.add(motifRadioItem);
buttonGroup.add(motifRadioItem);
windowStyleMenu.add(metalRadioItem);
buttonGroup.add(metalRadioItem);

informationMenu = new JMenu("Information");
authorItem = new JMenuItem("Author:Fuliang");
helpItem = new JMenuItem("Help");
informationMenu.add(authorItem);
informationMenu.add(helpItem);

bar = new JMenuBar();
bar.add(gameMenu);

bar.add(controlMenu);
bar.add(windowStyleMenu);
bar.add(informationMenu);

addActionListenerToMenu();
setJMenuBar(bar);
}
/*

  • 添加菜單響應
    */

private void addActionListenerToMenu()
{
newGameItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

stopGame();
reset();
setLevel(DEFAULT_LEVEL);

}
});

setBlockColorItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

Color newBlockColor =
        JColorChooser.showDialog(RussiaBlocksGame.this,
                "Set color for block", canvas.getBlockColor());
if (newBlockColor != null)
 canvas.setBlockColor(newBlockColor);

}
});

setBgColorItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

Color newBgColor =
        JColorChooser.showDialog(RussiaBlocksGame.this,"Set color for block", 
                           canvas.getBgColor());
if (newBgColor != null)
 canvas.setBgColor(newBgColor);

}
});
/www.oksousou.com 轉載請告知/
turnHardItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

int curLevel = getLevel();
if (curLevel < MAX_LEVEL) setLevel(curLevel + 1);

}
});

turnEasyItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

int curLevel = getLevel();
if (curLevel > 1) setLevel(curLevel - 1);

}
});

exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

System.exit(0);

}
});
playItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

playGame();

}
});

pauseItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

pauseGame();

}
});

resumeItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

resumeGame();

}
});

stopItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

stopGame();

}
});

windowsRadioItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
controlPanel.fanning();

}
});

motifRadioItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
controlPanel.fanning();;

}
});

metalRadioItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {

String plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
controlPanel.fanning();

}
});

}
/*

* 設定窗口風格
*/

private void setWindowStyle(String plaf)
{
try {
UIManager.setLookAndFeel(plaf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
e.printStackTrace();
}
}
/www.quzhuanpan.com 轉載請告知/
private class Game implements Runnable
{
/*

  • (non-Javadoc)

  • @see java.lang.Runnable#run()

  • 遊戲線程的run函數
    */

public void run()
{
int col=(int)(Math.random()*(canvas.getCols()-3));
style=RussiaBlock.STYLES(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER);

while (playing) {
if (block != null) {    //第一次循環時,block爲空
 if (block.isAlive()) {
  try {
   Thread.sleep(100);
  } catch (InterruptedException ie) {
   ie.printStackTrace();
  }
  continue;
 }
}

checkFullLine();

if (isGameOver()) {     //檢查遊戲是否應該結束了
 playItem.setEnabled(true);
 pauseItem.setEnabled(true);
 resumeItem.setEnabled(false);
 controlPanel.setPlayButtonEnabled(true);
 controlPanel.setPauseButtonLabel(true);

 reportGameOver();
 return;

}
block = new RussiaBlock(-1, col, getLevel(),style);
block.start();

col=(int)(Math.random()*(canvas.getCols()-3));
style=RussiaBlock.STYLES(int)(Math.random()*RussiaBlock.BLOCK_KIND_NUMBER);

controlPanel.setBlockStyle(style);

}
}
/*

  • 判斷是否能消去整行
    */

public void checkFullLine()
{
for (int i = 0; i < canvas.getRows(); i++) {

int row = -1;
boolean fullLineColorBox = true;
for (int j = 0; j < canvas.getCols(); j++) {
 if (!canvas.getBox(i, j).isColorBox()) {
  fullLineColorBox = false;
  break;
 }
}
if (fullLineColorBox) {
 curLevelScore += PER_LINE_SCORE;
 score += PER_LINE_SCORE;
 row = i--;
 canvas.removeLine(row);
}

}
}
/*

  • 判斷遊戲是否結束
    */

private boolean isGameOver() {
for (int i = 0; i < canvas.getCols(); i++) {

RussiaBox box = canvas.getBox(0, i);
if (box.isColorBox()) return true;

}
return false;
}
}
public static void main(String[] args)
{
new RussiaBlocksGame("Russia Blocks Game");
}
}
package russia;

/*
*虛擬的單個方格類,控制方格的顏色
*/
public class RussiaBox implements Cloneable
{
private boolean isColor;

public RussiaBox(boolean isColor)
{
this.isColor = isColor;
}
/*
*設置顏色
*/
public void setColor(boolean isColor)
{
this.isColor=isColor;
}
/*
*返回顏色
*/
/www.oksousou.com 轉載請告知/
public boolean isColorBox()
{
return isColor;
}
/*

  • @see java.lang.Object#clone()
    */

public Object clone() { Object o = null; try { o=super.clone(); }catch(CloneNotSupportedException e) { e.printStackTrace(); } return o; }}

相關文章
相關標籤/搜索