Los ejemplos en este artículo comparten con usted el código específico de implementación de Java Tetris para su referencia. El contenido específico es el siguiente
Ideas de diseño de tetris
Tetris ha estado jugando desde la infancia. Todos conocen las reglas. En el pasado, pensé que esa cosa era muy divertida, pero no podía ganar. ¡Ahora he aprendido a escribir uno solo y practicarlo todos los días!
Operación de teclado:
Clave izquierda: mover a la izquierda; Clave correcta: mover a la derecha;
Clave de arriba: Cambie la forma y la clave inferior: acelere la caída (sin problema, no hay más rectificación)
Si los cuadrados de cualquier fila están llenos, esta línea será eliminada. Eliminar una fila de cuadrados obtendrá 10 puntos. En la actualidad, no he establecido los niveles. Los bebés a los que les gusta pueden establecer los niveles ellos mismos;
Entonces, ¿de dónde vienen esas formas cuadradas? Está diseñado por nosotros nosotros mismos. Las formas comunes son: tipo I, tipo t, tipo L, tipo de cuadrícula Tianzi, etc., ¡agrégalas tú mismo!
Entonces, ¿qué pasó? De hecho, es solo una matriz 4*4. Por supuesto, puedes diseñar n*n felizmente, ¡tienes la última palabra!
Entonces, di un ejemplo a continuación para decirte por qué las formas que ves se pueden cambiar están diseñadas por adelantado, 0 está vacío y 1 es un relleno, ¡para que puedas crear formas en tu juego!
Olvídalo: simplemente coloque la imagen y vea el código ejecutando los resultados primero:
Te gusta? Si te gusta, hazlo directamente. Tal vez el código no está lo suficientemente escrito. Por favor, perdóname. Resumiré más cuando miro hacia atrás y seguiré actualizando el código;
Clase GamePanel: clase de interfaz de juego, todo el bloque se elimina y se muestra, y la lógica lenta del juego se implementa en esta clase;
paquete tetris; import java.awt.graphics; import java.awt.event.ActionEvent; import java.awt.event.actionListener; import java.awt.event.keyevent; import java.awt.event.Keylistener; import java.util.random; import javax.swing.joption; javax.swing.jpanel; import javax.swing.timer; public class gamePanel extiende jpanel implementa keylistener {private int maprow = 21; private int mapcol = 12; private int mapgame [] [] = new int [maprow] [mapcol]; // Abra un espacio de matriz bidimensional para almacenar nuestra información de mapa Temporizador de temporizador privado; Private int store = 0; // Registre la puntuación Random Random = New Random (); Private int curshapeType = -1; Private int Private int NextShapeState = -1; // Establezca el tipo y el estado del grupo de bloques que aparece la próxima vez private int posx = 0; privado int posy = 0; Las formas de int -int -int -{{0,1,0,0,0,0, 1,1,1,0, 0,0,0,0,0}, {0,0,0,0}, / / /}, /}, {0,0,0,0,0,0}, / /las formas} de {0,0,0}, /{0,0} los} {0,0,0,0}, {0,0,0,0}, /{0,0,0}, {glifos. Orden {{0,0,0,0, 1,1,1,1,1,0,0,0,0, 0,0,0,0,0}, {0,1,0,0,0, 0,1,0,0, 0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, {0,1,1,0, 1,1,0,0, 0,0,0,0,0,0,0}, {1,0,0,0, 1,1,0,0,0,0,0,0}, // z-en forma z 1,0,0,0,0,0}, {1,1,0,0, 0,1,1,0,0,0,0,0,0}, {1,1,0,0, 0,1,1,0,0,0,0,0,0}, {0,1,0,0, 1,1,0,0, 1,0,0,0,0,0,0}, //J glyphs are stored in counterclockwise order { {0,1,0,0, 0,1,0,0, 1,1,0,0, 0,0,0,0,0,0}, {1,1,1,0, 0,0,1,0,0,0,0,0,0,0,0}, {1,1,0,0, 1,0,0,0,0,0,0,0}, {1,0,0,0, 1,1,0,0,0,0,0,0}, {1,0,0,0, 1,1,0,0,0,0,0,0,0,0}, // l Los glifos se almacenan en orificio en sentido antihorario {{1,0,0,0,0,0, 1,0,0,0, 1,1,0,0,0,0,0,0,0,0,0}, {0,0,1,0, 1,1,0,0, 1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0}, {1,1,0,0, 0,1,0,0,0,0,0,0,0,0}, {1,1,1,0, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0}}}}; Private int Rowrect = 4; Private int colrect = 4; // Aquí consideramos la imagen almacenada como una matriz bidimensional 4*4. Aunque usamos una matriz unidimensional para almacenarla anteriormente, aún necesitamos considerarla como una matriz bidimensional para implementar private int rectwidth = 10; public gamePanel () // constructor ---- crea un buen mapa {Createrect (); initMap (); // Inicializar este mapa setwall (); // set wall // crereaterect (); temporizador = nuevo temporizador (500, new TimerListener ()); timer.start (); } class TimerListener implementa ActionListener {public Void ActionPerformed (ActionEvent E) {MovedOwn (); }} public void setwall () // columna 0 y 11 son paredes, y la fila 20 también es paredes {para (int i = 0; i <maprow; i ++) // dibujar la columna primero {mapgame [i] [0] = 2; mapgame [i] [11] = 2; } para (int j = 1; j <mapcol-1; j ++) // dibujar la última línea {mapgame [20] [j] = 2; }} public void initMap () // Inicializar este mapa, el ID de pared es 2, la identificación del espacio es 0 y la ID de bloque es 1 {para (int i = 0; i <maprow; i ++) {for (int j = 0; j <mapcol; j ++) {mapgame [i] [j] = 0; }}} public void creeaterect () // Crear bloque --- Si el tipo de bloque y el estado actuales existen, establezca la próxima vez, si no, establece el estado actual y el tipo {if (curshapeType == -1 && curshapeState == -1) // El estado de bloque actual es 1, indicando que el juego solo ha comenzado {curshapeType = aleator.nextint (shapes.llength); curshapeState = random.nextint (formas [0] .length); } else {curshapeType = nextShapeType; curshapeState = nextShapeState; } nextShapeType = Random.NextInt (formas.length); nextShapeState = Random.NextInt (formas [0] .length); posx = 0; Posy = 1; // Crear un cuadrado en la esquina superior izquierda de la pared if (GameOver (Posx, Posy, curshapeType, curshapeState)) {jOptionPane.showConfirmDialog (NULL, "Game End!", "Tip", jOptionPane.ok_option); System.exit (0); }} public boolean Gameover (int x, int y, intshapeType, int flapestate) // juzga si el juego termina {if (isornomove (x, y, shapeType, rayado)) {return false; } return verdadero; } Public boolean isornomove (int x, int y, int ShapeType, int flapestate) // juzga si la cifra actual se puede mover. Aquí enfatizamos que las coordenadas de x e y se refieren al objetivo superior izquierdo de una matriz bidimensional de 4*4 (la matriz que describe la figura) {for (int i = 0; i <rowrect; i ++) {for (int j = 0; j <colrect; j ++) {si (shapeType] [shapestate] [i*i*i*i*i*i*jmrect ;= 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 MAPGAME [X+I] [y+J] == 1 || }}} return true; } public void Turn () // rotar {int temp = curshapeState; curshapeState = (curshapeState+1) % formas [0] .length; if (isornomove (posx, posy, curshapeType, curshapeState)) {} else {curshapeState = temp; } repint (); } public void Moviendown () // Mover {if (isornomove (posx+1, posy, curshapeType, curshapeState)) {posx ++; } else {addTomap (); // corrige esta línea en la línea de verificación del mapa (); Creeaterect (); // recree un nuevo bloque} repint (); } public void Moveleft () // Move a la izquierda {if (isornomove (posx, posy-1, curshapeType, curshapeState)) {posy--; } repint (); } public void Moveright () // Mover a la derecha {if (isornomove (posx, posy+1, curshapeType, curshapeState)) {posy ++; } repint (); } public void addTomap () // corrige la imagen caída en el mapa {for (int i = 0; i <rowrect; i ++) {for (int j = 0; j <colrect; j ++) {if (shapes [curshapeType] [curshapestate] [i*colrect+j] ==) formas [curshapeType] [curshapeState] [i*colrect+j]; }}}} public Void Checkline () // Verifique si hay filas completas en estas líneas {int count = 0; for (int i = maprow-2; i> = 0; i--) {count = 0; for (int j = 1; j <mapcol-1; j ++) {if (mapgame [i] [j] == 1) {count ++; } el más ruptura; } if (count> = mapcol-2) {for (int k = i; k> 0; k--) {for (int p = 1; p <mapcol-1; p ++) {mapgame [k] [p] = mapGame [k-1] [p]; }} puntaje += 10; i ++; }}} public void Paint (Graphics g) // Repaint Window {super.paint (g); for(int i = 0; i < rowRect; i++)//Draw the falling block { for(int j = 0; j < colRect; j++) { if(shapes[curShapeType][curShapeState][i*colRect+j] == 1) { g.fillRect((posy+j+1)*RectWidth, (posx+i+1)*RectWidth, Rectwidth, rectwidth); } } } for(int i = 0; i < mapRow; i++)//Draw the block information that has been fixed on the map { for(int j = 0; j < mapCol; j++) { if(mapGame[i][j] == 2)//Draw the wall{ g.drawRect((j+1)*RectWidth, (i+1)*RectWidth, RectWidth, Rectwidth); } if (mapGame [i] [j] == 1) // dibujar pequeño cuadrado {g.fillrect ((j+1)*rectwidth, (i+1)*rectwidth, rectwidth, rectwidth); }}} G.DrawString ("score ="+ stork, 225, 15); G.DrawString ("Next Square:", 225, 50); for (int i = 0; j <colrect; j ++) {if (formas [nextshapeType] [nextShapeState] [i*colrect+j] == 1) {g.fillrect (225+ (j*rectwidth), 100+ (i*rectwidth), rectwidth, rectwidth); }}}} public void newGame () // El juego comienza de nuevo {score = 0; initMap (); Setwall (); Creeaterect (); repintado (); } public void stopGame () // El juego pausa {timer.stop (); } public void continúa () {timer.start (); } @Override public void keyTyped (keyEvent e) {} @Override public void keyPressed (keyEvent e) {switch (e.getKeyCode ()) {case Keyevent.vk_up: // up ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- KeyEvent.vk_right: // Right ----- Moveright (); romper; }} @Override public void KeyReleed (KeyEvent E) {// TODO STUB de método generado automático}} GameFrame Clase: el puerto de entrada de todo el juego, bueno, para decirlo sin rodeos, es una clase con la función Main (). Esta clase implementa algunos diseños de la interfaz del juego, que puedes entender como una pequeña interfaz de usuario;
paquete tetris; import java.awt.event.ActionEvent; import java.awt.event.actionListener; import javax.swing.jframe; import javax.swing.jmenu; import javax.swing.jmenubar; import javax.swing.jmenuitem; import javax.swing.joption; ActionListener {private int widthframe = 500; Private int HeightFrame = 600; Menú de JMenu privado = new JMenu ("Juego"); // Crear un menú Privado JMenuitem newGame = menú.add ("reiniciar"); // Cree una opción de menú incorporada JMENITEM EXITGAME = Menu.add ("Game Exit"); stopGame privado JMenuitem = menú.add ("Game Pause"); privado jmenuitem goongame = menú.add ("Juego continúa"); privado JMenu Menutwo = new JMenu ("Ayuda"); // Crear un segundo menú JMenuitem privado Acerca degame = Menutwo.add ("Acerca del juego"); GamePanel gamePanel = new GamePanel (); Public GameFrame () // Constructor {Addkeylistener (GamePanel); newGame.AddactionListener (esto); exitGame.AddactionListener (this); stopGame.AddactionListener (esto); Goongame.AddactionListener (esto); Aboutgame.AddactionListener (this); this.add (GamePanel); JMENUBAR Menu = new JMenubar (); Menu.Add (MenuOne); menú.Add (Menutwo); this.setJMenubar (menú); this.settitle ("tetris"); this.setBounds (50, 10, Widthframe, altura); this.setVisible (verdadero); this.setDefaultCloseOperation (jframe.exit_on_close); } public void ActionPerformed (ActionEvent E) {if (e.getSource () == NewGame) // El juego comienza nuevamente {gamePanel.newGame (); } if (e.getSource () == ExitGame) // Game Exit {System.exit (0); } if (e.getSource () == StopGame) // Game Pausa {GamePanel.stopGame (); } if (e.getSource () == goongame) // juego continúa {gamePanel.continueGame (); } if (e.getSource () == Aboutgame) // Acerca de la información del juego {joptionPane.ShowMessEdialog (nulo, "Mueva las teclas izquierda y derecha, cree rotación hacia arriba", "solicitante", jOptionPane.ok_option); }} public static void main (string [] args) {new GameFrame (); }}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.