這是java課最后做的課程設(shè)計(jì),由于java是初學(xué)的,所以做的時(shí)候有參考一些技術(shù)大牛的博客,在此表示感謝。
發(fā)在這里跟大家交流學(xué)習(xí)一下。
如需要完整工程文件、說(shuō)明文檔以及可運(yùn)行jar文件,下載地址:點(diǎn)擊打開(kāi)鏈接
RussianBlocksGame.java
package RussiaBlocksGame; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; /** * 游戲主類,繼承自JFrame類,負(fù)責(zé)游戲的全局控制。 內(nèi)含: 1.一個(gè)GameCanvas畫(huà)布類的實(shí)例對(duì)象, * 2.一個(gè)保存當(dāng)前活動(dòng)塊(RussiaBlock)實(shí)例的對(duì)象; 3.一個(gè)保存當(dāng)前控制面板(ControlPanel)實(shí)例的對(duì)象; */ public class RussiaBlocksGame extends JFrame { private static final long serialVersionUID = -7332245439279674749L; /** * 每填滿一行計(jì)多少分 */ public final static int PER_LINE_SCORE = 100; /** * 積多少分以后能升級(jí) */ public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20; /** * 最大級(jí)數(shù)是10級(jí) */ public final static int MAX_LEVEL = 10; /** * 默認(rèn)級(jí)數(shù)是2 */ public final static int DEFAULT_LEVEL = 2; private GameCanvas canvas; private ErsBlock block; private boolean playing = false; private ControlPanel ctrlPanel; //初始化菜單欄 private JMenuBar bar = new JMenuBar(); private JMenu mGame = new JMenu(" 游戲"), mControl = new JMenu(" 控制"), mInfo = new JMenu("幫助"); private JMenuItem miNewGame = new JMenuItem("新游戲"), miSetBlockColor = new JMenuItem("設(shè)置方塊顏色..."), miSetBackColor = new JMenuItem("設(shè)置背景顏色..."), miTurnHarder = new JMenuItem("升高游戲難度"), miTurnEasier = new JMenuItem("降低游戲難度"), miExit = new JMenuItem("退出"), miPlay = new JMenuItem("開(kāi)始"), miPause = new JMenuItem("暫停"), miResume = new JMenuItem("恢復(fù)"), miStop = new JMenuItem("終止游戲"), miRule = new JMenuItem("游戲規(guī)則"), miAuthor = new JMenuItem("關(guān)于本游戲"); /** * 建立并設(shè)置窗口菜單 */ private void creatMenu() { bar.add(mGame); bar.add(mControl); 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); miPlay.setEnabled(true); mControl.add(miPause); miPause.setEnabled(false); mControl.add(miResume); miResume.setEnabled(false); mControl.add(miStop); miStop.setEnabled(false); mInfo.add(miRule); mInfo.add(miAuthor); setJMenuBar(bar); miNewGame.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { stopGame(); reset(); setLevel(DEFAULT_LEVEL); } }); //設(shè)置方塊顏色 miSetBlockColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color newFrontColor = JColorChooser.showDialog(RussiaBlocksGame.this, "設(shè)置方塊顏色", canvas.getBlockColor()); if (newFrontColor != null) { canvas.setBlockColor(newFrontColor); } } }); //設(shè)置背景顏色 miSetBackColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color newBackColor = JColorChooser.showDialog(RussiaBlocksGame.this, "設(shè)置背景顏色", canvas.getBackgroundColor()); if (newBackColor != null) { canvas.setBackgroundColor(newBackColor); } } }); //定義菜單欄"關(guān)于"的功能,彈出確認(rèn)框。 miAuthor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "軟件工程(4)班/n3115005372/n楊宇杰/n©一切解釋權(quán)歸楊宇杰所有", "關(guān)于俄羅斯方塊 - 2016", 1); } }); //游戲規(guī)則說(shuō)明 miRule.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "由小方塊組成的不同形狀的板塊陸續(xù)從屏幕上方落下來(lái),/n玩家通過(guò)調(diào)整板塊的位置和方向,使它們?cè)谄聊坏撞科?n出完整的一條或幾條。這些完整的橫條會(huì)隨即消失,給新/n落下來(lái)的板塊騰出空間,與此同時(shí),玩家得到分?jǐn)?shù)獎(jiǎng)勵(lì)。/n沒(méi)有被消除掉的方塊不斷堆積起來(lái),一旦堆到屏幕頂端,/n玩家便告輸,游戲結(jié)束。", "游戲規(guī)則", 1); } }); //增加難度 miTurnHarder.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int curLevel = getLevel(); if (!playing && curLevel < MAX_LEVEL) { setLevel(curLevel + 1); } } }); //減少難度 miTurnEasier.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int curLevel = getLevel(); if (!playing && curLevel > 1) { setLevel(curLevel - 1); } } }); //退出按鈕動(dòng)作響應(yīng) miExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); } /** * 主游戲類的構(gòu)造方法 * * @param title String ,窗口標(biāo)題 */ public RussiaBlocksGame(String title) { super(title); //設(shè)置標(biāo)題 setSize(500, 600); //設(shè)置窗口大小 setLocationRelativeTo(null); //設(shè)置窗口居中 creatMenu(); Container container = getContentPane(); //創(chuàng)建菜單欄 container.setLayout(new BorderLayout(6, 0)); //設(shè)置窗口的布局管理器 canvas = new GameCanvas(20, 15); //新建游戲畫(huà)布 ctrlPanel = new ControlPanel(this); //新建控制面板 container.add(canvas, BorderLayout.CENTER); //左邊加上畫(huà)布 container.add(ctrlPanel, BorderLayout.EAST); //右邊加上控制面板 //注冊(cè)窗口事件。當(dāng)點(diǎn)擊關(guān)閉按鈕時(shí),結(jié)束游戲,系統(tǒng)退出。 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { stopGame(); System.exit(0); } }); //根據(jù)窗口大小,自動(dòng)調(diào)節(jié)方格的尺寸 addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent ce) { canvas.adjust(); } }); setVisible(true); canvas.adjust(); } /** * 讓游戲復(fù)位 */ public void reset() { //畫(huà)布復(fù)位,控制面板復(fù)位 ctrlPanel.setPlayButtonEnable(true); ctrlPanel.setPauseButtonEnable(false); ctrlPanel.setPauseButtonLabel(true); ctrlPanel.setStopButtonEnable(false); ctrlPanel.setTurnLevelDownButtonEnable(true); ctrlPanel.setTurnLevelUpButtonEnable(true); miPlay.setEnabled(true); miPause.setEnabled(false); miResume.setEnabled(false); miStop.setEnabled(false); ctrlPanel.reset(); canvas.reset(); } /** * 判斷游戲是否還在進(jìn)行 * * @return boolean,true -還在運(yùn)行,false-已經(jīng)停止 */ public boolean isPlaying() { return playing; } /** * 得到當(dāng)前活動(dòng)的塊 * * @return ErsBlock,當(dāng)前活動(dòng)塊的引用 */ public ErsBlock getCurBlock() { return block; } /** * 得到當(dāng)前畫(huà)布 * * @return GameCanvas,當(dāng)前畫(huà)布的引用 */ public GameCanvas getCanvas() { return canvas; } /** * 開(kāi)始游戲 */ public void playGame() { play(); ctrlPanel.setPlayButtonEnable(false); ctrlPanel.setPauseButtonEnable(true); ctrlPanel.setPauseButtonLabel(true); ctrlPanel.setStopButtonEnable(true); ctrlPanel.setTurnLevelDownButtonEnable(false); ctrlPanel.setTurnLevelUpButtonEnable(false); miStop.setEnabled(true); miTurnHarder.setEnabled(false); miTurnEasier.setEnabled(false); ctrlPanel.requestFocus(); //設(shè)置焦點(diǎn)在控制面板上 } /** * 游戲暫停 */ public void pauseGame() { if (block != null) { block.pauseMove(); } ctrlPanel.setPlayButtonEnable(false); ctrlPanel.setPauseButtonLabel(false); ctrlPanel.setStopButtonEnable(true); miPlay.setEnabled(false); miPause.setEnabled(false); miResume.setEnabled(true); miStop.setEnabled(true); } /** * 讓暫停中的游戲繼續(xù) */ public void resumeGame() { if (block != null) { block.resumeMove(); } ctrlPanel.setPlayButtonEnable(false); ctrlPanel.setPauseButtonEnable(true); ctrlPanel.setPauseButtonLabel(true); miPause.setEnabled(true); miResume.setEnabled(false); ctrlPanel.requestFocus(); } /** * 用戶停止游戲 */ public void stopGame() { playing = false; if (block != null) { block.stopMove(); } ctrlPanel.setPlayButtonEnable(true); ctrlPanel.setPauseButtonEnable(false); ctrlPanel.setPauseButtonLabel(true); ctrlPanel.setStopButtonEnable(false); ctrlPanel.setTurnLevelDownButtonEnable(true); ctrlPanel.setTurnLevelUpButtonEnable(true); miPlay.setEnabled(true); miPause.setEnabled(false); miResume.setEnabled(false); miStop.setEnabled(false); miTurnHarder.setEnabled(true); miTurnEasier.setEnabled(true); reset();//重置畫(huà)布和控制面板 } /** * 得到游戲者設(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; } /** * 得到自上次升級(jí)以來(lái)的游戲積分,升級(jí)以后,此積分清零 * * @return int,積分 */ public int getScoreForLevelUpdate() { if (canvas != null) { return canvas.getScoreForLevelUpdate(); } return 0; } /** * 當(dāng)積分累積到一定數(shù)值時(shí),升一次級(jí) * * @return Boolean,true-update succeed,false-update fail */ public boolean levelUpdate() { int curLevel = getLevel(); if (curLevel < MAX_LEVEL) { setLevel(curLevel + 1); canvas.resetScoreForLevelUpdate(); return true; } return false; } /** * 游戲開(kāi)始 */ private void play() { reset(); playing = true; Thread thread = new Thread(new Game());//啟動(dòng)游戲線程 thread.start(); } /** * 報(bào)告游戲結(jié)束了 */ private void reportGameOver() { new gameOverDialog(this, "俄羅斯方塊", "游戲結(jié)束,您的得分為" + canvas.getScore()); } /** * 一輪游戲過(guò)程,實(shí)現(xiàn)了Runnable接口 一輪游戲是一個(gè)大循環(huán),在這個(gè)循環(huán)中,每隔100毫秒, 檢查游戲中的當(dāng)前塊是否已經(jīng)到底了,如果沒(méi)有, * 就繼續(xù)等待。如果到底了,就看有沒(méi)有全填滿的行, 如果有就刪除它,并為游戲者加分,同時(shí)隨機(jī)產(chǎn)生一個(gè)新的當(dāng)前塊并讓它自動(dòng)落下。 * 當(dāng)新產(chǎn)生一個(gè)塊時(shí),先檢查畫(huà)布最頂上的一行是否已經(jīng)被占了,如果是,可以判斷Game Over 了。 */ private class Game implements Runnable { @Override public void run() { int col = (int) (Math.random() * (canvas.getCols() - 3));//隨機(jī)生成方塊出現(xiàn)的位置 int style = ErsBlock.STYLES[ (int) (Math.random() * 7)][(int) (Math.random() * 4)];//隨機(jī)生成一種形狀的方塊 while (playing) { if (block != null) { //第一次循環(huán)時(shí),block為空 if (block.isAlive()) { try { Thread.currentThread(); Thread.sleep(500); } catch (InterruptedException ie) { ie.printStackTrace(); } continue; } } checkFullLine(); //檢查是否有全填滿的行 if (isGameOver()) { reportGameOver(); miPlay.setEnabled(true); miPause.setEnabled(false); miResume.setEnabled(false); miStop.setEnabled(false); ctrlPanel.setPlayButtonEnable(true); ctrlPanel.setPauseButtonLabel(false); ctrlPanel.setStopButtonEnable(false); 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); } } //檢查畫(huà)布中是否有全填滿的行,如果有就刪之 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; } } /** * 定義GameOver對(duì)話框。 */ @SuppressWarnings("serial") private class gameOverDialog extends JDialog implements ActionListener { private JButton againButton, exitButton; private Border border = new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); public gameOverDialog(JFrame parent, String title, String message) { super(parent, title, true); if (parent != null) { setSize(240, 120); this.setLocationRelativeTo(parent); JPanel messagePanel = new JPanel(); messagePanel.add(new JLabel(message)); messagePanel.setBorder(border); Container container = this.getContentPane(); container.setLayout(new GridLayout(2, 0, 0, 10)); container.add(messagePanel); JPanel choosePanel = new JPanel(); choosePanel.setLayout(new GridLayout(0, 2, 4, 0)); container.add(choosePanel); againButton = new JButton("再玩一局"); exitButton = new JButton("退出游戲"); choosePanel.add(new JPanel().add(againButton)); choosePanel.add(new JPanel().add(exitButton)); choosePanel.setBorder(border); } againButton.addActionListener(this); exitButton.addActionListener(this); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == againButton) { this.setVisible(false); reset(); } else if (e.getSource() == exitButton) { stopGame(); System.exit(0); } } } }
GameCanvas.java
package RussiaBlocksGame; import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; /** * 畫(huà)布類,內(nèi)有<行數(shù)>*<列數(shù)> 個(gè)方格類實(shí)例。 繼承自JPanel類。 ErsBlock線程類動(dòng)態(tài)改變畫(huà)布類的方格顏色,畫(huà)布類通過(guò) * 檢查方格顏色來(lái)體現(xiàn)ErsBlock塊的移動(dòng)情況。 */ public class GameCanvas extends JPanel { private static final long serialVersionUID = 6732901391026089276L; private Color backColor = Color.darkGray, frontColor = Color.WHITE; private int rows, cols, score = 0, scoreForLevelUpdate = 0; private ErsBox[][] boxes; private int boxWidth, boxHeight; /** * 畫(huà)布類的構(gòu)造函數(shù) * * @param rows int,畫(huà)布的行數(shù) * @param cols int,畫(huà)布的列數(shù) 行數(shù)和列數(shù)決定著畫(huà)布擁有方格的數(shù)目 */ 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))); } /** * 畫(huà)布類的構(gòu)造函數(shù) * * @param rows * @param cols * @param backColor * @param frontColor */ public GameCanvas(int rows, int cols, Color backColor, Color frontColor) { this(rows, cols); this.backColor = backColor; this.frontColor = frontColor; } /** * 設(shè)置游戲背景色彩 * * @param backColor Color,背景色彩 */ public void setBackgroundColor(Color backColor) { this.backColor = backColor; } /** * 取得游戲背景色彩 * * @return Color ,背景色彩 */ public Color getBackgroundColor() { return backColor; } /** * 設(shè)置游戲方塊顏色 * * @param frontColor Color,方塊顏色 */ public void setBlockColor(Color frontColor) { this.frontColor = frontColor; } /** * 取得游戲方塊色彩 * * @return Color,方塊顏色 */ public Color getBlockColor() { return frontColor; } /** * 取得畫(huà)布中方格的行數(shù) * * @return */ public int getRows() { return rows; } /** * 取得畫(huà)布中方格的列數(shù) * * @return int,方格的列數(shù) */ public int getCols() { return cols; } /** * 取得游戲成績(jī) * * @return int, 分?jǐn)?shù) */ public int getScore() { return score; } /** * 取得自上一次升級(jí)后的積分 * * @return int ,上一次升級(jí)后的積分 */ public int getScoreForLevelUpdate() { return scoreForLevelUpdate; } /** * 升級(jí)后,將上一次升級(jí)以來(lái)的積分清零 */ public void resetScoreForLevelUpdate() { scoreForLevelUpdate -= RussiaBlocksGame.PER_LEVEL_SCORE; } /** * 得到某一行某一列的方格引用 * * @return 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類的函數(shù),畫(huà)組件。 * * @param g 圖形設(shè)備環(huán)境 */ @Override 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); } } } /** * 根據(jù)窗口大小,自動(dòng)調(diào)節(jié)方格的尺寸 */ public void adjust() { boxWidth = getSize().width / cols; boxHeight = getSize().height / rows; } /** * 當(dāng)一行被游戲者疊滿后,將此行清除,并為游戲者加分 * * @param row int,要清除的行,是由ErsBoxesGame類計(jì)算的 */ 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(); //將上一行的方塊顏色克隆下來(lái), } //即消去一行方塊 } score += RussiaBlocksGame.PER_LEVEL_SCORE; scoreForLevelUpdate += RussiaBlocksGame.PER_LEVEL_SCORE; repaint(); } /** * 重置畫(huà)布,置積分為零 */ 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(); } }
ControlPanel.java
package RussiaBlocksGame; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; /** * 控制面板類,繼承自JPanel。 上邊安放預(yù)顯窗口,等級(jí),得分,控制按鈕 主要用來(lái)控制游戲進(jìn)程。 */ class ControlPanel extends JPanel { private static final long serialVersionUID = 3900659640646175724L; private JTextField tfLevel = new JTextField("" + RussiaBlocksGame.DEFAULT_LEVEL), tfScore = new JTextField(" 0"), tfTime = new JTextField(" "); private JButton btPlay = new JButton(" 開(kāi)始"), btPause = new JButton(" 暫停"), btStop = new JButton("終止游戲"), btTurnLevelUp = new JButton(" 增加難度"), btTurnLevelDown = 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(6, 1)); private Timer timer; private Border border = new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); /** * 控制面板類的構(gòu)造函數(shù) * * @param game ErsBlocksGame,ErsBlocksGame 類的一個(gè)實(shí)例引用 方便直接控制ErsBlocksGame類的行為。 */ public ControlPanel(final RussiaBlocksGame game) { setLayout(new GridLayout(3, 1, 0, 2)); plTip.add(new JLabel(" 下一個(gè)方塊"), BorderLayout.NORTH); //添加組件 plTip.add(plTipBlock); plTip.setBorder(border); plInfo.add(new JLabel(" 難度系數(shù)")); plInfo.add(tfLevel); plInfo.add(new JLabel(" 得分")); plInfo.add(tfScore); plInfo.setBorder(border); plButton.add(btPlay); btPlay.setEnabled(true); plButton.add(btPause); btPause.setEnabled(false); plButton.add(btStop); btStop.setEnabled(false); plButton.add(btTurnLevelUp); plButton.add(btTurnLevelDown); plButton.add(tfTime); plButton.setBorder(border); tfLevel.setEditable(false); tfScore.setEditable(false); tfTime.setEditable(false); add(plTip); add(plInfo); add(plButton); addKeyListener(new KeyAdapter() { @Override 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; } } }); btPlay.addActionListener(new ActionListener() { //開(kāi)始游戲 @Override public void actionPerformed(ActionEvent ae) { game.playGame(); } }); btPause.addActionListener(new ActionListener() { //暫停游戲 @Override public void actionPerformed(ActionEvent ae) { if (btPause.getText().equals(" 暫停")) { game.pauseGame(); } else { game.resumeGame(); } } }); btStop.addActionListener(new ActionListener() { //停止游戲 @Override public void actionPerformed(ActionEvent ae) { game.stopGame(); } }); btTurnLevelUp.addActionListener(new ActionListener() { //升高難度 @Override public void actionPerformed(ActionEvent ae) { try { int level = Integer.parseInt(tfLevel.getText()); if (level < RussiaBlocksGame.MAX_LEVEL) { tfLevel.setText("" + (level + 1)); } } catch (NumberFormatException e) { } requestFocus(); } }); btTurnLevelDown.addActionListener(new ActionListener() { //降低游戲難度 @Override 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() { @Override public void componentResized(ComponentEvent ce) { plTipBlock.adjust(); } }); timer = new Timer(1000, new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { DateFormat format = new SimpleDateFormat("時(shí)間:HH:mm:ss"); //系統(tǒng)獲得時(shí)間 Date date = new Date(); tfTime.setText(format.format(date)); tfScore.setText("" + game.getScore()); int ScoreForLevelUpdate = //判斷當(dāng)前分?jǐn)?shù)是否能升級(jí) game.getScoreForLevelUpdate(); if (ScoreForLevelUpdate >= RussiaBlocksGame.PER_LEVEL_SCORE && ScoreForLevelUpdate > 0) { game.levelUpdate(); } } }); timer.start(); } /** * 設(shè)置預(yù)顯窗口的樣式 * * @param style int,對(duì)應(yīng)ErsBlock類的STYLES中的28個(gè)值 */ public void setTipStyle(int style) { plTipBlock.setStyle(style); } /** * 取得用戶設(shè)置的游戲等級(jí)。 * * @return int ,難度等級(jí),1-ErsBlocksGame.MAX_LEVEL */ public int getLevel() { int level = 0; try { level = Integer.parseInt(tfLevel.getText()); } catch (NumberFormatException e) { } return level; } /** * 讓用戶修改游戲難度等級(jí)。 * * @param level 修改后的游戲難度等級(jí) */ public void setLevel(int level) { if (level > 0 && level < 11) { tfLevel.setText("" + level); } } /** * 設(shè)置“開(kāi)始”按鈕的狀態(tài)。 */ public void setPlayButtonEnable(boolean enable) { btPlay.setEnabled(enable); } public void setPauseButtonEnable(boolean enable) { btPause.setEnabled(enable); } public void setPauseButtonLabel(boolean pause) { btPause.setText(pause ? " 暫停" : " 繼續(xù)"); } public void setStopButtonEnable(boolean enable) { btStop.setEnabled(enable); } public void setTurnLevelUpButtonEnable(boolean enable) { btTurnLevelUp.setEnabled(enable); } public void setTurnLevelDownButtonEnable(boolean enable) { btTurnLevelDown.setEnabled(enable); } /** * 重置控制面板 */ public void reset() { tfScore.setText(" 0"); plTipBlock.setStyle(0); } /** * 重新計(jì)算TipPanel里的boxes[][]里的小框的大小 */ public void adjust() { plTipBlock.adjust(); } /** * 預(yù)顯窗口的實(shí)現(xiàn)細(xì)節(jié)類 */ public class TipPanel extends JPanel { //TipPanel用來(lái)顯示下一個(gè)將要出現(xiàn)方塊的形狀 private static final long serialVersionUID = 5160553671436997616L; private Color backColor = Color.darkGray, frontColor = Color.WHITE; private ErsBox[][] boxes = new ErsBox[ErsBlock.BOXES_ROWS][ErsBlock.BOXES_COLS]; private int style, boxWidth, boxHeight; private boolean isTiled = false; /** * 預(yù)顯示窗口類構(gòu)造函數(shù) */ 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); } } } /** * 設(shè)置預(yù)顯示窗口的方塊樣式 * * @param style int,對(duì)應(yīng)ErsBlock類的STYLES中的28個(gè)值 */ public void setStyle(int style) { this.style = style; repaint(); } /** * 覆蓋JComponent類的函數(shù),畫(huà)組件。 * * @param g 圖形設(shè)備環(huán)境 */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (!isTiled) { adjust(); } int key = 0x8000; for (int i = 0; i < boxes.length; i++) { for (int j = 0; j < boxes[i].length; j++) { Color color = ((key & style) != 0 ? frontColor : backColor); g.setColor(color); g.fill3DRect(j * boxWidth, i * boxHeight, boxWidth, boxHeight, true); key >>= 1; } } } /** * g根據(jù)窗口的大小,自動(dòng)調(diào)整方格的尺寸 */ public void adjust() { boxWidth = getSize().width / ErsBlock.BOXES_COLS; boxHeight = getSize().height / ErsBlock.BOXES_ROWS; isTiled = true; } } }
ErsBox.java
package RussiaBlocksGame; import java.awt.Dimension; /** * 方格類,是組成塊的基本元素,用自己的顏色來(lái)表示塊的外觀 */ public class ErsBox implements Cloneable { private boolean isColor; private Dimension size = new Dimension(); /** * 方格類的構(gòu)造函數(shù), * * @param isColor 是不是用前景色來(lái)為此方格著色 true前景色,false 用背景色 */ public ErsBox(boolean isColor) { this.isColor = isColor; } /** * 此方格是不是用前景色表現(xiàn) * * @return boolean ,true用前景色表現(xiàn),false 用背景色表現(xiàn) */ public boolean isColorBox() { return isColor; } /** * 設(shè)置方格的顏色, * * @param isColor boolean ,true用前景色表現(xiàn),false 用背景色表現(xiàn) */ public void setColor(boolean isColor) { this.isColor = isColor; } /** * 得到此方格的尺寸 * * @return Dimension ,方格的尺寸 */ public Dimension getSize() { return size; } /** * 設(shè)置方格的尺寸, * * @param size Dimension ,方格的尺寸 */ public void setSize(Dimension size) { this.size = size; } /** * 覆蓋Object的Object clone(),實(shí)現(xiàn)克隆 * * @return Object,克隆的結(jié)果 */ @Override public Object clone() { Object cloned = null; try { cloned = super.clone(); } catch (Exception ex) { ex.printStackTrace(); } return cloned; } }
ErsBlock.java
package RussiaBlocksGame; /** * 塊類,繼承自線程類(Thread) 由4 × 4個(gè)方塊(ErsBox)構(gòu)成一個(gè)方塊, 控制塊的移動(dòng)·下落·變形等 */ class ErsBlock extends Thread { /** * 一個(gè)塊占的行數(shù)是4行 */ public final static int BOXES_ROWS = 4; /** * 一個(gè)塊占的列數(shù)是4列 */ public final static int BOXES_COLS = 4; /** * 讓升級(jí)變化平滑的因子,避免最后幾級(jí)之間的速度相差近一倍 */ public final static int LEVEL_FLATNESS_GENE = 3; /** * 相近的兩級(jí)之間,塊每下落一行的時(shí)間差別為多少(毫秒) */ public final static int BETWEEN_LEVELS_DEGRESS_TIME = 50; /** * 方塊的樣式數(shù)目為7 */ public final static int BLOCK_KIND_NUMBER = 7; /** * 每一個(gè)樣式的方塊的反轉(zhuǎn)狀態(tài)種類為4 */ public final static int BLOCK_STATUS_NUMBER = 4; /** * 分別對(duì)應(yīng)7種模型的28種狀態(tài) */ public final static int[][] STYLES = { //共28種狀態(tài) {0x0f00, 0x4444, 0x0f00, 0x4444}, //長(zhǎng)條型的四種狀態(tài) {0x04e0, 0x0464, 0x00e4, 0x04c4}, //T型的四種狀態(tài) {0x4620, 0x6c00, 0x4620, 0x6c00}, //反Z型的四種狀態(tài) {0x2640, 0xc600, 0x2640, 0xc600}, //Z型的四種狀態(tài) {0x6220, 0x1700, 0x2230, 0x0740}, //7型的四種狀態(tài) {0x6440, 0x0e20, 0x44c0, 0x8e00}, //反7型的四種狀態(tài) {0x0660, 0x0660, 0x0660, 0x0660}, //方塊的四種狀態(tài) }; private GameCanvas canvas; private ErsBox[][] boxes = new ErsBox[BOXES_ROWS][BOXES_COLS]; private int style, y, x, level; private boolean pausing = false, moving = true; /** * 構(gòu)造函數(shù),產(chǎn)生一個(gè)特定的塊 * * @param style 塊的樣式,對(duì)應(yīng)STYLES的28個(gè)值中的一個(gè) * @param y 起始位置,左上角在canvas中的坐標(biāo)行 * @param x 起始位置,左上角在canvas中的坐標(biāo)列 * @param level 游戲等級(jí),控制塊的下落速度 * @param canvas 畫(huà)板 */ public ErsBlock(int style, int y, int x, int level, GameCanvas canvas) { this.style = style; this.y = y; this.x = x; this.level = level; this.canvas = canvas; 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(); } /** * 線程類的run()函數(shù)覆蓋,下落塊,直到塊不能再下落 */ @Override public void run() { while (moving) { try { sleep(BETWEEN_LEVELS_DEGRESS_TIME * (RussiaBlocksGame.MAX_LEVEL - level + LEVEL_FLATNESS_GENE)); } catch (InterruptedException ie) { ie.printStackTrace(); } //后邊的moving是表示在等待的100毫秒間,moving沒(méi)有被改變 if (!pausing) { moving = (moveTo(y + 1, x) && moving); } } } /** * 塊向左移動(dòng)一格 */ public void moveLeft() { moveTo(y, x - 1); } /** * 塊向右移動(dòng)一格 */ public void moveRight() { moveTo(y, x + 1); } /** * 塊向下移動(dòng)一格 */ 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 startMove() { pausing = false; moving = true; } /** * 暫停塊的下落,對(duì)應(yīng)游戲暫停 */ public void pauseMove() { pausing = true; // moving = false; } /** * 繼續(xù)塊的下落,對(duì)應(yīng)游戲繼續(xù) */ public void resumeMove() { pausing = false; moving = true; } /** * 停止塊的下落,對(duì)應(yīng)游戲停止 */ public void stopMove() { pausing = false; moving = false; } /** * 將當(dāng)前塊從畫(huà)布的對(duì)應(yīng)位置移除,要等到下次重畫(huà)畫(huà)布時(shí)才能反映出來(lái) */ 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 = canvas.getBox(i + y, j + x); if (box == null) { continue; } box.setColor(false); } } } } /** * 讓當(dāng)前塊放置在畫(huà)布的對(duì)因位置上,要等到下次重畫(huà)畫(huà)布時(shí)才能看見(jiàn) */ 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 = canvas.getBox(i + y, j + x); if (box == null) { continue; } box.setColor(true); } } } } /** * 當(dāng)前塊能否移動(dòng)到newRow/newCol 所指定的位置 * * @param newRow int,目的地所在行 * @param newCol int,目的地所在列 * @return boolean,true-能移動(dòng),false-不能移動(dòng) */ public 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 = canvas.getBox(i + newRow, j + newCol); if (box == null || (box.isColorBox())) { display(); return false; } } } } display(); return true; } /** * 將當(dāng)前塊移動(dòng)到newRow/newCol 所指定的位置 * * @param newRow int,目的地所在行 * @param newCol int,目的地所在列 * @return boolean,true-移動(dòng)成功,false-移動(dòng)失敗 */ private synchronized boolean moveTo(int newRow, int newCol) { if (!isMoveAble(newRow, newCol) || !moving) { return false; } erase(); y = newRow; x = newCol; display(); canvas.repaint(); return true; } /** * 當(dāng)前塊能否變成newStyle所指定的塊樣式,主要是考慮 邊界以及被其他塊擋住,不能移動(dòng)的情況 * * @param newSytle int,希望改變的塊樣式,對(duì)應(yīng)STYLES的28個(gè)值中的一個(gè) * @return boolean,true-能改變,false-不能改變 */ 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 = canvas.getBox(i + y, j + x); if (box == null || (box.isColorBox())) { display(); return false; } } key >>= 1; } } display(); return true; } /** * 將當(dāng)前塊變成newStyle所指定的塊樣式 * * @param newStyle int,希望改變的塊樣式,對(duì)應(yīng)STYLES的28個(gè)值中的一個(gè) * @return true-改變成功,false-改變失敗 */ 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(); canvas.repaint(); return true; } }
Main.java
package RussiaBlocksGame; /** * 程序入口函數(shù) * * @param args String[],附帶的命令行參數(shù) */ public class Main { public static void main(String[] args) { new RussiaBlocksGame("俄羅斯方塊:楊宇杰"); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VeVb武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選