Примеры в этой статье делятся с вами конкретным кодом игры Java Mine Sweeping для вашей ссылки. Конкретный контент заключается в следующем
Импорт java.awt.borderlayout; import java.awt.color; import java.awt.container; import java.awt.gridlayout; импорт java.awt.insets; импорт java.awt.label; import java.awt.event.actionevent; import java.awt.avent. java.awt.event.itemevent; import java.awt.event.itemlistener; импорт java.awt.event.mouseevent; импорт java.awt.event.mouselistener; импорт java.util.random; Импорт javax.swing.jbutton; импортировать javax.swing.jcombobox; импорт javax.swing.jframe; импорт javax.swing.joptionpane; импорт javax.swing.jpanel; открытый класс Saalei реализует Mouselestener, ActionListener {jPanel p = new jPanel (); Jframe frame = new jframe ("Mine-weeping"); @Suppresswarnings ("rawtypes") jcombobox combobox = new jcombobox (); Jbutton reset = new jbutton ("перезапуск"); Контейнер -контейнер = новый контейнер (); // Структура игровых данных Saoleiconstant constant = new Saoleiconstant (); Jbutton [] [] buttons = new jbutton [constant.row] [constant.col]; // определить кнопку int [] [] counts = new int [constant.row] [constant.col]; // определить целовый массив сохранение номера ниже кнопки // create constructor public saolei () {// show window framesize (600,700); Frame.SetReSizable (false); frame.setDefaultCloseoPeration (jframe.exit_on_close); frame.setlayout (new Borderlayout ()); // Добавить повтор и выберите кнопку сложности addTopButton (); // Добавить кнопку минного поля addbuttons (); // коричневый шахт addlei (); // Добавить молнией count calcneibolei (); Frame.SetVisible (true); } void addTopButton () {p.Removeall (); P.Add (сброс); reset.setbackground (color.green); reset.setopaque (true); reset.addactionListener (это); //combobox.additem("select сложно »); combobox.additem ("сложность новичка"); combobox.additem («основная сложность»); combobox.additem («промежуточная сложность»); combobox.additem ("передовая сложность"); combobox.additem ("Master Swardulty"); combobox.setbackground (color.green); combobox.setopaque (true); combobox.additemlistener (new itemListener () {@Override public void itemStateChanged (itemEvent e) {string item = e.getItem (). toString (); if (item == "newbie сложно") {constant.leicount = 20; ResetGame ();} ense elementale ") {inourty. {inourtally {inourty. {inourtally. ResetGame (); P.Add (ComboBox); Frame.add (p, borderlayout.north); //p.add(new label («Общее количество потоков:»+constant.leicount, label.center)); //p.add(new label («Общее количество потоков:»+constant.leicount, label.right)); } /* void addNandubutton () {nandu.setbackground (color.green); nandu.setopaque (true); nandu.addactionListener (это); frame.add (nandu, borderlayout.west); } void addresetButton () {reset.setbackground (color.green); reset.setopaque (true); reset.addactionListener (это); //reset.addmouseListener( Это); Frame.add (сброс, borderlayout.north); } */ void addlei () {случайный rand = new Random (); Int Randrow, Randcol; for (int i = 0; i <constant.leicount; i ++) {randRow = rand.nextint (constant.row); randcol = rand.nextint (constant.col); if (counts [randrow] [randcol] == constant.leicode) {i--; } else {counts [randRow] [randcol] = constant.leicode; //buttons! }}} void addbuttons () {frame.add (intainer, borderlayout.center); container.setlayout (new Gridlayout (constant.row, constant.col)); for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {jbutton button = new jbutton (); button.setbackground (color.white); button.setopaque (true); Button.AddactionListener (это); Button.AddMouseListener ((MouseListener) это); кнопки [i] [j] = кнопка; intainer.add (кнопка); }}} void calcneibolei () {int count; for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {count = 0; if (counts [i] [j] == constant.leicode) продолжить; if (i> 0 && j> 0 && counts [i-1] [j-1] == constant.leicode) count ++; if (i> 0 && counts [i-1] [j] == constant.leicode) count ++; if (i> 0 && j <19 && counts [i-1] [j+1] == constant.leicode) count ++; if (j> 0 && counts [i] [j-1] == constant.leicode) count ++; if (j <19 && counts [i] [j+1] == constant.leicode) count ++; if (i <19 && counts [i] [j+1] == constant.leicode) count ++; if (i <19 && j> 0 && counts [i+1] [j-1] == constant.leicode) count ++; if (i <19 && counts [i+1] [j-1] == constant.leicode) count ++; if (i <19 && counts [i+1] [j] == constant.leicode) count ++; if (i <19 && j <19 && counts [i+1] [j+1] == constant.leicode) count ++; counts [i] [j] = count; кнопки [i] [j] .setmargin (новые вставки (0,0,0,0)); // пусть кнопка изменится с шаблоном на кнопке // кнопки [i] [j] .Settext (counts [i] [j] + ""); }}} @Override public void actionperformed (actionEvent e) {jbutton button = (jbutton) e.getSource (); if (button.equals (reset)) {resetgame (); // перезапустить игру} else {int count = 0; for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {if (button.equals (кнопки [i] [j])) {count = counts [i] [j]; if (count == constant.leicode) {losegame (); } else {opencell (i, j); checkwin (); } возвращаться; }}}}}}}}}}}} public void mouseclicked (mouseevent e) {jbutton button = (jbutton) e.getSource (); if (e.getbutton () == mouseevent.button3) {// судить правой щелчок мыши для (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {if (button.eckals (iffons [i] [j])) {if (i] [i]) {if (i] [i]) {if (i]) {if (i]) (i] [i]) (i] [i]) {if]. {//buttons=^^. кнопки [i] [j] .setmargin (новые вставки (0,0,0,0)); // пусть кнопки меняются с помощью шаблона на кнопках кнопок [i] [j] .settext ("?"); возвращаться; }}}}}}}}}} void resetGame () {for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {buttons [i] [j] .settext (""); кнопки [i] [j] .setEnabled (true); кнопки [i] [j] .setbackground (color.white); counts [i] [j] = 0; }} addlei (); Calcneibolei (); } void checkwin () {for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {if (кнопки [i] [j] .isenabled () == true && counts [i] [j]! = constant.leicode) return; }} Joptionpane.showmessageDialog (кадр, "Да, вы выиграли!"); } // Используйте рекурсивный метод для OpenCell (int i, int j) {if (кнопки [i] [j] .IseNabled () == false) return; кнопки [i] [j] .setbackground (color.etellow); кнопки [i] [j] .setopaque (true); кнопки [i] [j] .setEnabled (false); if (counts [i] [j] == 0) {if (i> 0 && j> 0 && counts [i-1] [j-1]! = constant.leicode) opencell (i-1, j-1); if (i> 0 && j <19 && counts [i-1] [j]! = constant.leicode) opencell (i-1, j); if (i> 0 && j <19 && counts [i-1] [j+1]! = constant.leicode) opencell (i-1, j+1); if (j> 0 && counts [i] [j-1]! = constant.leicode) opencell (i, j-1); if (j <19 && counts [i] [j+1]! = constant.leicode) opencell (i, j+1); if (i <19 && j> 0 && counts [i+1] [j-1]! = constant.leicode) opencell (i+1, j-1); if (i <19 && counts [i+1] [j]! = constant.leicode) opencell (i+1, j); if (i <19 && j <19 && counts [i+1] [j+1]! = constant.leicode) opencell (i+1, j+1); } else {кнопки [i] [j] .setmargin (новые вставки (0,0,0,0)); кнопки [i] [j] .settext (counts [i] [j] + ""); }} void losegame () {for (int i = 0; i <constant.row; i ++) {for (int j = 0; j <constant.col; j ++) {int count = counts [i] [j]; if (count == constant.leicode) {кнопки [i] [j] .setmargin (новые вставки (0,0,0,0)); кнопки [i] [j] .settext ("lei"); кнопки [i] [j] .setbackground (color.red); кнопки [i] [j] .setEnabled (false); } else {кнопки [i] [j] .setmargin (новые вставки (0,0,0,0)); кнопки [i] [j] .settext (count + ""); кнопки [i] [j] .setEnabled (false); }}} JoptionPane.showmessageDialog (кадр, «Ошибка, вы проиграли!»); } public static void main (string [] args) {new saalei (); } @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 Автогенерированный метод stub}}Постоянный класс
открытый класс saoleiconstant {final int row = 20; // количество строк 30 окончательных int col = 20; // Количество столбцов 30 окончательный int leicode = 10; // Определить число ниже гром, защищенного int temp = 20; Защищенный int leicount = temp; // количество грома 30}Диаграмма воспроизведения
Для более захватывающих игр, пожалуйста, обратитесь к специальной теме "Java Classic Games"
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.