Aprendí esta técnica el año pasado y aún no la he escrito. Ahora me he tomado el tiempo de escribir un juego de Tetris.
Solo el nuevo juego simple, pausa, continuar, la función de puntos. Simplemente se da cuenta de las funciones rusas clásicas.
Ya no lo presentaré. Si está interesado, ejecutarlo usted mismo y publique una foto más tarde.
Código:
paquete cn.hncu; import java.awt.color; import java.awt.font; import java.awt.graphics; import java.awt.event.actionEvent; import java.awt.event.actionListener; import java.awt.event.keyAdapter; import java.awt.event; javax.swing.jmenu; import javax.swing.jmenubar; import javax.swing.jmenuitem; import javax.swing.joptionPane; import javax.swing.jpanel; import javax.swing.timer; tetris de clase pública extiende jframe {public void main (string [] tetris tets (= tetris (= tetris (); te.setVisible (verdadero); // Si agrega un cuadro de edición a la interfaz que se apoderará del enfoque, debe usar el siguiente código //te.requestfocus(true) ;//let el panel de juego obtiene enfoque: obtenga la escucha del teclado} Tetrispanel privado TP; JMenuitem itemPause; JMenuitem itemContinue; public tetris () {this.setDefaultCloseOperation (EXIT_ON_CLOSE); this.setLocation (700, 200); this.setsize (220, 275); this.setResizable (falso); tp = new Tetrispanel (); this.getContentPane (). add (tp); // Agregar menú JMenubar Menubar = new JMenubar (); this.setjmenubar (Menubar); JMenu Menugame = new JMenu ("Juego"); Menubar.add (Menugame); JMenuitem itemNew = new JMenuitem ("nuevo juego"); itemNew.SetActionCommand ("nuevo"); itemPause = new JMenuitem ("Pausa"); itemPause.SetActionCommand ("Pausa"); itemContinue = new JMenuitem ("Continuar"); itemContinue.SetActionCommand ("Continuar"); itemContinue.SetEnabled (falso); Menugame.Add (ItemNew); Menugame.add (itemPause); Menugame.add (itemContinue); Menulistener menulistener = new Menulistener (); itemnew.AddactionListener (Menulistener); itemPause.AddactionListener (Menulistener); itemContinue.AddactionListener (Menulistener); // deja que todo Jframe agregue el teclado escuchando esto.addkeylistener (tp.listener); } clase Menulistener implementa ActionListener {@Override public void ActionPerformed (ActionEvent E) {// Play New Game if (E.GetActionCommand (). Equals ("New")) {tp.newGame (); } if (e.getActionCommand (). Equals ("Pausa")) {Timer.stop (); itemContinue.SetEnabled (verdadero); itemPause.SetEnabled (falso); } if (e.getActionCommand (). Equals ("Continuar")) {timer.restart (); itemContinue.SetEnabled (falso); itemPause.SetEnabled (true); }}} temporizador de temporizador privado; clase Tetrispanel extiende jpanel {// forma del cuadrado: // La primera dimensión representa el tipo de bloque (incluidos 7 tipos: S, S, Z, J, I, O, T) // La segunda dimensión representa el número de rotaciones // La tercera y cuarta dimensión representa la matriz de bloques // las formas de bloque formas [] [] [] = new int [] [] [] { / * * plantilla { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, , 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, {0,0,0,0,0,0,0,0,0,0, * 0,0,0,0,0,0,0,0,0,0} } */ // I (※Switch the bar in version 1 from line 1 to line 2) { { 0, 0, 0, 0, 0, 1, 1, 1, 1, 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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, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // L { { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // T { { 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {1, 1, 1, 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}; private int blocktype; // block type private int turnstate; // estado de rotación private int x; // block posición x-columna posición de columna número int y; // posición de bloque y-fila de posición-fila de filas privadas int map [] [] = new int [13] [23]; // mapa: 12 columnas y 22 rodajas. Para evitar transfronader, la matriz se abre en: 13 columnas y 23 filas privadas int demora = 1000; Public TimerKeylister Listener = new TimerKeylister (); private int store = 0; // score public tetRispanel () {newGame (); nextblock (); // temporizador = nuevo temporizador (retraso, oyente); //timer.start (); } public void newGame () {blockType = (int) (math.random ()*1000)%7; TurnState = (int) (Math.random ()*1000)%4; x = 4; y = 0; for (int i = 0; i <12; i ++) {// línea para (int j = 0; j <21; j ++) {// caminando if (i == 0 || i == 11) {// 3 es la cuadrícula del mapa de la frontera de interfaz [i] [j] = 3; // realmente, solo use los intérmenes que no sean 0 y 1, pero el uso de 3 aquí tiene un efecto especial - uso}} mapa {map) }} map [i] [21] = 3; // 3 es la cuadrícula del borde de la interfaz} if (timer! = null) {timer.stop (); } retraso = 1000; temporizador = nuevo temporizador (retraso, oyente); timer.start (); } private void nextBlock () {blockType = (int) (math.random ()*1000)%7; TurnState = (int) (Math.random ()*1000)%4; x = 4; y = 0; // Juego sobre if (Crash (X, Y, BlockType, TurnState) == 0) {Timer.stop (); int option = joptionPane.showConfirmDialog (este "juego terminado !!, todavía te atreves a venir ..."); if (option == jOptionPane.ok_option) {newGame (); } else if (opción == JOptionPane.No_Option) {System.Exit (0); }}} private void down () {if (Crash (x, y+1, blocktype, turnstate) == 0) {// Tenga en cuenta que y+1 se usa aquí para determinar si la posición correspondiente en el mapa es un bloque o marco apilados después de que el bloque se caiga en un cuadrado; // guarda la información del bloque actual al mapa NextBlock (); } else {y ++; } repint (); } private void izquierdo () {if (x> = 0) {x -= choque (x -1, y, blocktype, turnstate); } repint (); } private void derecha () {if (x <8) {x += choque (x +1, y, blocktype, turnstate); } repint (); } private void thur () {if (choque (x, y, blocktype, (turnstate+1)%4) == 1) {turnstate = (turnstate+1)%4; } repint (); } private void add (int x, int y, int blocktype, int turnstate) {for (int a = 0; a <4; a ++) {for (int b = 0; b <4; b ++) {if (shapes [blockType] [turnstate] [a*4+b] == 1 1) {map [x+b+1] [y+a] = 1; }}} trydelline (); } // Eliminar vacío privado trydelline () {for (int b = 0; b <21; b ++) {int c = 1; para (int a = 0; a <12; a ++) {c & = map [a] [b]; // Todos son 1, el resultado de c es 1} if (c == 1) {// Hay una línea que debe eliminarse // mover una línea en la secuencia para (int d = b; d> 0; d-) {int e = 0; e <11; e ++) mapa [e] [d-1]; }} // Agregar puntaje de puntos += 100; retraso /=1.05; timer.setDelay (retraso); }}} // Ejemplo de parámetro: 4,3,2,3 // juzga si hay una colisión privada int cloque (int x, int y, int blocktype, int turnstate) {for (int a = 0; a <4; a ++) {for (int b = 0; b <4; b ++) {// if ((forma de blocktype] [thurn 4+b] map [x+b+1] [y+a] == 1) || // (formas [blockType] [turnstate] [a*4+b] == 1 && map [x+b+1] [y+a] == 3)) {///} if ((blockType] [thurnstate] [a*4+b] & map [x+b+1] [y+A+1) 0; // colisión}}} return 1; // sin colisión} @Override public void Paint (gráficos g) {// blocktype = 6; // turnstate = 3; // x = 4; // y = 6; Super.Paint (g); // eliminar la imagen de la imagen G.SetColor (nuevo color (153,51,205)); // Dibuja el bloque de corriente para (int j = 0; j <16; j ++) {if (formas [blocktype] [turnstate] [j] == 1) {g.fillrect ((j%4+x+1)*10, (j/4+y)*10, 10, 10); G.SetColor (Color.cyan); G.Drawrect ((J%4+x+1)*10, (j/4+y)*10, 10, 10); G.SetColor (nuevo color (153,51,205)); }} // Dibuja el marco de la interfaz y los bloques de pila --- todo el mapa G.SetColor (color.red); para (int i = 0; i <12; i ++) {// caminar para (int j = 0; j <22; j ++) {// caminar if (map [i] [j] == 3) {g.drawrect (i*10, j*10, 10, 10); } else if (map [i] [j] == 1) {g.fillrect (i*10, j*10, 10, 10); G.SetColor (color.green); g.drawrect (i*10, j*10, 10, 10); G.SetColor (Color.Red); }}} // Muestra el puntaje, y el diseño es hermoso, agregue algo a la interfaz // dibuje la parte derecha del área cuadrada G.SetColor (color.red); G.SetFont (nueva fuente ("AA", Font.Bold, 11)); G.DrawString ("Score =" + Score, 130, 20); G.SetFont (nueva fuente ("AA", Font.Plain, 13)); G.SetColor (color.blue); G.DrawString ("Rechazar juegos pirateados", 125, 70); G.DrawString ("Tenga cuidado con la autoprotección", 125, 90); G.DrawString ("Cuidado con ser engañado", 125, 110); G.DrawString ("El juego moderado es bueno para el cerebro", 125, 130); G.DrawString ("Agregar al juego es perjudicial para el cuerpo", 125, 150); G.DrawString ("Tiempo de programación razonablemente", 125, 170); G.Drawstring ("Disfruta de una vida saludable", 125, 190); } class TimerKeylister extiende KeyAdapter implementa ActionListener {@Override public void ActionPerformed (ActionEvent E) {down (); } @Override public void KeyPressed (KeyEvent E) {switch (E.GetKeyCode ()) {Case KeyEvent.vk_down: down (); romper; case keyEvent.vk_left: left (); break; case keyEvent.vk_right: right (); break; case keyEvent.vk_Up: gurn (); break; Case keyEvent.vk_f1: plug (); caso KeyEvent.vk_f2: Time (); }} public void plug () {score+= 100; } public void time () {demandado = 1000; timer.setDelay (retraso); }}}Ejecutar interfaz:
Para juegos más emocionantes, consulte el tema especial "Java Classic Games"
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.