Este es el último diseño de curso para los cursos de Java. Como Java es un principiante, me he referido a algunos blogs de expertos técnicos al hacerlo. Me gustaría expresar mi gratitud aquí.
Publique aquí para comunicarse y aprender.
Si necesita archivos de proyecto completos, documentación y archivos JAR ejecutables, descargue la dirección: haga clic para abrir el enlace
Russianblocksgame.java
paquete russiaBlocksgame; import java.awt.*; import java.awt.event.*; import javax.swing.border.border; import javax.swing.border.etchedborder; /*** La clase de juego principal, heredada de la clase Jframe, es responsable del control global del juego. Incluye: 1. Un objeto de instancia de la clase GameCanvas Canvas, * 2. Un objeto que contiene la instancia actual del bloque activo (RussiaBlock); 3. Un objeto que contiene la instancia del panel de control actual (ControlPanel); */ clase pública russiaBlocksgame extiende jframe {privado estático final SerialVersionUid = -7332245439279674749l; / *** ¿Cuántos puntos se cuentan para cada fila llena*/ Public final Static int Per_line_score = 100; / *** ¿Cuántos puntos se pueden actualizar después de la acumulación*/ Public final Static int Per_level_score = per_line_score* 20; / *** La serie máxima es el nivel 10*/ Public final Static int max_level = 10; / ** * La serie predeterminada es 2 */ pública final static int default_level = 2; lienzo de gamecanvas privado; Bloque privado ERSBLOCK; Booleano privado Boolean = False; Controlpanel privado Ctrlpanel; // Inicializar barra de menú barra privada jmenubar = new JMenubar (); privado jmenu mgame = new JMenu ("juego"), mcontrol = new JMenu ("Control"), minfo = new JMenu ("Ayuda"); 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 ("inicio"), mipAuse = new JMenuitem ("Pausa"), Miresume = new JMenuitem ("reanudar"), mistop = new JMenuitem ("termine el juego"), Mirule = new JMenuitem ("reglas de juego"), Miauthor = newuthor = new Jmenuitem (""), Mirule "); / *** Crear y establecer el menú de la ventana*/ private void createMenu () {bar.add (mgame); bar.add (Mcontrol); bar.add (minfo); mgame.add (minewgame); mgame.addseparator (); // Agregar línea dividida horizontal mgame.add (misetblockColor); mGame.Add (MisetblockColor); mgame.addseparator (); // agregue la línea dividida horizontal mgame.add (MiturnHarder); mGame.Add (Miturneasier); mgame.addseparator (); // Agregar línea dividida horizontal mgame.add (miExit); mcontrol.add (miplay); miplay.setEnabled (true); mcontrol.add (mipaus); MIPAUSE.SetEnabled (falso); mcontrol.add (Miresume); Miresume.SetEnabled (falso); mcontrol.add (mistop); Mistop.SetEnabled (falso); minfo.add (Mirule); minfo.add (Miauthor); setJMenubar (bar); minewgame.addactionListener (new ActionListener () {@Override public void ActionPerformed (ActionEvent E) {stopGame (); reset (); setLevel (default_level);}}); // Establezca el color de bloque MisetBlockColor.AddactionListener (new ActionListener () {@Override public Void ActionPerformed (ActionEvent E) {Color NewFrontColor = JColorChooser.ShowDialog (RussiaBlockSGeN {Canvas.SetBlockColor (NewFrontColor); // Establezca el color de fondo misetbackColor.addactionListener (new ActionListener () {@Override public Void ActionPerformed (ActionEvent E) {Color NewBackColor = JColorChooser.ShowDialog (RussiaBlockSGame.This, "Establecer el color de fondo", Canvas.getBackgroundColor ()); si (neybackColor! Canvas.setBackgroundColor (NewBackColor); // Defina la función de la barra de menú "Acerca de" y aparece un cuadro de confirmación. miAuthor.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Software Engineering (4) Class/n3115005372/nYang Yujie/n©All the right to interpret is owned by Yang Yujie", "About Tetris- 2016", 1); } }); // Reglas del juego Descripción Mirule.AdDactionListener (New ActionListener () {@Override public void ActionPerformed (ActionEvent E) {JOPTionPane.ShowMessEdialog (NULL, "placas de diferentes formas compuestas de pequeños cuadrados caen desde la parte superior de la parte superior tras otra. Estas barras horizontales desaparecerán de inmediato, lo que hace que las placas nuevas /nadas sean el mismo tiempo. // Aumente la dificultad MITURNHARDER.AdDActionListener (new ActionListener () {@Override Public Void ActionperFormed (ActionEvent E) {int Curlevel = GetLevel (); if (! Playing && Curlevel <Max_Level) {SetLevel (Curlevel + 1);}}); // Reduce la dificultad MITURNEASIER.AdDActionListener (new ActionListener () {@Override public Void ActionperFormed (ActionEvent E) {int Curlevel = getLevel (); if (! Playing && Curlevel> 1) {SetLevel (Curlevel - 1);}}}); // Salir del botón Respuesta de acción Miexit.AddactionListener (new ActionListener () {@Override public Void ActionPerformed (ActionEvent E) {System.exit (0);}}); } / *** Método del constructor de la clase de juego principal** @param Title String, Título de la ventana* / public RussiaBlockSGame (título de cadena) {super (título); // Establecer el título SetSize (500, 600); // establecer el tamaño de la ventana setLocationRelativeto (nulo); // establecer el centro de ventana createMenu (); Contenedor contenedor = getContentPane (); // Crear contenedor de barra de menú.setLayout (nuevo BorderLayout (6, 0)); // Establecer el administrador de diseño del lienzo de la ventana = new GameCanvas (20, 15); // Crear un nuevo juego Canvas Ctrlpanel = nuevo ControlPanel (esto); // crear un nuevo contenedor de panel de control.add (lienzo, borderLayout.center); // Agregar Canvas Container.add (Ctrlpanel, borderLayout.east); // Agregar panel de control a la derecha // registra eventos de la ventana. Cuando se hace clic en el botón Cerrar, el juego termina y el sistema sale. addWindowlistener (new WindowAdapter () {@Override public void WindowClosing (WindowEvent We) {stopGame (); System.exit (0);}}); // Ajuste automáticamente el tamaño del cuadrado de acuerdo con el tamaño de la ventana addComponentListener (nuevo ComponentAdapter () {@Override public void ComponentResized (CompaneSeNEVENT CE) {Canvas.Adjust ();}}); setVisible (verdadero); Canvas.Adjust (); } /*** Restablecer el juego* /public void reset () {// restablecer el lienzo y restablecer el panel de control ctrlpanel.setPlayButtonable (true); ctrlpanel.setPauseButtonenable (falso); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setStopButtonable (falso); ctrlpanel.seturnLevelDownButtonable (verdadero); ctrlpanel.seturnlevelupButtonable (verdadero); miplay.setEnabled (true); MIPAUSE.SetEnabled (falso); Miresume.SetEnabled (falso); Mistop.SetEnabled (falso); ctrlpanel.reset (); Canvas.reset (); } / *** Determine si el juego todavía está en progreso** @return boolean, true - todavía se está ejecutando, falso -ha detenido* / public boolean isplaying () {return playing; } / *** Obtenga el bloque actualmente activo** @return ersblock, la referencia al bloque actualmente activo* / public ersblock getCurblock () {return Block; } / *** Obtenga el lienzo actual** @return gamecanvas, la referencia al lienzo actual* / public gameCanvas getCanvas () {return Canvas; } / *** Iniciar el juego* / public void playgame () {play (); ctrlpanel.setPlayButtonable (falso); ctrlpanel.setPauseButtonenable (verdadero); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setStopButtonable (true); ctrlpanel.seturnLevelDownButtonable (falso); ctrlpanel.seturnlevelupbuttonable (falso); Mistop.SetEnabled (verdadero); miturnharder.setEnabled (falso); mITURNEASIER.SetEnabled (falso); ctrlpanel.requestfocus (); // Establezca el enfoque en el panel de control}/*** PAUSE DE JUEGO*/public void pauseGame () {if (block! = Null) {block.pauseMove (); } ctrlpanel.setPlayButtonAnable (falso); ctrlpanel.setPauseButtonLabel (falso); ctrlpanel.setStopButtonable (true); miplay.setEnabled (falso); MIPAUSE.SetEnabled (falso); Miresume.SetEnabled (verdadero); Mistop.SetEnabled (verdadero); } / *** Deje que el juego pausado continúe* / public void reumeGame () {if (block! = Null) {block.resumeMove (); } ctrlpanel.setPlayButtonAnable (falso); ctrlpanel.setPauseButtonenable (verdadero); ctrlpanel.setPauseButtonLabel (true); MIPAUSE.SetEnabled (verdadero); Miresume.SetEnabled (falso); ctrlpanel.requestfocus (); } / *** El usuario detiene el juego* / public void stopGame () {juego = false; if (block! = null) {block.stopmove (); } ctrlpanel.setPlayButtonAnable (true); ctrlpanel.setPauseButtonenable (falso); ctrlpanel.setPauseButtonLabel (true); ctrlpanel.setStopButtonable (falso); ctrlpanel.seturnLevelDownButtonable (verdadero); ctrlpanel.seturnlevelupButtonable (verdadero); miplay.setEnabled (true); MIPAUSE.SetEnabled (falso); Miresume.SetEnabled (falso); Mistop.SetEnabled (falso); miturnharder.setEnabled (verdadero); MITURNEASIER.SetEnabled (verdadero); reset (); // Restablecer Canvas and Control Panel}/** * Obtenga la dificultad establecida por el jugador * * @return int, Dificultad del juego 1-MAX_LEVEL */public int getLevel () {return ctrlPanel.getLevel (); } / ** * El usuario establece la dificultad del juego * * @param nivel int, dificultad del juego 1-max_level * / public void setLevel (int nivel) {if (nivel <11 && nivel> 0) {ctrlpanel.setLevel (nivel); }} / *** Obtener puntos de juego** @return int, puntos* / public int getsCore () {if (Canvas! = NULL) {return Canvas.getScore (); } return 0; } /*** Obtenga puntos de juego desde la última actualización. Después de la actualización, este punto se borrará** @return int, ints*/ public int GetScoreForLevelUpdate () {if (Canvas! = Null) {return Canvas.getScoreForLevelUpdate (); } return 0; } / ** * Cuando la integral se acumula a un determinado valor, actualice una vez * * @return boolean, verdadero-update suctare, falso-actualización de actualización * / public boolean LevelUpdate () {int Curlevel = getLevel (); if (curlevel <max_level) {setLevel (curlevel + 1); Canvas.resetscoreForLevelUpdate (); devolver verdadero; } return false; } / *** Game Start* / private void play () {reset (); jugar = verdadero; Thread Thread = New Thread (New Game ()); // Inicie el juego Thread Thread.Start (); } / *** Informe El juego ha terminado* / private void reportGamever () {new GameOverdialog (this, "Tetris", "El juego termina, su puntaje es" + Canvas.getScore ()); } /*** Una ronda de proceso de juego, implementando la interfaz Runnable. Una ronda de juego es un gran bucle. En este bucle, cada 100 milisegundos, verifique si el bloque actual en el juego ha alcanzado el final. Si no, * continuará esperando. Si se trata del final, depende de si hay una línea completamente llena. Si lo hay, elimínelo y agregue puntos al jugador, y genere aleatoriamente un nuevo bloque de corriente y deje que caiga automáticamente. * Cuando se genera un nuevo bloque, primero verifique si la línea en la parte superior del lienzo ha sido ocupada. Si es así, puedes juzgar al juego. */ private class Game implements runnable {@Override public void run () {int col = (int) (math.random () * (canvas.getCols () - 3)); // genera aleatoriamente la posición de block int style = ersblock.styles [(int) (math.random () * 7)] [(int) (int) (math.random () * 4) de una forma mientras (jugando) {if (block! = null) {// El bloque está vacío if (block.isalive ()) {try {thread.currentThread (); Thread.sleep (500); } capt (interruptedException IE) {ie.printstacktrace (); } continuar; }} checkfullline (); // verifique si hay líneas completamente llenas if (isGamever ()) {reportGameOver (); miplay.setEnabled (true); MIPAUSE.SetEnabled (falso); Miresume.SetEnabled (falso); Mistop.SetEnabled (falso); ctrlpanel.setPlayButtonable (true); ctrlpanel.setPauseButtonLabel (falso); ctrlpanel.setStopButtonable (falso); devolver; } block = new Ersblock (estilo, -1, col, getLevel (), lienzo); block.Start (); col = (int) (math.random () * (canvas.getCols () - 3)); style = ersblock.styles [(int) (math.random () * 7)] [(int) (math.random () * 4)]; ctrlpanel.settipstyle (estilo); }} // Verifique si hay líneas completamente llenas en el lienzo. Si hay uno, elimínelo 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; romper; }} if (fulllineColorbox) {row = i--; Canvas.removeline (fila); }}} // juzga si el juego ha terminado en función de si la fila superior está ocupada //@return boolean, true-the game ha terminado, falso-el juego no es sobre isgameS de boolean privado () {para (int i = 0; i <canvas.getCols (); i ++) {box ersbox = canvas.getbox (0, i); if (box.iscolorbox ()) {return true; }} return false; }} /*** Defina el cuadro de diálogo GameOver. */ @SupplesSwarnings ("Serial") GameOverdialog de clase privada extiende jdialog implementos actionListener {private jButton Again Button, ExitButton; borde de borde privado = nuevo grabador grabado (grabador grabado. criado, color. White, nuevo color (148, 145, 140)); Public GameOverdialog (Jframe Parent, Título de cadena, Mensaje de cadena) {Super (Parent, Título, True); if (parent! = null) {setSize (240, 120); this.setLocationRelativeto (padre); JPanel MessagePanel = new JPanel (); MessagePanel.Add (new JLabel (Mensaje)); MessagePanel.SetBorder (frontera); Contenedor contenedor = this.getContentPane (); Container.setLayout (nuevo GridLayout (2, 0, 0, 10)); Container.add (MessagePanel); Jpanel choosepanel = new JPanel (); choosepanel.setLayout (nuevo GridLayout (0, 2, 4, 0)); contenedor.add (choosepanel); AgainButton = new JButton ("Juega otro juego"); exitButton = new JButton ("juego de salida"); choosepanel.add (nuevo JPanel (). ADD (Again Button)); choosepanel.add (nuevo JPanel (). Add (ExitButton)); choosepanel.setBorder (frontera); } AgainButton.AddactionListener (esto); exitButton.AddactionListener (esto); this.setVisible (verdadero); } @Override public Void ActionPerformed (ActionEvent E) {if (e.getSource () == AgainButton) {this.setVisible (falso); reiniciar(); } else if (e.getSource () == ExitButton) {stopGame (); System.exit (0); }}}}Gamecanvas.java
paquete russiaBlocksgame; import java.awt.color; import java.awt.graphics; import javax.swing.jpanel; import javax.swing.border.etchedborder; /*** clase de lienzo, con <número de filas>* <número de columnas> instancias de clase cuadrada. Heredado de la clase Jpanel. La clase de hilo ERSBLOCK cambia dinámicamente el color de la cuadrícula de la clase de lienzo. La clase de lienzo usa * para verificar el color de la cuadrícula para reflejar el movimiento del bloque ERSBLOCK. */ clase pública GameCanvas se extiende JPanel {privado estático final Long SerialVersionUid = 6732901391026089276l; Color privado BackColor = Color.DarkGray, frontColor = color.white; privado int filas, cols, stork = 0, scatterForLevelUpdate = 0; cajas privadas ersbox [] []; privado int boxwidth, boxheight; / *** Constructor de la clase de lienzo** @param filas int, el número de filas del lienzo* @param cols int, el número de columnas y columnas del lienzo determina el número de cuadrados que tiene el lienzo*/ public gameCanvas (int flotas, int cols) {this.rows = cazas; this.cols = cols; cajas = new Ersbox [filas] [cols]; for (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <boxes [i] .length; j ++) {boxes [i] [j] = new ersbox (falso); } } setBorder(new EtchedBorder(EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)); } /** * Constructor of the canvas class* * @param rows * @param cols * @param backColor * @param frontColor */ public GameCanvas(int rows, int cols, Color backColor, Color frontColor) { this (fila, cols); getBackgroundColor () {return backColor; * Obtenga el número de filas del cuadrado en el lienzo** @return*/ public int getRows () {return filas; } / *** Obtenga los puntos desde la última actualización** @return int, los puntos después de la última actualización* / public int GetScoreForLevelUpdate () {return storkForLevelUpdate; } / *** Obtenga la referencia cuadrada de una determinada fila y columna** @return fila int, la fila donde se hace referencia al cuadrado* @param col int, la fila donde el cuadrado debe ser referenciado* @return ersbox, la referencia del cuadrado en la columna de la fila de la fila* / public Ersbox getBox (int, int cajas [0] .Length - 1) {return null; 0; * Ajuste automáticamente el tamaño del cuadrado de acuerdo con el tamaño de la ventana * / public void ajust () {boxwidth = getSize (). Width / cols; removeline (int row) {for (int i = row; i> 0; i--) {for (int j = 0; j <cols; j ++) {cajas [i] [j] = (ersbox) cuadros [i-1] [j] .clone (); RussiABLOCHSGAME.PER_LEVEL_SCORE; j <cajas [i] .length;Controlpanel.java
paquete russiaBlocksgame; import java.awt.borderlayut; 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; /*** Clase de panel de control, heredada de JPanel. La ventana de vista previa, el nivel, la puntuación y los botones de control se colocan sobre ella. */ Class ControlPanel extiende jpanel {privado estático final long SerialVersionUid = 3900659640646175724l; privado 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 ("aumentar la dificultad"), btturvelledown = new jButton ("reducir la dificultad");; privado jpanel pltip = new JPanel (new BorderLayout ()); Tippanel privado pltipblock = new Tippanel (); Jpanel privado plinfo = nuevo JPanel (nuevo GridLayout (4, 1)); privado jpanel plButton = nuevo JPanel (nuevo GridLayout (6, 1)); temporizador de temporizador privado; borde de borde privado = nuevo grabador grabado (grabador grabado. criado, color. White, nuevo color (148, 145, 140)); /*** Constructor de la clase del panel de control** @param Game ersblocksgame, una referencia de instancia de la clase ERSBLOCKSGAME es conveniente para controlar directamente el comportamiento de la clase ERSBLOCKSGAME. */ public Controlpanel (juego final de RussiaBlocksgame) {setLayout (new GridLayout (3, 1, 0, 2)); pltip.add (new JLabel ("Next Square"), BorderLayout.north); // agregar componente pltip.add (pltipblock); pltip.setBorder (borde); plinfo.add (nuevo JLabel ("Coeficiente de dificultad")); plinfo.add (tflevel); plinfo.add (new Jlabel ("Score")); plinfo.add (tfscore); Plinfo.setBorder (frontera); plButton.add (btplay); btplay.setEnabled (true); plButton.add (btpause); btPause.SetEnabled (falso); PLBUTTON.Add (btStop); btstop.setEnabled (falso); PLBUTTON.Add (btturnlevelup); PLBUTTON.Add (BtTurnLevelDown); PLBUTTON.Add (TFTime); PLBUTTON.SETBORDER (frontera); tflevel.setEditable (falso); tfscore.setEditable (falso); tftime.setEditable (falso); Agregar (PLTIP); agregar (plinfo); agregar (plButton); addKeyListener (nuevo keyAdapter () {@Override public void keyPressed (keyEvent ke) {if (! game.isPlaying ()) {return;} ersblock block = game.getCurBlock (); switch (ke.getkeyCode ()) {keyEvent.vk_down: block.mOvedOwn (); break; break; break; break; break. Block.MoVelEt (); btplay.addactionListener (new ActionListener () {// Inicie el juego @Override Void ActionPerformed (ActionEvent Ae) {game.playgame ();}}); btPause.AdDActionListener (new ActionListener () {// Pausa el juego @Override public Void ActionperFormed (ActionEvent Ae) {if (btpause.gettext (). Equals ("pausa")) {Game.PauseGame ();} else {Game.resumeGame ();}}}); btstop.addactionListener (new ActionListener () {// Deten el juego @Override Void ActionPerformed (ActionEvent Ae) {game.stopGame ();}}); btturnlevelUp.addactionListener (new ActionListener () {// Incrementa la dificultad @Override public Void ActionperFormed (ActionEvent Ae) {intit {int nivel = Integer.ParseInt (tflevel.gettext ()); if (RussiaBlocksGame.max_level) {tflevel.settext ("" "") if) Catch (NumberFormAxception e) {} requestFocus (); btTurnLevelDown.AdDActionListener (new ActionListener () {// Reduce la dificultad del juego @Override public Void ActionperFormed (ActionEvent Ae) {try {int nivel = Integer.ParseInt (tflevel.gettext ()); if (nivel> 1) {tflevel.setTxt (" + (nivel - 1);}}}} } requestFocus (); addComponentListener (nuevo 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 ("hora: hh: mm: ss"); // El sistema obtiene fecha de hora = nueva fecha (); tftime.settext (format.format (fecha)); Game.getScore ()); timer.start (); } / *** Establezca el estilo de la ventana previa a la pantalla** @param style int, correspondiente a los 28 valores en los estilos de la clase ERSBLOCK* / public void settipstyle (int style) {pltipblock.setStyle (estilo); } /*** Obtenga el nivel de juego establecido por el usuario. * * @return int, nivel de dificultad, 1-esblocksgame.max_level */ public int getLevel () {int nivel = 0; prueba {nivel = Integer.ParseInt (tflevel.gettext ()); } catch (numberFormateException e) {} nivel de retorno; } /*** Permita que los usuarios modifiquen el nivel de dificultad del juego. * * @param Nivel Modificado de dificultad del juego */ public void setLevel (int nivel) {if (nivel> 0 && nivel <11) {tflevel.setText ("" + nivel); }} /*** Establezca el estado del botón "Inicio". */ public void setPlayButtonAnable (boolean enable) {btplay.setEnabled (enable); } public void setPauseButtonAnable (boolean enable) {btPause.SetEnabled (enable); } public void setPauseButtonLabel (pausa boolean) {btpause.settext (pausa? "pausa": "continuar"); } public void setstopButtonAnable (boolean enable) {btStop.SetEnabled (enable); } public void seturnlevelUpButtonable (Boolean Enable) {btTurnLevelUp.SetEnabled (enable); } public void SeturnLevelDownButtonable (Boolean Enable) {btTurnLevelDown.SetEnabled (enable); } / *** Restablecer panel de control* / public void reset () {tfscore.setText ("0"); pltipblock.setStyle (0); } / *** Recalcule el tamaño de la caja pequeña en las cajas [] [] en tippanel* / public void ajust () {pltipblock.adjust (); } /*** La clase de detalles de implementación de la ventana previa a la muestra* /public class Tippanel extiende jpanel {// tippanel se usa para mostrar la forma del siguiente bloque para aparecer privado estatic final long serialversionUid = 5160553671436997616L; Color privado BackColor = Color.DarkGray, frontColor = color.white; Private ERSBox [] [] cajas = new ERSBox [esblock.boxes_rows] [esblock.boxes_cols]; Private int Style, Boxwidth, BoxHeight; booleano privado istiled = false; / *** Constructor de clase de ventana previa a la muestra*/ public tippanel () {for (int i = 0; i <boxes.length; i ++) {for (int j = 0; j <boxes [i] .length; j ++) {cuadros [i] [j] = new ersbox (falso); }}} / *** Establezca el estilo de bloque de la ventana previa a la pantalla** @param style int, correspondiente a 28 valores en los estilos de la clase ersblock* / public void setStyle (int style) {this.style = style; repintado (); } /*** Sobrescribe las funciones de la clase JComponent y dibujan componentes. * * @param g entorno del dispositivo gráfico */ @Override public void PaintComponent (Graphics g) {super.paintComponent (g); if (! istiled) {ajust (); } 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); clave >> = 1; }}} / *** g Ajuste automáticamente el tamaño del cuadrado de acuerdo con el tamaño de la ventana* / public void ajust () {boxWidth = getSize (). width / ersblock.boxes_cols; boxHeight = getSize (). Height / ersblock.boxes_rows; istiled = verdadero; }}}Ersbox.java
paquete russiaBlocksgame; import java.awt.dimension; / *** La clase cuadrada es el elemento básico que constituye el bloque, y usa su propio color para representar la apariencia del bloque*/ public class ERSBox implementa clonable {ISColor booleano privado; tamaño de dimensión privada = new Dimension (); / ** * El constructor de la clase cuadrada, * * @param iscolor hace el color de primer plano para colorear este color de primer plano verdadero cuadrado, falso uso de color */ public ersbox (boolean iscolor) {this.iscolor = isColor; } / *** ¿Es este cuadrado expresado en el color de primer plano** @return boolean, verdadero expresado en el color de primer plano, falso expresado en el color de fondo* / public boolean iscolorbox () {return isColor; } / ** * Establezca el color del cuadrado, * * @param iscolor boolean, verdadero expresado en el color de primer plano, falso expresado en el color de fondo * / public void setColor (boolean iscolor) {this.iscolor = isColor; } / *** Obtenga el tamaño de este cuadrado** @Dimension, el tamaño del cuadrado* / public dimension getSize () {return size; } / ** * Establezca el tamaño del cuadrado, * * @param dimensión de tamaño, el tamaño del cuadrado * / public void setSize (tamaño de dimensión) {this.size = size; } / *** Sobrescribe el objeto del objeto clone (), implementa clon** @return objeto, resultado de clon* / @Override public objeto clone () {objeto clone = null; intente {clone = super.clone (); } catch (Exception Ex) {Ex.PrintStackTrace (); } clon de retorno; }}Ersblock.java
paquete russiaBlocksgame; / *** La clase de bloque, heredada de la clase de subprocesos (hilo), consta de 4 × 4 bloques (ERSBox), controlando el movimiento, la caída, la deformación del bloque, etc.*/ clase ERSBLOCK extiende el hilo {/ *** El número de filas ocupadas por un bloque es 4 filas*/ pública final final INT Boxes_rows = 4; / *** El número de columnas ocupadas por un bloque es 4 columnas*/ Public final static int boxes_cols = 4; / *** El factor que suaviza los cambios de actualización para evitar casi el doble de la diferencia de velocidad entre las últimas etapas*/ pública final static int nivel_flatness_gene = 3; / ** * ¿Cuál es la diferencia entre los dos niveles similares del bloque para cada fila (milisegundos) */ público final static int entre_levels_degress_time = 50; / ** * El número de estilos de bloques es 7 */ público final static int block_kind_number = 7; / ** * El tipo de estado de inversión de bloques de cada estilo es 4 */ Public final static int block_status_number = 4; /*** 28 estados correspondientes a 7 modelos respectivamente*/public final static int [] [] styles = {// total 28 estados {0x0f00, 0x4444, 0x0f00, 0x4444}, // cuatro estados de rayas largas {0x04e0, 0x0464, 0x00e4, 0x04c4}, // cuatro estados de type de type de type de Tye {0x4620, 0x6c00, 0x4620, 0x6c00}, // Cuatro estados de tipo Z de tipo {0x2640, 0xc600, 0x2640, 0xc600}, // cuatro estados de tipo z {0x6220, 0x1700, 0x2230, 0x0740}, // cuatro estados de los estados de 7 type {0x6440, 0x0e20, 0x44c0, 0x8e00}, // cuatro estados de inverso 7 tipo {0x0660, 0x0660, 0x0660, 0x0660}, // cuatro estados de bloque}; lienzo de gamecanvas privado; Private ERSBox [] [] Boxes = new ERSBox [Boxes_Rows] [Boxes_Cols]; Private int Style, y, x, nivel; pausa booleana privada = falso, mudanza = verdadero; / *** constructor, genera un bloque específico*** @param estilo el estilo del bloque, correspondiente a uno de los 28 valores de los estilos* @param y posición de inicio, línea coordinada en la esquina superior izquierda en lienzo* @param x posición de inicio, columna de coordenadas en la esquina superior izquierda en el livel* @param nivel de juego de nivel, controle la velocidad de caída del bloque* @param canvas board*/ pública Última (intentador (intento, intente, intentador (intento, intente, intentador (intento, intente, intente, intente (intento, intente (intente, (intento, intente (intento, ( @estilo, intente. x, int nivel, Canvas de gamecanvas) {this.style = style; this.y = y; this.x = x; this.level = nivel; 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); cajas [i] [j] = new ersbox (isColor); clave >> = 1; } } mostrar(); } / *** La función run () de las cubiertas de la clase de hilo y deja caer el bloque hasta que el bloque no puede caer nuevamente* / @Override public void run () {while (mudando) {try {sleep (entre_levels_degress_time* (russiaBlocksgame.max_level - nivel + nivel_flatness_gene)); } capt (interruptedException IE) {ie.printstacktrace (); } // El movimiento posterior significa que el movimiento no se ha cambiado durante los 100 milisegundos de esperar si (! Pausing) {Moving = (Moveto (y + 1, x) && Moving); }}}} / ** * El bloque mueve una cuadrícula a la izquierda * / public void Moveleft () {Moveto (y, x - 1); } / ** * El bloque mueve una cuadrícula a la derecha * / public void Moveright () {Moveto (y, x + 1); } / ** * El bloque mueve una cuadrícula a la derecha * / public void Moventown () {Moveto (y + 1, x); } / *** BLOCK Variant* / 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; Turnto (NewStyle); devolver; }}}} public void startMove () {pausing = false; mudanza = verdadero; } /** * 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; borrar(); 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"); }} Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.