?? ersblocksgame.java
字號:
/**
* File: ErsBlocksGame.java
* User: 隋國丞
* Date: 2004.12.3
* Describe: 俄羅斯方塊的 Java 實現(xiàn)
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 游戲主類,繼承自JFrame類,負責(zé)游戲的全局控制。
* 內(nèi)含
* 1, 一個GameCanvas畫布類的實例引用,
* 2, 一個保存當(dāng)前活動塊(ErsBlock)實例的引用,
* 3, 一個保存當(dāng)前控制面板(ControlPanel)實例的引用;
*/
public class ErsBlocksGame extends JFrame {
/**
* 每填滿一行計多少分
*/
public final static int PER_LINE_SCORE = 100;
/**
* 積多少分以后能升級
*/
public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20;
/**
* 最大級數(shù)是10級
*/
public final static int MAX_LEVEL = 10;
/**
* 默認級數(shù)是5
*/
public final static int DEFAULT_LEVEL = 5;
private GameCanvas canvas;
private ErsBlock block;
private boolean playing = false;
private ControlPanel ctrlPanel;
private JMenuBar bar = new JMenuBar();
private JMenu
mGame = new JMenu("Game"),
mControl = new JMenu("Control"),
mWindowStyle = new JMenu("WindowStyle"),
mInfo = new JMenu("Information");
private JMenuItem
miNewGame = new JMenuItem("New Game"),
miSetBlockColor = new JMenuItem("Set Block Color ..."),
miSetBackColor = new JMenuItem("Set Background Color ..."),
miTurnHarder = new JMenuItem("Turn up the level"),
miTurnEasier = new JMenuItem("Turn down the level"),
miExit = new JMenuItem("Eixt"),
miPlay = new JMenuItem("Play"),
miPause = new JMenuItem("Pause"),
miResume = new JMenuItem("Resume"),
miStop = new JMenuItem("Stop"),
miAuthor = new JMenuItem("Author : apple@radiantek.com"),
miSourceInfo = new JMenuItem("You can get the source code / document by email");
private JCheckBoxMenuItem
miAsWindows = new JCheckBoxMenuItem("Windows"),
miAsMotif = new JCheckBoxMenuItem("Motif"),
miAsMetal = new JCheckBoxMenuItem("Metal", true);
/**
* 主游戲類的構(gòu)造函數(shù)
* @param title String,窗口標(biāo)題
*/
public ErsBlocksGame(String title) {
super(title);
setSize(315, 392);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
setLocation((scrSize.width - getSize().width) / 2,
(scrSize.height - getSize().height) / 2);
createMenu();
Container container = getContentPane();
container.setLayout(new BorderLayout(6, 0));
canvas = new GameCanvas(20, 12);
ctrlPanel = new ControlPanel(this);
container.add(canvas, BorderLayout.CENTER);
container.add(ctrlPanel, BorderLayout.EAST);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
stopGame();
System.exit(0);
}
});
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
canvas.fanning();
}
});
show();
canvas.fanning();
}
/**
* 讓游戲“復(fù)位”
*/
public void reset() {
ctrlPanel.reset();
canvas.reset();
}
/**
* 判斷游戲是否還在進行
* @return boolean, true-還在運行,false-已經(jīng)停止
*/
public boolean isPlaying() {
return playing;
}
/**
* 得到當(dāng)前活動的塊
* @return ErsBlock, 當(dāng)前活動塊的引用
*/
public ErsBlock getCurBlock() {
return block;
}
/**
* 得到當(dāng)前畫布
* @return GameCanvas, 當(dāng)前畫布的引用
*/
public GameCanvas getCanvas() {
return canvas;
}
/**
* 開始游戲
*/
public void playGame() {
play();
ctrlPanel.setPlayButtonEnable(false);
miPlay.setEnabled(false);
ctrlPanel.requestFocus();
}
/**
* 游戲暫停
*/
public void pauseGame() {
if (block != null) block.pauseMove();
ctrlPanel.setPauseButtonLabel(false);
miPause.setEnabled(false);
miResume.setEnabled(true);
}
/**
* 讓暫停中的游戲繼續(xù)
*/
public void resumeGame() {
if (block != null) block.resumeMove();
ctrlPanel.setPauseButtonLabel(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.requestFocus();
}
/**
* 用戶停止游戲
*/
public void stopGame() {
playing = false;
if (block != null) block.stopMove();
miPlay.setEnabled(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.setPlayButtonEnable(true);
ctrlPanel.setPauseButtonLabel(true);
}
/**
* 得到當(dāng)前游戲者設(shè)置的游戲難度
* @return int, 游戲難度1-MAX_LEVEL
*/
public int getLevel() {
return ctrlPanel.getLevel();
}
/**
* 讓用戶設(shè)置游戲難度
* @param level int, 游戲難度1-MAX_LEVEL
*/
public void setLevel(int level) {
if (level < 11 && level > 0) ctrlPanel.setLevel(level);
}
/**
* 得到游戲積分
* @return int, 積分。
*/
public int getScore() {
if (canvas != null) return canvas.getScore();
return 0;
}
/**
* 得到自上次升級以來的游戲積分,升級以后,此積分清零
* @return int, 積分。
*/
public int getScoreForLevelUpdate() {
if (canvas != null) return canvas.getScoreForLevelUpdate();
return 0;
}
/**
* 當(dāng)分?jǐn)?shù)累計到一定的數(shù)量時,升一次級
* @return boolean, ture-update successufl, false-update fail
*/
public boolean levelUpdate() {
int curLevel = getLevel();
if (curLevel < MAX_LEVEL) {
setLevel(curLevel + 1);
canvas.resetScoreForLevelUpdate();
return true;
}
return false;
}
/**
* 游戲開始
*/
private void play() {
reset();
playing = true;
Thread thread = new Thread(new Game());
thread.start();
}
/**
* 報告游戲結(jié)束了
*/
private void reportGameOver() {
JOptionPane.showMessageDialog(this, "Game Over!");
}
/**
* 建立并設(shè)置窗口菜單
*/
private void createMenu() {
bar.add(mGame);
bar.add(mControl);
bar.add(mWindowStyle);
bar.add(mInfo);
mGame.add(miNewGame);
mGame.addSeparator();
mGame.add(miSetBlockColor);
mGame.add(miSetBackColor);
mGame.addSeparator();
mGame.add(miTurnHarder);
mGame.add(miTurnEasier);
mGame.addSeparator();
mGame.add(miExit);
mControl.add(miPlay);
mControl.add(miPause);
mControl.add(miResume);
mControl.add(miStop);
mWindowStyle.add(miAsWindows);
mWindowStyle.add(miAsMotif);
mWindowStyle.add(miAsMetal);
mInfo.add(miAuthor);
mInfo.add(miSourceInfo);
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,
"Set color for block", canvas.getBlockColor());
if (newFrontColor != null)
canvas.setBlockColor(newFrontColor);
}
});
miSetBackColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Color newBackColor =
JColorChooser.showDialog(ErsBlocksGame.this,
"Set color for block", canvas.getBackgroundColor());
if (newBackColor != null)
canvas.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);
canvas.fanning();
ctrlPanel.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);
canvas.fanning();
ctrlPanel.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);
canvas.fanning();
ctrlPanel.fanning();
miAsWindows.setState(false);
miAsMetal.setState(true);
miAsMotif.setState(false);
}
});
}
/**
* 根據(jù)字串設(shè)置窗口外觀
* @param plaf String, 窗口外觀的描述
*/
private void setWindowStyle(String plaf) {
try {
UIManager.setLookAndFeel(plaf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
}
}
/**
* 一輪游戲過程,實現(xiàn)了Runnable接口
* 一輪游戲是一個大循環(huán),在這個循環(huán)中,每隔100毫秒,
* 檢查游戲中的當(dāng)前塊是否已經(jīng)到底了,如果沒有,
* 就繼續(xù)等待。如果到底了,就看有沒有全填滿的行,
* 如果有就刪除它,并為游戲者加分,同時隨機產(chǎn)生一個
* 新的當(dāng)前塊,讓它自動下落。
* 當(dāng)新產(chǎn)生一個塊時,先檢查畫布最頂上的一行是否已經(jīng)
* 被占了,如果是,可以判斷Game Over了。
*/
private class Game implements Runnable {
public void run() {
int col = (int) (Math.random() * (canvas.getCols() - 3)),
style = ErsBlock.STYLES[(int) (Math.random() * 7)][(int) (Math.random() * 4)];
while (playing) {
if (block != null) { //第一次循環(huán)時,block為空
if (block.isAlive()) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
continue;
}
}
checkFullLine(); //檢查是否有全填滿的行
if (isGameOver()) { //檢查游戲是否應(yīng)該結(jié)束了
miPlay.setEnabled(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.setPlayButtonEnable(true);
ctrlPanel.setPauseButtonLabel(true);
reportGameOver();
return;
}
block = new ErsBlock(style, -1, col, getLevel(), canvas);
block.start();
col = (int) (Math.random() * (canvas.getCols() - 3));
style = ErsBlock.STYLES[(int) (Math.random() * 7)][(int) (Math.random() * 4)];
ctrlPanel.setTipStyle(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) {
row = i--;
canvas.removeLine(row);
}
}
}
/**
* 根據(jù)最頂行是否被占,判斷游戲是否已經(jīng)結(jié)束了。
* @return boolean, true-游戲結(jié)束了,false-游戲未結(jié)束
*/
private boolean isGameOver() {
for (int i = 0; i < canvas.getCols(); i++) {
ErsBox box = canvas.getBox(0, i);
if (box.isColorBox()) return true;
}
return false;
}
}
/**
* 程序入口函數(shù)
* @param args String[], 附帶的命令行參數(shù)
*/
public static void main(String[] args) {
new ErsBlocksGame("Russia Blocks by apple@radiantek.com");
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -