Este é o último design do curso para os cursos de Java. Como Java é iniciante, me referi a alguns blogs de especialistas técnicos ao fazê -lo. Eu gostaria de expressar minha gratidão aqui.
Publique aqui para se comunicar e aprender.
Se você precisar de arquivos completos de projeto, documentação e arquivos de jar executáveis, faça o download do endereço: Clique para abrir o link
Russianblocksgame.java
pacote russiBlocksgame; importar java.awt.*; importar java.awt.event.*; importar javax.swing.border.border; importar javax.swing.border.etchedborder; /*** A classe de jogo principal, herdada da classe JFrame, é responsável pelo controle global do jogo. Inclui: 1. Um objeto de instância da classe GameCanvas Canvas, * 2. Um objeto que contém a instância atual do bloco ativo (RussiBlock); 3. Um objeto que contém a instância atual do painel de controle (ControlPanel); */ classe pública russiBlocksgame estende JFRame {private estático final serialversionuid = -7332245439279674749l; / *** Quantos pontos são contados para cada linha preenchida*/ public final estático int per_line_score = 100; / *** Quantos pontos podem ser atualizados após acumulação*/ public final estático int per_level_score = per_line_score* 20; / *** A série máxima é o nível 10*/ public final estático int max_level = 10; / ** * A série padrão é 2 */ public final estático int default_level = 2; Canvas privadas de gamecanvas; Bloco privado de Ersblock; Playing booleano privado = falso; ControlPanel privado CtrlPanel; // Inicialize a barra de menu Private Jmenubar Bar = new Jmenubar (); Private Jmenu Mgame = New Jmenu ("Game"), Mcontrol = New Jmenu ("Control"), Minfo = New Jmenu ("Ajuda"); private JMenuItem miNewGame = new JMenuItem("New Game"), miSetBlockColor = new JMenuItem("Set Block Color..."), miSetBackColor = new JMenuItem("Set Background Color..."), miTurnHarder = new JMenuItem("Elevate Game Difficulty"), miTurnEasier = new JMenuItem("Reduce Game Difficulty"), miExit = new JMenuItem("Exit"), miPlay = new JMenuItem("Start"), miPause = new JMenuItem("Pause"), miResume = new JMenuItem("Resume"), miStop = new JMenuItem("Terminate the game"), miRule = new JMenuItem("Game Rules"), miAuthor = new JMenuItem("About this game"); / *** Crie e defina o menu da janela*/ private void cretMenu () {bar.add (mgame); bar.add (mcontrol); bar.add (minfo); mgame.add (minewgame); mgame.addseparator (); // Adicionar linha de divisão horizontal mgame.add (misetBlockColor); mgame.add (misetBlockColor); mgame.addseparator (); // Adicione a linha de divisão horizontal mgame.add (miturnharder); mgame.add (miturneasier); mgame.addseparator (); // Adicionar linha de divisão horizontal mgame.add (miexit); mcontrol.add (miplay); miplay.setEnabled (true); mcontrol.add (mipause); mipause.setEnabled (false); mcontrol.add (miresume); miresume.setEnabled (false); mcontrol.add (Entop); 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);}}); // defina o bloco color misetBlockcolor.addactionListener (new ActionListener () {@Override public void actionPerformed (ActionEvent e) {color newfrontColor = jcolorchooser.showdialog (russiBlocksgame.This, "set the block cor", pode {Canvas.setBlockColor (newfrontColor); // defina a cor misetbackcolor.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent e) {color newbackColor = jcolorchooser.ShowDAlGackC (russiBlocksgame.This, "set the Background Color", Canvas.get.getCol! canvas.setBackgroundColor (newbackColor); // Defina a função da barra de menus "Sobre" e uma caixa de confirmação aparece. miauthor.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent E) {JoptionPane.showMessagedialog (Null, "Software Engineering (4) Class/N3115005372/nyang yujie/n © All para interpretar é }); //Game rules description miRule.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Plates of different shapes composed of small squares fall from the top of the screen one after another. The /n player adjusts the position and direction of the plates to make them spell out a complete one or several pieces at the bottom of the screen. These As barras horizontais completas desaparecem imediatamente, abrindo espaço para as placas caídas. // Aumente a dificuldade miturnharder.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent E) {int curlevel = getLevel (); if (! Tocando && clelovel <max_level) {Setlevel (nível de moda + 1);}}); // reduz a dificuldade miturnEasier.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent e) {int curlevel = GetLevel (); if (! // Resposta de ação do botão de saída miexit.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent e) {System.exit (0);}}); } / *** Método do construtor da classe principal de jogo** @param title string, título da janela* / public russiBlocksgame (string title) {super (título); // defina o título SetSize (500, 600); // defina o tamanho da janela setLocationRelativeTo (null); // defina o centro de janela createMenu (); Contêiner de contêiner = getContentPane (); // Crie a barra de menu Container.setLayout (New BorderLayout (6, 0)); // Defina o gerente de layout da janela Canvas = new GameCanvas (20, 15); // Crie uma nova tela de jogo CtrlPanel = new ControlPanel (this); // crie um novo contêiner de painel de controle.add (Canvas, borderlayout.center); // Adicione o container de canvas.add (ctrlpanel, borderlayout.east); // Adicione o painel de controle nos eventos da janela Right // Registrar. Quando o botão Fechar é clicado, o jogo termina e o sistema sai. addWindowlistener (new windowAdapter () {@Override public void WindowClosing (WindowEvent nós) {stopgame (); System.exit (0);}}); // Ajusta automaticamente o tamanho do quadrado de acordo com o tamanho da janela AddComponentListener (new ComponentAdApter () {@Override public void comOnentResized (componentEvent CE) {Canvas.adjust ();}}); setvisible (true); canvas.adjust (); } /*** Redefinir o jogo* /public void reset () {// Redefina a tela e redefinir o painel de controle 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 (); } / *** Determine se o jogo ainda está em andamento** @return boolean, true - ainda está em execução, false -has parado* / public boolean isPlaying () {return tocando; } / *** Obtenha o bloco atualmente ativo** @return ersblock, a referência ao bloco atualmente ativo* / public ErsBlock getCurBlock () {Bloco de retorno; } / *** Obtenha a tela atual** @return gameCanvas, a referência à tela atual* / public gameCanvas getCanvas () {return Canvas; } / *** Inicie o jogo* / 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 (); // Defina o foco no painel de controle}/*** pausa de jogo*/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); } / *** Deixe o jogo pausado continuar* / 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 (); } / *** O usuário interrompe o jogo* / public void stopgame () {plays = 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 (); // redefinir tela e painel de controle}/** * Obtenha a dificuldade definida pelo jogador * * @return int, dificuldade do jogo 1-max_level */public int getLevel () {return ctrlpanel.getLevel (); } / ** * O usuário define a dificuldade do jogo * * @param nível int, dificuldade do jogo 1-max_level * / public void setlevel (int nível) {if (nível <11 && nível> 0) {ctrlpanel.setLevel (nível); }} / *** Obtenha pontos de jogo** @return int, pontos* / public int getScore () {if (Canvas! = Null) {return Canvas.getScore (); } retornar 0; } /*** Obtenha pontos de jogo desde a última atualização. Após a atualização, esse ponto será limpo** @return int, ints*/ public int getScoreFeLeVelUpDate () {if (Canvas! = Null) {retorna canvas.getScoreFeLevelUpDate (); } retornar 0; } / ** * Quando a integral se acumula a um determinado valor, atualize uma vez * * @return boolean, verdadeiro update sucessivo, fals update falha * / public boolean LevelUpdate () {int curlevel = getLevel (); if (Curlevel <max_level) {Setlevel (Curlevel + 1); canvas.ReSetSCOREFORLEVELUPDATE (); retornar true; } retornar false; } / *** Início do jogo* / private void play () {reset (); tocando = verdadeiro; Thread Thread = new Thread (novo jogo ()); // Inicie o thread do jogo Thread.start (); } / *** Relatório O jogo acabou* / private void ReportGameover () {new GameOverdialog (this, "tetris", "o jogo termina, sua pontuação é" + canvas.getScore ()); } /*** Uma rodada de processo de jogo, implementando a interface executável. Uma rodada de jogo é um grande loop. Nesse circuito, a cada 100 milissegundos, verifique se o bloco atual do jogo chegou ao fim. Caso contrário, * continuará esperando. Se chegar ao final, depende se há uma linha totalmente preenchida. Se houver, exclua -o e adicione pontos ao jogador e gerar aleatoriamente um novo bloco atual e deixe cair automaticamente. * Quando um novo bloco é gerado, verifique se a linha na parte superior da tela foi ocupada. Nesse caso, você pode julgar o jogo. */ Classe Private Game implementa Runnable {@Override public void run () {int col = (int) (Math.random () * (Canvas.getCols () - 3); // gera aleatoriamente a posição do Block Int Style = Ersblock.styles [(int) (e Math.random () * 7) [ de uma forma enquanto (tocando) {if (block! = null) {// o bloco está vazio se (block.isalive ()) {try {thread.currentThread (); Thread.sleep (500); } catch (interruptedException ie) {ie.printStackTrace (); } continuar; }} checkfullLine (); // Verifique se existem linhas totalmente preenchidas se (isgameover ()) {reportGameover (); miplay.setEnabled (true); mipause.setEnabled (false); miresume.setEnabled (false); mistop.setEnabled (false); ctrlpanel.setPlayButtoneNable (true); ctrlpanel.setPauseButtonLabel (false); ctrlpanel.setstopbuttonenable (false); retornar; } bloco = new ersblock (estilo, -1, col, getLevel (), tela); block.start (); col = (int) (math.random () * (canvas.getCols () - 3)); style = ersblock.styles [(int) (math.random () * 7)] [(int) (math.random () * 4)]; Ctrlpanel.SettipStyle (estilo); }} // Verifique se existem linhas totalmente preenchidas na tela. Se houver um, exclua -o public void checkfullLine () {for (int i = 0; i <canvas.getRows (); i ++) {int linha = -1; boolean fulllineColorBox = true; for (int j = 0; j <canvas.getCols (); j ++) {if (! canvas.getbox (i, j) .iscolorbox ()) {fulllineColorbox = false; quebrar; }} if (FullLinColorBox) {Row = i--; Canvas.RemoveLine (linha); }}} // julgue se o jogo terminou com base no fato de a linha superior estar ocupada //@retornar boolean, true--o jogo acabou, False-o jogo não está sobre o privado booleano isgameover () {for (int i = 0; i <canvas.getcols (); i ++) {iersbox box = Canvas.Box (0svas.getCols (); i ++) {iSbox box = Canvas.Box (0svas.getCols (); i ++) {iSbox box = Canvas.Box (> if (box.iscolorbox ()) {return true; }} retornar false; }} /*** Defina a caixa de diálogo Gameover. */ @Suppresswarnings ("serial") A classe privada GameOverdialog estende o JDialog implementa o ActionListener {Private JButton novamente Button, exitbutton; fronteira privada de fronteira = novo etchedborder (etchedborder.raised, cor.white, nova cor (148, 145, 140)); Public GameOverdialog (JFRame Parent, String Title, String message) {super (pai, título, true); if (pai! = null) {setSize (240, 120); this.setLocationRelativeTo (pai); Jpanel messagePanel = new jpanel (); messagePanel.add (New Jlabel (mensagem)); MessagePanel.setborder (Border); Contêiner contêiner = this.getContentPane (); container.setLayout (New GridLayout (2, 0, 0, 10)); container.add (MessagePanel); Jpanel escolhaPanel = new jpanel (); escolhaPanel.setLayout (New GridLayout (0, 2, 4, 0)); container.add (escolhaPanel); novamentebutton = new jbutton ("Jogue outro jogo"); exitbutton = new jbutton ("jogo de saída"); escolhaPanel.Add (New Jpanel (). Add (AgainButton)); escolhaPanel.add (New Jpanel (). Add (exitbutton)); escolhaPanel.setborder (borda); } novamentebutton.addactionListener (this); exitbutton.addactionListener (isto); this.setVisible (true); } @Override public void ActionPerformed (ActionEvent e) {if (e.getSource () == AgainButton) {this.setVisible (false); reiniciar(); } else if (e.getSource () == exitbutton) {stopgame (); System.Exit (0); }}}}Gamecanvas.java
pacote russiBlocksgame; importar java.awt.color; importar java.awt.graphics; importar javax.swing.jpanel; importar javax.swing.border.etchedborder; /*** Classe de tela, com <número de linhas>* <número de colunas> instâncias de classe quadrada. Herdado da classe jpanel. A classe Ersblock Thread altera dinamicamente a cor da grade da classe Canvas. A classe Canvas usa * para verificar a cor da grade para refletir o movimento do bloco Ersblock. */ classe pública gamecanvas estende JPanel {private estático final serialversionUid = 6732901391026089276l; color privado backcolor = color.darkgray, frontcolor = color.white; private int linhas, cols, pontuação = 0, scoreLorLevelUpDate = 0; private ersbox [] [] caixas; Private Int Boxwidth, BoxHeight; / *** Construtor da classe Canvas** @param linhas int, o número de linhas da tela* @param cols int, o número de colunas e colunas da tela determina o número de quadrados que as tela têm*/ public gamecanvas (int filas, int cols) {this.Rows = ROws; this.cols = cols; Caixas = New ErsBox [linhas] [cols]; para (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <caixas [i] .Length; j ++) {caixas [i] [j] = new ErsBox (false); }} Setborder (New EtChedBorder (etcedborder.Raised, color.white, nova cor (148, 145, 140));} / ** * Construtor da classe de tela * * @param linhas * @param cols * @param backcolor * @param frontcolor * / public gamesnas isto (linhas, cols); getbackgroundcolor () {return backcolor; * Obtenha o número de linhas do quadrado na tela** @return*/ public int getRows () {retorna linhas; pontuação; RussiBlocksgame.per_level_score; - 1 ||. g.setColor (FrontColor); BoxHeight, verdadeiro); ErsBoxesGame Class */public sincronizado Void Removeline (int linha) {for (int i = linha; i> 0; i-) {for (int j = 0; j <cols; j ++) {caixas [i] [j] Score +RussiBlocksgame.per_level_score; J = 0;ControlPanel.java
pacote russiBlocksgame; importar java.awt.borderlayout; importar java.awt.color; importar java.awt.graphics; importar java.awt.gridlayout; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.awt.event.componentAdapter; importar java.awt.event.componentEvent; importar java.awt.event.keyadapter; importar java.awt.event.keyevent; importar java.text.dateFormat; importar java.text.simpledateFormat; importar java.util.date; importar javax.swing.jbutton; importar javax.swing.jlabel; importar javax.swing.jpanel; importar javax.swing.jtextfield; importar javax.swing.timer; importar javax.swing.border.border; importar javax.swing.border.etchedborder; /*** Classe do painel de controle, herdada da JPanel. Os botões de visualização da janela, nível, pontuação e controle são colocados nela. */ classe ControlPanel estende JPanel {private estático final serialversionUId = 3900659640646175724L; Private JTextfield tflevel = new JTextfield ("" + russiaBlocksgame.default_level), tfscore = new jtextfield ("0"), tftime = new jtextfield (""); Private JButton btPlay = new JButton ("Start"), btpause = new JButton ("pausa"), btstop = new jbutton ("End the Game"), btturnLevelup = New Jbutton ("Aumente a dificuldade"), BtTurnVurnveldown = New Jbutton ("a dificuldade"), BtTurnvelDown = New Jbutton ("a dificuldade"), BtturnvelDown = jbutton "Reduza a dificuldade"), 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)); Timer privado Timer; fronteira privada de fronteira = novo etchedborder (etchedborder.raised, cor.white, nova cor (148, 145, 140)); /*** Construtor da classe de painel de controle** @param jogo ersblocksgame, uma referência de instância da classe Ersblocksgame é conveniente para controlar diretamente o comportamento da classe Ersblocksgame. */ public ControlPanel (jogo final RussiBlocksgame) {setLayout (New GridLayout (3, 1, 0, 2)); pltip.add (New Jlabel ("Next Square"), borderlayout.north); // Adicionar componente pltip.add (pLtiPBlock); pltip.setborder (borda); Plinfo.add (New Jlabel ("Coeficiente de dificuldade"); Plinfo.add (Tflevel); Plinfo.add (New Jlabel ("Score")); Plinfo.add (tfscore); Plinfo.setborder (borda); 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 (borda); tflevel.seteditable (false); tfscore.seteditable (false); tftime.seteditable (falso); 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 () {caseEvent.VK_BOWN :Moved.Moved; Block.Moveleft (); btplay.addactionListener (new ActionListener () {// inicie o jogo @Override public void ActionPerformed (ActionEvent AE) {game.playgame ();}}); btpause.addactionListener (new ActionListener () {// Pause o jogo @Override public void ActionPerformed (ActionEvent AE) {if (btpause.getText (). Equals ("pausegame") {game.pausegame ();} mais {game.Resumegame (); btstop.addactionListener (new ActionListener () {// pare o jogo @Override public void ActionPerformed (ActionEvent AE) {game.stopgame ();}}); btTurnLevelUp.addActionListener(new ActionListener() { // Increase difficulty @Override public void actionPerformed(ActionEvent ae) { try { int level = Integer.parseInt(tfLevel.getText()); if (level < RussiaBlocksGame.MAX_LEVEL) { tfLevel.setText("" + (level + 1)); } } Catch (númeroFormatexception e) {} requestFocus (); BtTurnLevelDown.addactionListener (new ActionListener () {// reduz a dificuldade do jogo @Override public void ActionPerformed (ActionEvent Ae) {try {int Level = Integer.parseInt (Tflevel.getText (); if (Level> 1) {Tflevel.Settxt (" } requestFocus (); addComponentListener (new componentAdApter () {@Override public void comOnentResized (componentEvent CE) {pltiPblock.adjust ();}}); Timer = novo Timer (1000, new ActionListener () {@Override public void ActionPerformed (ActionEvent AE) {DateFormat format = new SimpleDateFormat ("Hora: hh: mm: ss"); // o sistema obtém a data da data = new Date (); game.getScore (); timer.start (); } / *** Defina o estilo da janela pré-display** @param estilo int, correspondendo aos 28 valores nos estilos da classe ErsBlock* / public void SettipStyle (int style) {pltiPblock.setstyle (estilo); } /*** Obtenha o nível do jogo definido pelo usuário. * * @return int, nível de dificuldade, 1-esblocksgame.max_level */ public int getLevel () {int nível = 0; tente {nível = Integer.parseint (tflevel.getText ()); } catch (numberFormatexception e) {} Retorno nível; } /*** Deixe os usuários modificarem o nível de dificuldade do jogo. * * @PARAM Nível de jogo modificado no nível do jogo */ public void Setlevel (int nível) {if (nível> 0 && nível <11) {tflevel.settext ("" + nível); }} /*** Defina o status do botão "Iniciar". */ public void setPlayButtoNENABLE (BOOLEAN ENABLE) {BTPLAY.setEnabled (Enable); } public void setPauseButtonEnable (enable boolean) {btpause.setEnabled (enable); } public void setPauseButtonLabel (pausa booleana) {btpause.settext (pausa? "pausa": "continua"); } public void setStopButtonEnable (enable boolean) {btstop.setEnabled (enable); } public void SetturnLevelUpButtonEnable (enable boolean) {BtTurnLevelUp.SetEnabled (Enable); } public void SetturnLevelDownButtonenable (enable boolean) {BtTurnLevelDown.SetEnabled (Enable); } / *** Redefinir painel de controle* / public void reset () {tfscore.settext ("0"); pltiPblock.setStyle (0); } / *** recalcule o tamanho da caixa pequena em caixas [] [] em tippainel* / public void ajuste () {pltiPblock.adjust (); } /*** Detalhes da implementação Classe da janela pré-display* /classe pública TippAnel estende JPanel {// TippAnel é usado para exibir a forma do próximo bloco para aparecer private estático final serialversionuid = 51605367143697616l; color privado backcolor = color.darkgray, frontcolor = color.white; private ersbox [] [] caixas = new ersbox [esblock.boxes_rows] [esblock.boxes_cols]; Estilo privado int, largura de caixa, peso de caixa; Privado booleano odiado = false; / *** Construtor de classe de janela pré-display*/ public TippAnel () {for (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <caixas [i] .Length; j ++) {caixas [i] [j] = new ersbox (false); }}} / *** Defina o estilo de bloco da janela pré-display** @param estilo int, correspondendo a 28 valores em estilos da classe Ersblock* / public void SetStyle (int style) {this.style = style; repintar (); } /*** Substitua as funções da classe JComponent e desenhe componentes. * * @param g aparelho de dispositivo de gráfico */ @Override public void PaintComponent (gráfico g) {super.paintComponent (g); if (! istiled) {ajuste (); } int key = 0x8000; para (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <caixas [i] .Length; j ++) {color color = ((chave e estilo)! = 0? FrontColor: backcolor); g.setColor (cor); G.Fill3Drect (J * BOXWidth, I * BoxHeight, Boxwidth, BoxHeight, True); chave >> = 1; }}} / *** g ajuste automaticamente o tamanho do quadrado de acordo com o tamanho da janela* / public void ajuste () {boxwidth = getSize (). width / ersblock.boxes_cols; BoxHeight = getSize (). Hight / ersblock.boxes_rows; Istiled = true; }}}Ersbox.java
pacote russiBlocksgame; importar java.awt.dimension; / *** A classe quadrada é o elemento básico que compõe o bloco e usa sua própria cor para representar a aparência do bloco*/ classe pública ErsBox implementa clonável {private boolean iscolor; Tamanho da dimensão privada = new Dimension (); / ** * O construtor da classe quadrada, * * @param iScolor faz a cor do primeiro plano é usada para colorir essa cor de primeiro plano quadrada, Falso Use cor de fundo */ Public ErsBox (boolean iscolor) {this.iscolor = isColor; } / *** Este quadrado é expresso na cor do primeiro plano** @return boolean, verdadeira expressa na cor do primeiro plano, falsa expressa na cor do fundo* / public boolean iscolorbox () {return iscolor; } / ** * Defina a cor do quadrado, * * @param iscolor boolean, verdadeiro expresso na cor do primeiro plano, falsa expressa na cor do fundo * / public void setColor (boolean iscolor) {this.iscolor = iscolor; } / *** Obtenha o tamanho deste quadrado** @return Dimension, o tamanho do quadrado* / dimensão pública getSize () {Tamanho do retorno; } / ** * Defina o tamanho do quadrado, * * @param tamanho da dimensão, o tamanho do quadrado * / public void Setsize (tamanho da dimensão) {this.size = size; } / *** Substituir o objeto do objeto clone (), implementar clone** @return objeto, resultado do clone* / @Override public Object clone () {objeto clone = null; tente {clone = super.clone (); } catch (Exceção ex) {ex.PrintStackTrace (); } retornar clone; }}Ersblock.java
pacote russiBlocksgame; / *** A classe de bloco, herdada da classe Thread (Thread), consiste em blocos 4 × 4 (ErsBox), controlando o movimento, a queda, a deformação do bloco, etc.*/ classe ersblock estende o thread {/ *** o número de linhas ocupadas por um bloco é 4 linhas*/ public Final STATION COXES_ROWS = 4; / *** O número de colunas ocupadas por um bloco é 4 colunas*/ public final static int boxes_cols = 4; / *** O fator que suaviza as alterações de atualização para evitar quase o dobro da diferença de velocidade entre os últimos estágios*/ public final estático int Level_flatness_gene = 3; / ** * Qual é a diferença entre os dois níveis semelhantes do bloco para cada linha (milissegundos) */ public final estático int entre_levels_degress_time = 50; / ** * O número de estilos de blocos é 7 */ public final static int block_kind_number = 7; / ** * O tipo de estado de inversão de blocos de cada estilo é 4 */ public final static int block_status_number = 4; /** * 28 states corresponding to 7 models respectively*/ public final static int[][] STYLES = { //Total 28 states {0x0f00, 0x4444, 0x0f00, 0x4444}, //Four states of long stripes {0x04e0, 0x0464, 0x00e4, 0x04c4}, //Four states of T type {0x4620, 0x6c00, 0x4620, 0x6c00}, // quatro estados do tipo Z reverso {0x2640, 0xc600, 0x2640, 0xc600}, // quatro estados do tipo z {0x6220, 0x1700, 0x2230, 0x074} Four 0x44c0, 0x8e00}, // quatro estados do inverso 7 tipo {0x0660, 0x0660, 0x0660, 0x0660}, // quatro estados do bloco}; Canvas privadas de gamecanvas; private ersbox [] [] Estilo privado int, y, x, nível; Possa booleana privada = false, movimentando = true; / *** Construtor, gera um bloco específico** @param estilo o estilo do bloco, correspondendo a um dos 28 valores de estilos* @param y Posição inicial, coordenar a linha no canto superior esquerdo no nível* @Param X Start Position, coordenar a coluna do canto superior esquerdo na tela* @Param Nível de jogo/ nível de lixo, controlar a queda da velocidade da fita, a fita, a fita, a fita, na pista, a fita, a fita, a fita, a coluna, a coluna de queda, na parte superior esquerda, na parte superior, a fita, na parte superior esquerda, a queda de speater. x, int nível, GameCanvas Canvas) {this.style = style; this.y = y; this.x = x; this.level = nível; this.Canvas = Canvas; tecla int = 0x8000; para (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <caixas [i] .Length; j ++) {boolean iscolor = ((estilo & key)! = 0); caixas [i] [j] = new ErsBox (ISCOLOR); chave >> = 1; } } mostrar(); } / *** A função run () da classe Thread cobre e solta o bloco até que o bloco não possa cair novamente* / @Override public void run () {while (movimentando) {try {sleep (entre_levels_degress_time* (russiBlocksgame.max_level + Level_flatness_gene); } catch (interruptedException ie) {ie.printStackTrace (); } // A mudança subsequente significa que a mudança não foi alterada durante os 100 milissegundos de espera se (! Pausando) {moving = (moveto (y + 1, x) && movendo); }}}} / ** * O bloco move uma grade para a esquerda * / public void MoveleLeft () {moveto (y, x - 1); } / ** * O bloco move uma grade para a direita * / public void Moveight () {moveto (y, x + 1); } / ** * O bloco move uma grade para a direita * / public void mudouwn () {moveto (y + 1, x); } / *** variante de bloco* / public void TurnNext () {for (int i = 0; i <block_kind_number; i ++) {for (int j = 0; j <block_status_number; j ++) {if (estilos [i] [j] == Style) {intenstyle = estilos [i] [i] [i] [i] [i] [i;; Turnto (Newstyle); retornar; }}}} public void startMove () {pausing = false; move = true; } /** * Pause the whereabouts of the block, corresponding to the game pause*/ public void pauseMove() { pausing = true; // moving = false; } /** * Continue the whereabouts of the block, corresponding to the game continue*/ public void resumeMove() { pausing = false; moving = true; } /** * Stop the whereabouts of the block, corresponding to the game pause*/ public void stopMove() { pausing = false; moving = false; } /** * Remove the current block from the corresponding position of the canvas and will not be reflected until the next time you repaint the canvas*/ 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); } } } } } /** * Let the current block be placed in the corresponding position of the canvas, and you have to wait until the next time you repaint the canvas*/ 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); } } } } } /** * Can the current block be moved to the location specified by newRow/newCol* * @param newRow int, the destination line* @param newCol int, destination column * @return boolean, true-can move, false-cannot move*/ 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; } } } } mostrar(); return true; } /** * Move the current block to the location specified by newRow/newCol* * @param newRow int, destination row* @param newCol int, destination column* @return boolean, true-move successfully, false-move failed*/ private synchronized boolean moveTo(int newRow, int newCol) { if (!isMoveAble(newRow, newCol) || !moving) { return false; } erase(); y = newRow; x = newCol; mostrar(); canvas.repaint(); return true; } /** * Can the current block become the block style specified by newStyle, mainly considering the boundary and being blocked by other blocks and cannot be moved* * @param newSytle int, the block style you want to change corresponds to one of the 28 values of STYLES* @return boolean, true-can change, false-cannot change*/ private boolean isTurnAble(int newStyle) { int key = 0x8000; apagar(); 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; } } mostrar(); return true; } /** * Turn the current block into the block style specified by newStyle* * @param newStyle int, the block style you want to change, corresponding to one of the 28 values of STYLES* @return true-change succeeds, false-change fails*/ 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; mostrar(); canvas.repaint(); return true; }}Main.java
package RussiaBlocksGame; /** * Program entry function* * @param args String[], accompanied by command line parameters*/ public class Main { public static void main(String[] args) { new RussiaBlocksGame("Tetris: Yang Yujie"); }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。