In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the methods and steps of realizing Gobang game with Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "using Java to achieve Gobang game methods and steps" bar!
1. The creation of graphical interface
1.1 create a JFrame forms container
1) JFrame forms need to set the basic size, layout, default closing method, and the most important settings visible.
Add components to JFrame to draw chessboard pieces and game operations.
1) drawing of chessboard pieces: customize a class to inherit JPanel, and rewrite the method of drawing chessboard and pieces into the paint () method, so that when the form changes (zoom in, zoom out, move, etc., the chessboard pieces will not disappear and the game can be saved).
2) the operations such as repentance and admitting defeat are realized by adding mouse monitoring to the JButton button.
two。 Realization of key points
Use six classes to implement the logic behind, UI class, DrawChessBoard class, GameMouse class, QiZi class, Location class, and AI class.
2.1 draw pieces where the chessboard clicks
1) add mouse monitoring to the chessboard to obtain the coordinates of the click location
The UI class is responsible for initializing the graphical interface in 1 and adding listeners for the GameMouse class to the DrawChessBoard class. In this way, when the mouse clicks on the chessboard, you can obtain the pixel coordinates of the mouse clicked on the chessboard by rewriting the mouseClicked () of the GameMouse class.
2) convert the coordinates into the coordinates in the two-digit array
Save the position of all the pieces on the chessboard using the int [] memory two-dimensional array in the QiZi class, so that the pixel coordinates are converted into the coordinates in the two-dimensional array, and the corresponding values of the color of the pieces are attached, so that the positions of all pieces on the board can be saved.
3) draw pieces on the chessboard
In the DrawChessBoard class paint () method, traversing the non-zero value of the int [] [] memory two-dimensional array in the QiZi class, you can call the brush method at the appropriate location to draw the black and white chess pieces.
2.2 judge whether to win or lose
1) after the chess pieces are played, the chess position is saved to the int [] [] memory two-dimensional array of the QiZi class, and the number of consecutive pieces in four directions can be calculated around this point. If the number reaches five, the winner can be determined by generating the pop-up window of the JOptionPane class.
2.2 the realization of the function of repentance and the function of prompting the position of the last child.
1) each time you successfully play a chess piece, you can create a Location object that stores the pawn coordinates, and add the object to the ArrayList or Stack container of the QiZi class. When the mouse clicks on the Button, clear the value of the corresponding position in the int [] [] memory two-dimensional array of the QiZi class (change it to 0), and then redraw the pawn on the chessboard to complete the repentance effect.
2) at the same time, you can find the position of the last falling child in the container, and draw the last falling child prompt in the corresponding coordinates of the chessboard.
2.3 realization of starting and admitting defeat
1) start the game, that is, reset the game, and clear the corresponding attributes of the chess pieces, such as int [] [] memory two-dimensional array (that is, chess spectrum), owener=1 (reset to white), and clear the pieces on the board.
2) if you admit defeat, you can judge the value of the current QiZi.owner, judge the loser and give a hint.
The realization of 2.4AI
1) if the default AI is black, you need to call AI to play black chess pieces after the white square, so call the AI method in the if branch that needs to play white chess in GameMouse.
2) whether AI is strong or not depends on its design, here provides an idea: set up a chess type comparison table, assign values to different chess types (such as 1111, on behalf of Baizi four-company, high weight), when it comes to AI, you can calculate the overall weight of each vacant position on the chessboard in eight directions according to this table, and drop the pieces in the maximum weight. The weight setting of different chess in the chess type comparison table can be obtained by analyzing a large number of chess games such as python, so as to train AI. The more reasonable the weight setting is, the stronger the AI will be.
3. Other featur
The animation effects and sound effects can be realized by opening up different threads, while the network war can add network communication related modules.
4. Source code package wuziqi925; import javax.swing.*;import java.awt.*; public class GameUI {public static void main (String [] args) {GameUI gameUI=new GameUI (); gameUI.showUI ();} public void showUI () {/ / create chess sub-object QiZi qizi=new QiZi (); / / get form JFrame jFrame=new JFrame (); jFrame.setSize (1000795); jFrame.setDefaultCloseOperation (3) JFrame.setLocationRelativeTo (null); jFrame.setLayout (null); jFrame.setTitle (Gobang); jFrame.setResizable (false); / / form add chessboard panel DrawChessBoard chessBoard=new DrawChessBoard (qizi); jFrame.add (chessBoard); chessBoard.setSize (760760); chessBoard.setBackground (Color.ORANGE) / / Test JFrame frame pixel size, Insets [top=32,left=3,bottom=3,right=3] / / System.out.println (jFrame.getInsets ()); / / form add option panel for drawing chessboard JPanel bp=new JPanel (); bp.setSize (236760); bp.setBackground (Color.lightGray); bp.setLocation (760); bp.setLayout (null) JFrame.add (bp); / / add buttons to the option panel: JButton start=new JButton ("start"); start.setBackground (Color.white); start.setFont (new Font ("Chinese script", Font.BOLD,20); start.setBounds (40wager350,150,150); JButton quit=new JButton ("give up"); quit.setBackground (Color.white) Quit.setFont (new Font (Chinese Xingkai, Font.BOLD,20); quit.setBounds (40pr 440, 150pc50); JButton undo=new JButton (repentant chess); undo.setBackground (Color.white); undo.setFont (new Font (Hsinkai, Font.BOLD,20)); undo.setBounds (40pr 530pr 15050); bp.add (start); bp.add (quit) Bp.add (undo); / / Select mode options ButtonGroup bg=new ButtonGroup (); JRadioButton rrdz=new JRadioButton ("player versus Battle"); JRadioButton rjdz=new JRadioButton ("Man-Machine Battle"); rrdz.setSize (120mem30); rrdz.setLocation (55jue 60); rrdz.setFont (new Font ("Chinese Xingkai", Font.BOLD,20); rrdz.setVisible (true) Rjdz.setSize (120mem30); rjdz.setLocation (55mem90); rjdz.setFont (new Font (Font.BOLD,20)); rjdz.setVisible (true); bg.add (rjdz); bg.add (rrdz); bp.add (rjdz); bp.add (rrdz); bp.setVisible (true) / / set form visible jFrame.setVisible (true); AI ai=new AI (qizi,chessBoard); / / get the mouse monitor and brush of the chessboard and add the brush to the mouse Graphics g1=chessBoard.getGraphics (); GameMouse gameMouse=new GameMouse (qizi,chessBoard,ai); chessBoard.addMouseListener (gameMouse); start.addActionListener (gameMouse); quit.addActionListener (gameMouse) Undo.addActionListener (gameMouse); rrdz.addActionListener (gameMouse); rjdz.addActionListener (gameMouse);} package wuziqi925; import javax.swing.*;import java.awt.*; public class DrawChessBoard extends JPanel {QiZi qiZi; private static int LINE_NUM = 15; private static int MARGIN_WIDTH = 30; public static int CELL_SIZE = 50; public DrawChessBoard (QiZi qiZi) {this.qiZi = qiZi } @ Override public void paint (Graphics g) {super.paint (g); / / draw chessboard for (int I = 0; I
< LINE_NUM; i++) { g.drawLine(MARGIN_WIDTH, MARGIN_WIDTH + i * CELL_SIZE, MARGIN_WIDTH + (LINE_NUM - 1) * CELL_SIZE, MARGIN_WIDTH + i * CELL_SIZE); g.drawLine(MARGIN_WIDTH + i * CELL_SIZE, MARGIN_WIDTH, MARGIN_WIDTH + i * CELL_SIZE, MARGIN_WIDTH + (LINE_NUM - 1) * CELL_SIZE); } //画棋盘上的点 g.fillOval(CELL_SIZE*3+22,CELL_SIZE*3+22,16,16); g.fillOval(CELL_SIZE*11+22,CELL_SIZE*3+22,16,16); g.fillOval(CELL_SIZE*3+22,CELL_SIZE*11+22,16,16); g.fillOval(CELL_SIZE*11+22,CELL_SIZE*11+22,16,16); //画棋子 int[][] a = qiZi.memory; for (int i = 0; i < a.length; i++) { for (int j = 0; j < a[i].length; j++) { if (a[i][j] == 1) { g.setColor(Color.white); g.fillOval(CELL_SIZE * i + 7, CELL_SIZE * j + 7, 46, 46); } else if (a[i][j] == 2) { g.setColor(Color.black); g.fillOval(CELL_SIZE * i + 7, CELL_SIZE * j + 7, 46, 46); } } } //画出最后一步棋子的位置上的十字架 if (qiZi.arr.size() >0) {Graphics2D G1 = (Graphics2D) g; g1.setColor (Color.red); g1.setStroke (new BasicStroke (3.0f)); Location l = qiZi.arr.get (qiZi.arr.size ()-1) G1.drawLine (CELL_SIZE * l.x + MARGIN_WIDTH-8, CELL_SIZE * l.y + MARGIN_WIDTH, CELL_SIZE * l.x + MARGIN_WIDTH + 8, CELL_SIZE * l.y + MARGIN_WIDTH); g1.drawLine (CELL_SIZE * l.x + MARGIN_WIDTH, CELL_SIZE * l.y + MARGIN_WIDTH-8, CELL_SIZE * l.x + MARGIN_WIDTH, CELL_SIZE * l.y + MARGIN_WIDTH + 8) } package wuziqi925; import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener; public class GameMouse implements MouseListener, ActionListener {QiZi qizi; DrawChessBoard drawChessBoard; AI ai; public GameMouse () {} public GameMouse (QiZi qiZi, DrawChessBoard drawChessBoard,AI ai) {this.qizi = qiZi; this.drawChessBoard=drawChessBoard This.ai=ai;} @ Override public void mouseClicked (MouseEvent e) {int cellSize= DrawChessBoard.CELL_SIZE; int x=e.getX (); int xx=0; int y=e.getY (); int yy=0 / / draw the pieces in the click position and convert the position of the following pieces to the coordinates if (qizi.owner==1) {if ((x-30)% cellSize > 25 & (y-30)% cellSize > 25) {xx= (x-30) / cellSize + 1; yy= (y-30) / cellSize + 1 } else if ((x-30)% cellSize > 25 & (y-30)% cellSize
< 25) { xx=(x - 30) / cellSize + 1; yy=(y - 30) / cellSize; } else if ((x - 30) % cellSize < 25 & (y - 30) % cellSize >25) {xx= (x-30) / cellSize; yy= (y-30) / cellSize + 1;} else if ((x-30)% cellSize
< 25 & (y - 30) % cellSize < 25) { xx=(x - 30) / cellSize; yy=(y - 30) / cellSize; } if(qizi.memory[xx][yy]==0) {//判断无子 qizi.x=xx; qizi.y=yy; qizi.memory[qizi.x][qizi.y] = qizi.owner;//下棋子并将棋子放入容器 Location location=new Location(qizi);//记录刚下的棋子位置顺序 qizi.arr.add(location); drawChessBoard.repaint();//绘制刚下的棋子 qizi.judgeWinner();//判断输赢 qizi.owner=2;//交换棋权 } if (ai.state){ ai.initiateAI(); } }else { qizi.owner=2; if ((x - 30) % cellSize >25 & (y-30)% cellSize > 25) {xx= (x-30) / cellSize + 1; yy= (y-30) / cellSize + 1;} else if ((x-30)% cellSize > 25 & (y-30)% cellSize
< 25) { xx=(x - 30) / cellSize + 1; yy=(y - 30) / cellSize; } else if ((x - 30) % cellSize < 25 & (y - 30) % cellSize >25) {xx= (x-30) / cellSize; yy= (y-30) / cellSize + 1;} else if ((x-30)% cellSize
< 25 & (y - 30) % cellSize < 25) { xx=(x - 30) / cellSize; yy=(y - 30) / cellSize; } if(qizi.memory[xx][yy]==0) { qizi.x=xx; qizi.y=yy; qizi.memory[qizi.x][qizi.y] = qizi.owner;//下棋子并将棋子放入容器 Location location=new Location(qizi);//记录刚下的棋子位置顺序 qizi.arr.add(location); drawChessBoard.repaint();//绘制刚下的棋子 qizi.judgeWinner();//判断输赢 qizi.owner=1;//交换棋权 } } } @Override public void actionPerformed(ActionEvent e) { int cellSize= DrawChessBoard.CELL_SIZE; String s=e.getActionCommand(); JOptionPane tc=new JOptionPane(); //悔棋功能的实现 if (s.equals("悔棋")){ if (qizi.arr.size()>0) {Location l = qizi.arr.get (qizi.arr.size ()-1); qizi.memory [l.x] [l.y] = 0; qizi.arr.remove (qizi.arr.size ()-1); if (qizi.owner = = 1) {qizi.owner = 2 } else if (qizi.owner = = 2) {qizi.owner = 1;}} else {tc.showMessageDialog (null, "No chess can be destroyed, please play chess!") ;} / / refresh the chessboard drawChessBoard.repaint ();} if (s.equals (start)) {qizi.owner=1; qizi.memory=new int [15] [15]; qizi.arr.clear (); qizi.win=false; drawChessBoard.repaint () } if (s.equals ("give up")) {int whiteCount=0; int blackCount=0; for (int I = 0; I)
< qizi.memory.length; i++) { for (int j = 0; j < qizi.memory[i].length; j++) { if (qizi.memory[i][j]==1){ whiteCount++; }else if (qizi.memory[i][j]==2){ blackCount++; } } } if (whiteCount==blackCount){ tc.showMessageDialog(null,qizi.owner==1 ?"黑方投降,白方胜!":"白方投降,黑方胜!"); }else if(whiteCount>BlackCount) {tc.showMessageDialog (null, "Black surrenders, White wins!") ;} else {tc.showMessageDialog (null, "White surrenders, black wins!") ;} if (s.equals) {ai.state=true;} if (s.equals) {ai.state=false } @ Override public void mousePressed (MouseEvent e) {} @ Override public void mouseReleased (MouseEvent e) {} @ Override public void mouseEntered (MouseEvent e) {} @ Override public void mouseExited (MouseEvent e) {}} package wuziqi925; import javax.swing.*;import java.util.ArrayList; public class QiZi {int x; int y; int owner=1 / 1 for white, 2 for black int [] [] memory; ArrayList arr; boolean win=false; public QiZi () {memory=new int [15] [15]; arr=new ArrayList (50);} public void judgeWinner () {JOptionPane tc=new JOptionPane (); int count1=0; int count2=0; int count3=0; int count4=0 / / Vertical direction detection for (int I = ymurl; I >-1; iMel -) {if (memory [x] [I] = = owner) {count1++;} else {break;}} for (int I = yellow1; I 3) {tc.showMessageDialog (null,owner==1? " Bai Fangsheng ":" Black side wins "); win=true; return;} / / horizontal direction detection for (int I = Xmurl; I >-1; iMub -) {if (memory [I] [y] = = owner) {count2++;} else {break }} for (int I = xylene 1; I 3) {tc.showMessageDialog (null,owner==1? " Bai Fangsheng ":" Black side wins "); win=true; return;} / / detect int yy=y; for in\ direction (int I = Xero1; i1; iMube -) {if (yy==0) {break;} yy-- If (memory [I] [yy] = = owner) {count3++;} else {break;}} if (count3 > 3) {tc.showMessageDialog (null,owner==1? " Bai Fangsheng ":" Black side wins "); win=true; return;} / / detect yy=y; for in / direction (int I = xylene; i1; iMube -) {if (yy==14) {break;} yy++ If (memory [I] [yy] = = owner) {count4++;} else {break;}} if (count4 > 3) {tc.showMessageDialog (null,owner==1? " Bai Fangsheng ":" black side wins "); win=true; return;} package wuziqi925; public class Location {QiZi qiZi; int x; int y; public Location (QiZi qiZi) {/ / record chess score xqiqiZi.x; yqiqiZi.y;} public Location (int x, int y) {this.x = x; this.y = y }} package wuziqi925; import java.util.*; public class AI {boolean state=false;//true is on false, off QiZi qiZi; is off QiZi qiZi; / / store chess weight private HashMap playValueTable=new HashMap (); / / store the weight of each lower point private HashMap locationsAndValues=new HashMap (); DrawChessBoard drawChessBoard; int AIDO=0; public AI (QiZi qiZi,DrawChessBoard drawChessBoard) {this.drawChessBoard=drawChessBoard; this.qiZi=qiZi / 1 represents white square pieces (players), 2 represents black square pieces (AI) playValueTable.put ("22221", 100); playValueTable.put ("2222", 100); playValueTable.put ("11112", 99); playValueTable.put ("1111", 0); playValueTable.put ("2221", 40); playValueTable.put ("2221", 45) PlayValueTable.put ("1112", 35); playValueTable.put ("1111,46); playValueTable.put (" 221,25 "); playValueTable.put (" 2211,20); playValueTable.put ("111,15"); playValueTable.put ("112,10"); playValueTable.put ("21", 5); playValueTable.put ("2", 10) PlayValueTable.put ("1", 8); playValueTable.put ("12", 2);} public void initiateAI () {if (qiZi.win) {return;} int chessValue=0; / / traversing the chessboard to find the space for (int I = 0; I-1) -) {if (qiZi.memory [I] [k] = = 1) {s1.append (1);} else if (qiZi.memory [I] [k] = = 2) {s1.append (2);} else {break }} int count1=playValueTable.get (s1.toString ()) = = null?0:playValueTable.get (s1.toString ()); totalValue+=count1; / / South for (int k = juni1; k-1; Kmuri -) {if (qiZi.memory [k] [j] = = 1) {s3.append (1) } else if (qiZi.memory [k] [j] = = 2) {s3.append (2);} else {break;}} int count3=playValueTable.get (s3.toString ()) = = null?0:playValueTable.get (s3.toString ()); totalValue+=count3; / / East for (int k = iTunes 1; k-1) QiZi.memory -) {if (yy==0) {break;} yy--; if (qiZi.memory [k] [yy] = = 1) {s6.append (1);} else if (qiZi.memory [k] [yy] = = 2) {s6.append (2) } else {break;}} int count6=playValueTable.get (s6.toString ()) = = null?0:playValueTable.get (s6.toString ()); totalValue+=count6; / / NE yy=j; for (int k = iTun1; k-1; Kmuri -) {if (yy==14) {break } yy++; if (qiZi.memory [k] [yy] = = 1) {s8.append (1);} else if (qiZi.memory [k] [yy] = = 2) {s8.append (2);} else {break }} int count8=playValueTable.get (s8.toString ()) = = null?0:playValueTable.get (s8.toString ()); totalValue+=count8; return totalValue;}} so far, I believe you have a deeper understanding of "the methods and steps of realizing Gobang games with Java". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.