您好,登錄后才能下訂單哦!
不懂java如何制作俄羅斯方塊小程序??其實想解決這個問題也不難,下面讓小編帶著大家一起學習怎么去解決,希望大家閱讀完這篇文章后大所收獲。具體內容如下:
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類,負責游戲的全局控制。 內含: 1.一個GameCanvas畫布類的實例對象, * 2.一個保存當前活動塊(RussiaBlock)實例的對象; 3.一個保存當前控制面板(ControlPanel)實例的對象; */ public class RussiaBlocksGame extends JFrame { private static final long serialVersionUID = -7332245439279674749L; /** * 每填滿一行計多少分 */ public final static int PER_LINE_SCORE = 100; /** * 積多少分以后能升級 */ public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20; /** * 最大級數是10級 */ public final static int MAX_LEVEL = 10; /** * 默認級數是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("設置方塊顏色..."), miSetBackColor = new JMenuItem("設置背景顏色..."), miTurnHarder = new JMenuItem("升高游戲難度"), miTurnEasier = new JMenuItem("降低游戲難度"), miExit = new JMenuItem("退出"), miPlay = new JMenuItem("開始"), miPause = new JMenuItem("暫停"), miResume = new JMenuItem("恢復"), miStop = new JMenuItem("終止游戲"), miRule = new JMenuItem("游戲規則"), miAuthor = new JMenuItem("關于本游戲"); /** * 建立并設置窗口菜單 */ 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); } }); //設置方塊顏色 miSetBlockColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color newFrontColor = JColorChooser.showDialog(RussiaBlocksGame.this, "設置方塊顏色", canvas.getBlockColor()); if (newFrontColor != null) { canvas.setBlockColor(newFrontColor); } } }); //設置背景顏色 miSetBackColor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Color newBackColor = JColorChooser.showDialog(RussiaBlocksGame.this, "設置背景顏色", canvas.getBackgroundColor()); if (newBackColor != null) { canvas.setBackgroundColor(newBackColor); } } }); //定義菜單欄"關于"的功能,彈出確認框。 miAuthor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "軟件工程(4)班\n3115005372\n楊宇杰\n©一切解釋權歸楊宇杰所有", "關于俄羅斯方塊 - 2016", 1); } }); //游戲規則說明 miRule.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "由小方塊組成的不同形狀的板塊陸續從屏幕上方落下來,\n玩家通過調整板塊的位置和方向,使它們在屏幕底部拼\n出完整的一條或幾條。這些完整的橫條會隨即消失,給新\n落下來的板塊騰出空間,與此同時,玩家得到分數獎勵。\n沒有被消除掉的方塊不斷堆積起來,一旦堆到屏幕頂端,\n玩家便告輸,游戲結束。", "游戲規則", 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); } } }); //退出按鈕動作響應 miExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); } /** * 主游戲類的構造方法 * * @param title String ,窗口標題 */ public RussiaBlocksGame(String title) { super(title); //設置標題 setSize(500, 600); //設置窗口大小 setLocationRelativeTo(null); //設置窗口居中 creatMenu(); Container container = getContentPane(); //創建菜單欄 container.setLayout(new BorderLayout(6, 0)); //設置窗口的布局管理器 canvas = new GameCanvas(20, 15); //新建游戲畫布 ctrlPanel = new ControlPanel(this); //新建控制面板 container.add(canvas, BorderLayout.CENTER); //左邊加上畫布 container.add(ctrlPanel, BorderLayout.EAST); //右邊加上控制面板 //注冊窗口事件。當點擊關閉按鈕時,結束游戲,系統退出。 addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent we) { stopGame(); System.exit(0); } }); //根據窗口大小,自動調節方格的尺寸 addComponentListener(new ComponentAdapter() { @Override public void componentResized(ComponentEvent ce) { canvas.adjust(); } }); setVisible(true); canvas.adjust(); } /** * 讓游戲復位 */ public void reset() { //畫布復位,控制面板復位 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(); } /** * 判斷游戲是否還在進行 * * @return boolean,true -還在運行,false-已經停止 */ public boolean isPlaying() { return playing; } /** * 得到當前活動的塊 * * @return ErsBlock,當前活動塊的引用 */ public ErsBlock getCurBlock() { return block; } /** * 得到當前畫布 * * @return GameCanvas,當前畫布的引用 */ public GameCanvas getCanvas() { return canvas; } /** * 開始游戲 */ 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(); //設置焦點在控制面板上 } /** * 游戲暫停 */ 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); } /** * 讓暫停中的游戲繼續 */ 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();//重置畫布和控制面板 } /** * 得到游戲者設置的難度 * * @return int ,游戲難度1-MAX_LEVEL */ public int getLevel() { return ctrlPanel.getLevel(); } /** * 用戶設置游戲難度 * * @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; } /** * 當積分累積到一定數值時,升一次級 * * @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; } /** * 游戲開始 */ private void play() { reset(); playing = true; Thread thread = new Thread(new Game());//啟動游戲線程 thread.start(); } /** * 報告游戲結束了 */ private void reportGameOver() { new gameOverDialog(this, "俄羅斯方塊", "游戲結束,您的得分為" + canvas.getScore()); } /** * 一輪游戲過程,實現了Runnable接口 一輪游戲是一個大循環,在這個循環中,每隔100毫秒, 檢查游戲中的當前塊是否已經到底了,如果沒有, * 就繼續等待。如果到底了,就看有沒有全填滿的行, 如果有就刪除它,并為游戲者加分,同時隨機產生一個新的當前塊并讓它自動落下。 * 當新產生一個塊時,先檢查畫布最頂上的一行是否已經被占了,如果是,可以判斷Game Over 了。 */ private class Game implements Runnable { @Override public void run() { int col = (int) (Math.random() * (canvas.getCols() - 3));//隨機生成方塊出現的位置 int style = ErsBlock.STYLES[ (int) (Math.random() * 7)][(int) (Math.random() * 4)];//隨機生成一種形狀的方塊 while (playing) { if (block != null) { //第一次循環時,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); } } //檢查畫布中是否有全填滿的行,如果有就刪之 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); } } } //根據最頂行是否被占,判斷游戲是否已經結束了 //@return boolean ,true-游戲結束了,false-游戲未結束 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對話框。 */ @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; /** * 畫布類,內有<行數>*<列數> 個方格類實例。 繼承自JPanel類。 ErsBlock線程類動態改變畫布類的方格顏色,畫布類通過 * 檢查方格顏色來體現ErsBlock塊的移動情況。 */ 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; /** * 畫布類的構造函數 * * @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 * @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; } /** * 設置游戲背景色彩 * * @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 */ 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; } /** * 升級后,將上一次升級以來的積分清零 */ 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類的函數,畫組件。 * * @param g 圖形設備環境 */ @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); } } } /** * 根據窗口大小,自動調節方格的尺寸 */ public void adjust() { 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 += RussiaBlocksGame.PER_LEVEL_SCORE; scoreForLevelUpdate += RussiaBlocksGame.PER_LEVEL_SCORE; repaint(); } /** * 重置畫布,置積分為零 */ 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。 上邊安放預顯窗口,等級,得分,控制按鈕 主要用來控制游戲進程。 */ 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(" 開始"), 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)); /** * 控制面板類的構造函數 * * @param game ErsBlocksGame,ErsBlocksGame 類的一個實例引用 方便直接控制ErsBlocksGame類的行為。 */ public ControlPanel(final RussiaBlocksGame game) { setLayout(new GridLayout(3, 1, 0, 2)); 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); 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() { //開始游戲 @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("時間:HH:mm:ss"); //系統獲得時間 Date date = new Date(); tfTime.setText(format.format(date)); tfScore.setText("" + game.getScore()); int ScoreForLevelUpdate = //判斷當前分數是否能升級 game.getScoreForLevelUpdate(); if (ScoreForLevelUpdate >= RussiaBlocksGame.PER_LEVEL_SCORE && ScoreForLevelUpdate > 0) { game.levelUpdate(); } } }); timer.start(); } /** * 設置預顯窗口的樣式 * * @param style int,對應ErsBlock類的STYLES中的28個值 */ public void setTipStyle(int style) { plTipBlock.setStyle(style); } /** * 取得用戶設置的游戲等級。 * * @return int ,難度等級,1-ErsBlocksGame.MAX_LEVEL */ public int getLevel() { int level = 0; try { level = Integer.parseInt(tfLevel.getText()); } catch (NumberFormatException e) { } return level; } /** * 讓用戶修改游戲難度等級。 * * @param level 修改后的游戲難度等級 */ public void setLevel(int level) { if (level > 0 && level < 11) { tfLevel.setText("" + level); } } /** * 設置“開始”按鈕的狀態。 */ public void setPlayButtonEnable(boolean enable) { btPlay.setEnabled(enable); } public void setPauseButtonEnable(boolean enable) { btPause.setEnabled(enable); } public void setPauseButtonLabel(boolean pause) { btPause.setText(pause ? " 暫停" : " 繼續"); } 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); } /** * 重新計算TipPanel里的boxes[][]里的小框的大小 */ public void adjust() { plTipBlock.adjust(); } /** * 預顯窗口的實現細節類 */ public class TipPanel extends JPanel { //TipPanel用來顯示下一個將要出現方塊的形狀 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; /** * 預顯示窗口類構造函數 */ 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); } } } /** * 設置預顯示窗口的方塊樣式 * * @param style int,對應ErsBlock類的STYLES中的28個值 */ public void setStyle(int style) { this.style = style; repaint(); } /** * 覆蓋JComponent類的函數,畫組件。 * * @param g 圖形設備環境 */ @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根據窗口的大小,自動調整方格的尺寸 */ 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; /** * 方格類,是組成塊的基本元素,用自己的顏色來表示塊的外觀 */ public class ErsBox implements Cloneable { private boolean isColor; private Dimension size = new Dimension(); /** * 方格類的構造函數, * * @param isColor 是不是用前景色來為此方格著色 true前景色,false 用背景色 */ public ErsBox(boolean isColor) { this.isColor = isColor; } /** * 此方格是不是用前景色表現 * * @return boolean ,true用前景色表現,false 用背景色表現 */ public boolean isColorBox() { return isColor; } /** * 設置方格的顏色, * * @param isColor boolean ,true用前景色表現,false 用背景色表現 */ public void setColor(boolean isColor) { this.isColor = isColor; } /** * 得到此方格的尺寸 * * @return Dimension ,方格的尺寸 */ public Dimension getSize() { return size; } /** * 設置方格的尺寸, * * @param size Dimension ,方格的尺寸 */ public void setSize(Dimension size) { this.size = size; } /** * 覆蓋Object的Object clone(),實現克隆 * * @return Object,克隆的結果 */ @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個方塊(ErsBox)構成一個方塊, 控制塊的移動·下落·變形等 */ class ErsBlock extends Thread { /** * 一個塊占的行數是4行 */ public final static int BOXES_ROWS = 4; /** * 一個塊占的列數是4列 */ public final static int BOXES_COLS = 4; /** * 讓升級變化平滑的因子,避免最后幾級之間的速度相差近一倍 */ public final static int LEVEL_FLATNESS_GENE = 3; /** * 相近的兩級之間,塊每下落一行的時間差別為多少(毫秒) */ public final static int BETWEEN_LEVELS_DEGRESS_TIME = 50; /** * 方塊的樣式數目為7 */ public final static int BLOCK_KIND_NUMBER = 7; /** * 每一個樣式的方塊的反轉狀態種類為4 */ public final static int BLOCK_STATUS_NUMBER = 4; /** * 分別對應7種模型的28種狀態 */ 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}, //方塊的四種狀態 }; private GameCanvas canvas; private ErsBox[][] boxes = new ErsBox[BOXES_ROWS][BOXES_COLS]; private int style, y, x, level; private boolean pausing = false, moving = true; /** * 構造函數,產生一個特定的塊 * * @param style 塊的樣式,對應STYLES的28個值中的一個 * @param y 起始位置,左上角在canvas中的坐標行 * @param x 起始位置,左上角在canvas中的坐標列 * @param level 游戲等級,控制塊的下落速度 * @param canvas 畫板 */ 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()函數覆蓋,下落塊,直到塊不能再下落 */ @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沒有被改變 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 startMove() { pausing = false; moving = true; } /** * 暫停塊的下落,對應游戲暫停 */ public void pauseMove() { pausing = true; // moving = false; } /** * 繼續塊的下落,對應游戲繼續 */ public void resumeMove() { pausing = false; moving = true; } /** * 停止塊的下落,對應游戲停止 */ public void stopMove() { pausing = false; 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 = canvas.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 = canvas.getBox(i + y, j + x); if (box == null) { continue; } box.setColor(true); } } } } /** * 當前塊能否移動到newRow/newCol 所指定的位置 * * @param newRow int,目的地所在行 * @param newCol int,目的地所在列 * @return boolean,true-能移動,false-不能移動 */ 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; } /** * 將當前塊移動到newRow/newCol 所指定的位置 * * @param newRow int,目的地所在行 * @param newCol int,目的地所在列 * @return boolean,true-移動成功,false-移動失敗 */ 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; } /** * 當前塊能否變成newStyle所指定的塊樣式,主要是考慮 邊界以及被其他塊擋住,不能移動的情況 * * @param newSytle int,希望改變的塊樣式,對應STYLES的28個值中的一個 * @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; } /** * 將當前塊變成newStyle所指定的塊樣式 * * @param newStyle int,希望改變的塊樣式,對應STYLES的28個值中的一個 * @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; /** * 程序入口函數 * * @param args String[],附帶的命令行參數 */ public class Main { public static void main(String[] args) { new RussiaBlocksGame("俄羅斯方塊:楊宇杰"); } }
感謝你能夠認真閱讀完這篇文章,希望小編分享java如何制作俄羅斯方塊小程序?內容對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業資訊頻道,遇到問題就找億速云,詳細的解決方法等著你來學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。