Este artigo descreve o jogo de varredura de minas e a versão aprimorada implementada pelo Java Swing. Compartilhe -o para sua referência, como segue:
Versão 1:
pacote awtdemo; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.awt.event.mouseEvent; import java.awt.event.mouselistener; import javax.swing.jbutton; import..event.jfame; Exemplo de varredura de minas, escrito por swing, adequado para iniciantes praticar* Este programa usa setbounds (x, y, w, h) para layout o método de controle* refere-se à varredura de mina embutida no Win XP. Obviamente, a função de escrita não foi feita, * algumas das funções feitas têm bugs * * @author ping_qc */public class Test estende JFrame implementa ActionListener, Runnable, MouseListener {private estático final serialversionUid = -241775839796509613l; final privado int vazio = 0; mina int particular privada = 1; private final int verificado = 2; Final privado int mine_count = 10; // o número de Thunder Private final int button_border = 50; // tamanho de cada ponto final privado int mine_size = 10; // Especificação de interface, 20x20 private final int start_x = 20; // Posição inicial x private final int start_y = 50; // Start Position Y Sinalizador booleano privado; private jbutton [] [] JB; Private Jlabel JL; Showtime privado de Jlabel; private int [] [] mapa; /*** Detecte se há um raio em torno de um ponto. As coordenadas dos pontos circundantes podem ser calculadas a partir desta matriz*/ private int [] [] mv = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {{--1}}; / *** gera aleatoriamente um número definido de trovão*/ public void makemine () {int i = 0, tx, ty; para (; i <mine_count;) {tx = (int) (math.random () * mine_size); ty = (int) (math.random () * mine_size); if (map [tx] [ty] == vazio) {map [tx] [ty] = mine; i ++; // Não lembre -se do raio repetido}}}}/ *** Coloque a matriz de botões no quadro e corresponda ao mapa [] [] Array*/ public void makeButton () {for (int i = 0; i <mine_size; i ++) {para (int j = 0; j <mine_size; j ++); // if (map [i] [j] == mine) // jb [i] [j] .settext (i+","+j); // ouvinte Adicionar jb [i] [j] .addactionListener (this); jb [i] [j] .addmouselistener (isto); jb [i] [j] .setName (i + "_" + j); // clicar conveniente é determinar qual botão foi clicado // font font = new font (font.serif, font.bold, 10); // jb [i] [j] .setFont (font); // jb [i] [j] .settext (i+","+j); jb [i] [j] .setbounds (j * button_border + start_x, i * button_border + start_y, button_border, button_border); this.add (jb [i] [j]); }}} public void init () {flag = false; jl.settext ("Bem -vindo ao teste, há um total de" + mine_count + "Thunder"); jl.setVisible (true); jl.setbounds (20, 20, 500, 30); this.add (jl); ShowTime.Settext ("Declantado: 0 segundos"); ShowTime.setBounds (400, 20, 100, 30); this.add (Showtime); makemine (); makeButton (); this.SetSize (550, 600); this.setLocation (700, 100); this.setResizable (false); this.setDefaultCloseoperation (exit_on_close); this.setVisible (true); } teste público (título da string) {super (title); this.setLayout (nulo); // Não está usando o gerenciador de layout, defina a posição de cada controle com setBounds JB = new JButton [mine_size] [mine_size]; jl = new jlabel (); ShowTime = new Jlabel (); map = new int [mine_size] [mine_size]; // mapeie os botões em uma matriz} public static void main (string [] args) {teste test = new test ("wulin.com-mine swarding game Test 1"); test.init (); test.run (); } @Override public void ActionPerformed (ActionEvent e) {objeto obj = e.getSource (); int x, y; if ((obj instanceof jbutton) == false) {showMessage ("erro", "erro interno"); retornar; } String [] tmp_str = ((jbutton) obj) .getName (). Split ("_"); x = Integer.parseint (tmp_str [0]); y = integer.parseint (tmp_str [1]); if (mapa [x] [y] == mine) {showMessage ("Death", "você pisou em uma mina ~~~"); bandeira = true; showmine (); retornar; } dfs (x, y, 0); checksuccess (); } / ** * Após cada clique, determine se todos os LightNings foram encontrados calculando o número de botões com status ativado * / verificação de vazio privado () {int cnt = 0; para (int i = 0; i <mine_size; i ++) {for (int j = 0; j <mine_size; j ++) {if (jb [i] [j] .iSenabled ()) {cnt ++; }}} if (cnt == mine_count) {string tmp_str = ShowTime.getText (); tmp_str = tmp_str.replaceall ("[^0-9]", ""); ShowMessage ("Victory", "Quando esse lavador de minas é compartilhado:" + tmp_str + "segundos"); bandeira = true; showmine (); }} private int dfs (int x, int y, int d) {map [x] [y] = verificado; int i, tx, ty, cnt = 0; for (i = 0; i <8; i ++) {tx = x+mv [i] [0]; ty = y + mv [i] [1]; if (tx> = 0 && tx <mine_size && ty> = 0 && ty <mine_size) {if (map [tx] [ty] == mine) {cnt ++; // estatísticas do número do trovão próximo a este ponto} se (map [tx] [ty] == vazio) {;; } else if (map [tx] [ty] == verificado) {; }}} if (cnt == 0) {for (i = 0; i <8; i ++) {tx = x+mv [i] [0]; ty = y + mv [i] [1]; if (tx> = 0 && tx <mine_size && ty> = 0 && ty <mine_size && map [tx] [ty]! = verificado) {dfs (tx, ty, d + 1); }}} else {jb [x] [y] .settext (cnt + ""); } jb [x] [y] .setEnabled (false); devolver cnt; } / ** * Mostre algumas informações sobre a tag jl * * @param título * @param info * / private void showMessage (título da string, string info) {jl.settext (info); System.out.println ("In Functino ShowMessage ():" + Info); } public void run () {int t = 0; while (true) {if (flag) {break; } tente {thread.sleep (1000); } catch (interruptedException e) {e.printStackTrace (); } t ++; ShowTime.Settext ("Declantado:" + T + "segundos"); } // showMine (); } private void showMine () {// icon iconmine = new imageicon ("e: /mine.jpg"); para (int i = 0; i <mine_size; i ++) {for (int j = 0; j <mine_size; j ++) {if (map [i] [j] == mine) {jb [i] [j] .settext ("#"); // jb [i] [j] .SeTOn (icoMine); }}}} @Override public void mouseclicked (mouseevent e) {if (e.getButton () == 3) {objeto obj = e.getSource (); if ((obj instanceof jbutton) == false) {showMessage ("erro", "erro interno"); retornar; } String [] tmp_str = ((jbutton) obj) .getName (). Split ("_"); int x = inteiro.parseint (tmp_str [0]); int y = Integer.parseint (tmp_str [1]); if ("{1}". Equals (jb [x] [y] .getText ()))) {jb [x] [y] .settext (""); } else {jb [x] [y] .settext ("{1}"); } /* if (jb [x] [y] .geticon () == null) {jb [x] [y] .seticon (new imageicon ("e: /flag.jpg")); } else {jb [x] [y] .seticon (null); }*/ } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseexited (mouseevent e) {// TODO Method Stub}}} stub}Efeito de corrida:
A versão 2 é uma melhoria para o programa da versão 1 acima, e a função de marcação do clique com o botão direito do mouse e a função de dificuldade de seleção independente é adicionada com base na base inalterada.
pacote awtdemo; importar java.awt.event.actionEvent; importar java.awt.event.actionListener; importar java.awt.event.mouseEvent; importar java.awt.event.mouselistener; importação javax.jbutton; importação javax.swing.jfame; javax.swing.jlabel; @suppresswarnings ("serial") a classe pública Saolei estende o jframe implementa ActionListener, runnable, mouselistener {private final int loepty = 0; private final int lomine = 1; private final int lOCHECKED = 2; private final int lomine_count = 10; private final int lobutton_border = 50; private final int lomine_size = 10; Final privado AT LOSTART_X = 20; Final privado AT LOSTART_Y = 50; bandeira booleana privada; private jbutton [] [] JB; Private Jlabel JL; Showtime privado de Jlabel; private int [] [] mapa; private int [] [] mv = {{-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1}}; public void makelomine () {int i = 0, tx, ty; para (; i <lomine_count;) {tx = (int) (math.random () * lomine_size); ty = (int) (math.random () * lomine_size); if (map [tx] [ty] == LoeMpty) {map [tx] [ty] = lomine; i ++; }}} public void makeButton () {for (int i = 0; i <lomine_size; i ++) {for (int j = 0; j <lomine_size; j ++) {jb [i] [j] = novo jbutton (); jb [i] [j] .AddactionListener (isto); jb [i] [j] .addmouselistener (isto); jb [i] [j] .setName (i + "_" + j); jb [i] [j] .Setbounds (j * lobutton_border + perdet_x, i * lobutton_border + perdet_y, lobutton_border, lobutton_border); this.add (jb [i] [j]); }}} public void init () {flag = false; jl.settext ("Teste bem -vindo, há um total de" + lomine_count + "Thunder"); jl.setVisible (true); jl.setbounds (20, 20, 500, 30); this.add (jl); ShowTime.Settext ("Declantado: 0 segundos"); ShowTime.setBounds (400, 20, 100, 30); this.add (Showtime); makelomine (); makeButton (); this.SetSize (550, 600); this.setLocation (700, 100); this.setResizable (false); this.setDefaultCloseoperation (exit_on_close); this.setVisible (true); } public saolei (título da string) {super (título); this.setLayout (nulo); // Nenhum gerente de layout é usado, Setbounds para a posição de cada controle jb = new jbutton [lomine_size] [lomine_size]; jl = new jlabel (); ShowTime = new Jlabel (); map = new int [lomine_size] [lomine_size]; // mapeie os botões em uma matriz} public static void main (string [] args) {saolei test = new saolei ("wulin.com-mine swarding game Test 2"); test.init (); test.run (); } @Override public void ActionPerformed (ActionEvent e) {objeto obj = e.getSource (); int x, y; if ((obj instanceof jbutton) == false) {showMessage ("erro", "erro interno"); retornar; } String [] tmp_str = ((jbutton) obj) .getName (). Split ("_"); x = Integer.parseint (tmp_str [0]); y = integer.parseint (tmp_str [1]); if (map [x] [y] == lomine) {showMessage ("Death", "você pisou em uma mina ~~~"); bandeira = true; showlomine (); retornar; } dfs (x, y, 0); checksuccess (); } private void checksuccess () {int cnt = 0; for (int i = 0; i <lomine_size; i ++) {for (int j = 0; j <lomine_size; j ++) {if (jb [i] [j] .iSenabled ()) {cnt ++; }}} if (cnt == lomine_count) {string tmp_str = ShowTime.getText (); tmp_str = tmp_str.replaceall ("[^0-9]", ""); ShowMessage ("Victory", "Quando esse lavador de minas é compartilhado:" + tmp_str + "segundos"); bandeira = true; showlomine (); }} private int dfs (int x, int y, int d) {map [x] [y] = lochecked; int i, tx, ty, cnt = 0; for (i = 0; i <8; i ++) {tx = x+mv [i] [0]; ty = y + mv [i] [1]; if (tx> = 0 && tx <lomine_size && ty> = 0 && ty <lomine_size) {if (map [tx] [ty] == lomine) {cnt ++; } else if (map [tx] [ty] == LoeSpty) {; } else if (map [tx] [ty] == LOCHECKED) {; }}} if (cnt == 0) {for (i = 0; i <8; i ++) {tx = x+mv [i] [0]; ty = y + mv [i] [1]; if (tx> = 0 && tx <lomine_size && ty> = 0 && ty <lomine_size && map [tx] [ty]! }}} else {jb [x] [y] .settext (cnt + ""); } jb [x] [y] .setEnabled (false); devolver cnt; } private void showMessage (título da string, String info) {jl.settext (info); System.out.println ("In Functino ShowMessage ():" + Info); } public void run () {int t = 0; while (true) {if (flag) {break; } tente {thread.sleep (1000); } catch (interruptedException e) {e.printStackTrace (); } t ++; ShowTime.settext ("Tempo decorrido:" + t + "segundos"); }} private void showlomine () {for (int i = 0; i <lomine_size; i ++) {for (int j = 0; j <lomine_size; j ++) {if (map [i] [j] == lomine) {jb [i] [j] .Settext ("Thunder); }}}} public void mouseclicked (mouseevent e) {if (e.getButton () == 3) {objeto obj = e.getSource (); if ((obj instanceof jbutton) == false) {showMessage ("erro", "erro interno"); retornar; } String [] tmp_str = ((jbutton) obj) .getName (). Split ("_"); int x = inteiro.parseint (tmp_str [0]); int y = Integer.parseint (tmp_str [1]); if ("{1} quot" .equals (jb [x] [y] .getText ())) {jb [x] [y] .settext (""); } else {jb [x] [y] .settext ("{1} quot"); }}} public void mousePressed (mouseevent e) {} @Override public void MouseReleased (mouseevent e) {} public void mouseEntered (mouseevent e) {} @Override public void mouseexited (mousevent e) {}}Efeito de corrida:
Para obter mais informações sobre os algoritmos Java, os leitores interessados neste site podem visualizar os tópicos: "Estrutura de dados Java e tutorial de algoritmo", "Resumo das dicas de nó da operação Java Dom", "Resumo de dicas de operação de Java e Operação de Java" e "Resumo de Java cache" Tips "TIPS"
Espero que este artigo seja útil para a programação Java de todos.