Aprendi essa técnica no ano passado e ainda não a escrevi. Agora eu dediquei um tempo para escrever um jogo de tetris.
Apenas um novo jogo simples, pausa, continue, os pontos funcionem. Ele simplesmente percebe as funções clássicas russas.
Eu não vou mais apresentar. Se você estiver interessado, execute você mesmo e poste uma foto mais tarde.
Código:
pacote cn.hncu; importar java.awt.color; importar java.awt.font; importar java.awt.graphics; importar java.awt.event.actionEvent; import java.awt.event.eactionListener; importan; javax.swing.jmenu; importar javax.swing.jmenubar; importar javax.swing.jmenuitem; importar javax.swing.JOptionPane; import javax.swing.jpanel; te.setVisible (true); // Se você adicionar uma caixa de edição à interface que apreenderá o foco, precisará usar o seguinte código //te.requestFocus(tuRue) ;//let the Game Painel Get Focus-obtenha o teclado que escuta} private tetrispainel tp; Jmenuitem ItemPause; Jmenuitem itemContinue; public tetris () {this.setDefaultCloseoperation (exit_on_close); this.setLocation (700, 200); this.SetSize (220, 275); this.setResizable (false); tp = new tetrispAnel (); this.getContentPane (). Add (tp); // Adicionar menu jmenubar Menubar = new jmenubar (); this.setjmenubar (Menubar); Jmenu menugame = new jmenu ("jogo"); menubar.add (menugame); Jmenuitem ItemNew = New Jmenuitem ("Novo Jogo"); itemNew.SetActionCommand ("novo"); itemPause = new jmenuitem ("pausa"); itemPause.setActionCommand ("pausa"); itemContinue = new Jmenuitem ("Continue"); itemContinue.SetActionCommand ("Continue"); itemContinue.setEnabled (false); menugame.add (itemNew); menugame.add (itemPause); menugame.add (itemContinue); Menulistener Menulistener = New Menulistener (); itemNew.addactionListener (Menulistener); itemPause.addactionListener (Menulistener); itemContinue.addactionListener (Menulistener); // Deixe todo o JFRame adicione o teclado ouvindo this.adDkeyListener (tp.Listener); } classe Menulistener implementa ActionListener {@Override public void ActionPerformed (ActionEvent e) {// Jogue novo jogo if (e.getActionCommand (). Equals ("new")) {tp.newgame (); } if (e.getActionCommand (). Equals ("pausa")) {timer.stop (); itemContinue.setEnabled (true); itemPause.setEnabled (false); } if (e.getActionCommand (). Equals ("Continue")) {timer.restart (); itemContinue.setEnabled (false); itemPause.setEnabled (true); }}} temporizador privado; class TetrisPanel extends JPanel{ // Shape of the square: // The first dimension represents the block type (including 7 types: S, Z, L, J, I, O, T) // The second dimension represents the number of rotations // The third and fourth dimension represents the block matrix // shapes[type][turnState][i] i--> block[i/4][i%4] int Shapes [] [] [] = new int [] [] [] { / * * modelo { {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0. 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 } }, // S { { 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0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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, 0 } } }; private int blocktype; // tipo de bloco privado int turnstate; // estado de rotação privado int x; // Posição do bloco x- coluna de posição coluna column private int y; // Posição do bloco y-robuste-row número private int map [] [] = new int [13] [23]; // mapa: 12 colunas e 22 linhas. Para prevenir a fronteira transfronteiriça, a matriz é aberta em: 13 colunas e 23 linhas privadas int a atraso = 1000; public timerKeylister ouvinte = new TimerKeyLister (); private int escore = 0; // pontuação pública tetrispAnel () {newGame (); nextBlock (); // timer = novo timer (atraso, ouvinte); //timer.start (); } public void newGame () {blocktype = (int) (math.random ()*1000)%7; Turnstate = (int) (Math.random ()*1000)%4; x = 4; y = 0; para (int i = 0; i <12; i ++) {// linha para (int j = 0; j <21; j ++) {// caminhando if (i == 0 || i == 11) {// 3 é a grade do mapa da interface [i] [j] = 3; // realmente, use integers »» {1 [i] [i] [j] = 3; realmente//apenas, use »» »» que {1, mas 1, mas 1; }} mapa [i] [21] = 3; // 3 é a grade da borda da interface} if (timer! = null) {timer.stop (); } atraso = 1000; timer = novo timer (atraso, ouvinte); timer.start (); } private void nextBlock () {blocktype = (int) (math.random ()*1000)%7; Turnstate = (int) (Math.random ()*1000)%4; x = 4; y = 0; // jogo over if (frash (x, y, blocktype, turnstate) == 0) {timer.stop (); int option = joptionpane.showconfirmdialog (isto, "jogo over !!, você ainda ousa vir ..."); if (option == JoptionPane.ok_Option) {newGame (); } else if (option == joptionpane.no_option) {System.exit (0); }}} private void Down () {if (Crash (x, y+1, BlockType, Turnstate) == 0) {// Observe que Y+1 é usado aqui para determinar se a posição correspondente no mapa é um bloco ou quadro empilhado após o bloco que é lançado por um quadrado; // salvar a informação do bloco atual para o mapa a seguir (); } else {y ++; } repaint (); } private void left () {if (x> = 0) {x -= crash (x -1, y, blocktype, turnTate); } repaint (); } private void Right () {if (x <8) {x += crave (x +1, y, blocktype, turnTate); } repaint (); } private void Turn () {if (Crash (x, y, blocktype, (Turnstate+1)%4) == 1) {Turnstate = (TurnsTate+1)%4; } repaint (); } 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 ){ map[x+b+1][y+a] = 1; }}} trydelline (); } // elimine o void privado TryDelline () {for (int b = 0; b <21; b ++) {int c = 1; para (int a = 0; a <12; a ++) {c & = map [a] [b]; // todos são 1, o resultado de c é 1} se (c == 1) {// existe uma linha que precisa ser eliminada // mover uma linha para baixo na sequência (int d = b; d> 0; d-) {para (int e = 0; mapa [e] [d-1]; }} // Adicione a pontuação de pontos += 100; atraso /=1.05; timer.setDelay (atraso); } } } // Parameter example: 4,3,2,3 //Judge whether there is a collision private int crash(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 && mapa [x+b+1] [y+a] == 1) || // (Shapes [blocktype] [Turnstate] [a*4+b] == 1 && map [x+b+1] [y+a] == 3)) {//} if ((shapes [blocktype] [turnTate] [a*4 4 0; // colisão}}} retornar 1; // sem colisão} @Override public void Paint (gráficos g) {// blocktype = 6; // Turnstate = 3; // x = 4; // y = 6; Super.paint (g); // elimina o AfterImage G.setColor (nova cor (153,51,205)); // desenhe o bloco atual para (int j = 0; j <16; j ++) {if (Shapes [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 (nova cor (153,51,205)); }} // desenhe o quadro da interface e os blocos de pilha --- o mapa inteiro G.setColor (color.red); para (int i = 0; i <12; i ++) {// andando para (int j = 0; j <22; j ++) {// caminhando 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); }}} // mostra a pontuação e o layout é bonito, adicione algo à interface // desenhe a parte direita da área quadrada G.SetColor (color.red); G.SetFont (New Font ("AA", Font.Bold, 11)); G.DrawString ("Score =" + Score, 130, 20); g.setFont (nova fonte ("aa", font.plain, 13)); g.setColor (color.blue); G.DrawString ("Rejeitar Jogos Pirateados", 125, 70); G.DrawString ("Tenha cuidado com a autoproteção"., 125, 90); G.DrawString ("Cuidado com o fato de ser enganado"., 125, 110); G.DrawString ("O jogo moderado é bom para o cérebro", 125, 130); G.DrawString ("Adicionar ao jogo é prejudicial ao corpo"., 125, 150); G.DrawString ("horário do cronograma razoavelmente", 125, 170); G.DrawString ("Desfrute de uma vida saudável"., 125, 190); } classe TimerKeyLister estende KeyAdapter implementa ActionListener {@Override public void ActionPerformed (ActionEvent E) {Down (); } @Override public void KeyPressed (keyEvent e) {switch (e.getKeyCode ()) {case keyEvent.vk_down: Down (); quebrar; case keyevent.vk_left: left (); quebra; case keyevent.vk_right: right (); quebra; case keyevent.vk_up: Turn (); quebra; case keyevent.vk_f1: plug (); case keyevent.vk_f2: time (); }} public void plug () {score+= 100; } public void time () {telto = 1000; timer.setDelay (atraso); }}}Interface em execução:
Para jogos mais emocionantes, consulte o tópico especial "Java Classic Games"
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.