This little game is the JAVA course design of my sister and I, and it is also the first JAVA project I have done. It is suitable for beginners. I hope it can help those children who are troubled by the JAVA course design~~~
1. The game needs to be implemented
1. Design the main frame and interface.
2. Use the ActionListener interface to realize the monitoring of button events.
3. Restart the implementation of the function.
4. Implementation of the chess function.
5. Implementation of exit function.
6. Definition of chess piece dots in the chessboard.
7. Use the MouseListener interface to implement event monitoring and implement all methods in the interface.
8. When the mouse moves to the intersection point on the board and there are no chess pieces on the point, it can become a small hand shape.
9. When clicking on the chessboard, use the if statement to determine whether the point is at the intersection, and use the foreach statement and getX() and getY() method in the chess class to traverse the position of each chess piece to determine whether the point has chess pieces.
10. When it is determined that you can put a sub at the clicked point, when drawing a piece, use the for loop to traverse every existing point and use the setColor of the Graphics class to set the color, and use the fillOval method of the Graphics class to set the shape size.
11. When drawing the chess piece, you must judge the winner and lose in time. Use the index and for loop to traverse the directions of the last chess piece. If there are chess pieces on the same straight line with a number of chess pieces greater than or equal to five, that is the one represented by the current chess piece.
12. When the winner is decided, the corresponding information can be popped up.
2. Functional code implementation
2.1 Enter the game
public static void main(String[] args) { StartChessJFrame f=new StartChessJFrame();//Create the main frame f.setVisible(true);//Show the main frame}2.2 Initialization, define some quantities to be used.
private ChessBoard chessBoard;//Fight panel private Panel toolbar;//Toolbar panel private Button startButton;//Set the start button private Button backButton;//Set the regret button private Button exitButton;//Set the exit button
2.3 Interface construction method (game framework)
public StartChessJFrame(){ setTitle("Standalone Goji");//Set the title chessBoard=new ChessBoard();//Initialize the panel object, create and add menu MyItemListener lis=new MyItemListener();//Initialize the button event listener internal class toolbar=new Panel();//Instance the toolbar bar startButton=new Button("Restart"); backButton=new Button("Reply"); exitButton=new Button("Exit");//Initialize toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));// Use FlowLayout to layout toolbar.add(backButton); toolbar.add(startButton); toolbar.add(exitButton);// Add three buttons to the tool panel startButton.addActionListener(lis); backButton.addActionListener(lis); exitButton.addActionListener(lis);//Register the three button events to listen to the event add(toolbar,BorderLayout.SOUTH);//Layout the tool panel to the south of the interface, that is, add(chessBoard);//Add the panel object to the form setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Set the interface close event pack();//Adaptive size}2.4 button implementation and monitoring (internal construction method)
MyItemListener lis=new MyItemListener();//Initialize the internal class of the button event listener toolbar=new Panel();//Instantiate the tool panel bar startButton=new Button("Restart"); backButton=new Button("Reply"); exitButton=new Button("Exit");//Initialize toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));//Layout the toolbar.add(backButton); toolbar.add(startButton); toolbar.add(exitButton);//Add three buttons to the tool panel startButton.addActionListener(lis); backButton.addActionListener(lis); exitButton.addActionListener(lis);//Register the three button events to listen for events2.5 Listening of button events
private class MyItemListener implements ActionListener{ public void actionPerformed(ActionEvent e) { Object obj=e.getSource();//Get the event source if(obj==startButton){ System.out.println("Start...");//Restart//JFiveFrame.this inner class references the external class chessBoard.restartGame(); }else if(obj==exitButton){ System.exit(0);//End the application}else if(obj==backButton){ System.out.println("Repent Chess...");//Repent ChessBoard.goback(); } } }2.6 Restart button function implementation
public void restartGame(){//Clear chess pieces for(int i=0;i<chessList.length;i++) chessList[i]=null; /*Restore game-related variable values*/ isBack=true; gameOver=false;//Whether the game ends chessCount=0;//The number of chess pieces on the current board is repaint(); }2.7 Function implementation of the chess button
public void goback(){ if(chessCount==0) return ; chessList[chessCount-1]=null; chessCount--; if(chessCount>0){ xIndex=chessList[chessCount-1].getX(); yIndex=chessList[chessCount-1].getY(); } isBack=!isBack; repaint(); }2.8 When the chessboard becomes larger or smaller as needed, the window should change accordingly.
//Dimension: Inside the rectangular ChessBoard class public Dimension getPreferredSize(){ return new Dimension(MARGIN*2+GRID_SPAN*COLS,MARGIN*2+GRID_SPAN*ROWS); } pack();//Adaptive size Inside the StartChessBoard class2.9 Defining chess pieces
import java.awt.*; public class Point { private int x;//x index value of chess piece in the chess board private int y;//y index value of chess piece in the chess board private Color color;//color public static int DIAMETER=30;//diameter public Point(int x,int y,Color color){ this.x=x; this.y=y; this.color=color; } //Get x index value of chess piece in the chess board public int getX(){ return x; } //Get y index value of chess piece in the chess board public int getY(){ return y; } //Get the chess piece color public Color getColor(){ return color; } } 3. Functional part code implementation
3.1 Initialization, define some quantities to be used.
public static int MARGIN=30;//Marriage public static int GRID_SPAN=35;//Grid spacing public static int ROWS=18;//Number of chessboard rows public static int COLS=18;//Number of chessboard columns Point[] chessList=new Point[(ROWS+1)*(COLS+1)];//Initialize each array element to null boolean isBack=true;//Default starts to black chess first gameOver=false;//Does the game end int chessCount;//The number of chess pieces on the current chessboard int xIndex,yIndex;//Index of the chess piece just played
3.2 Constructing method of chessboard object
public ChessBoard(){ setBackground(Color.LIGHT_GRAY);//Set the background color to gray addMouseListener(this);//Add event listener addMouseMotionListener(new MouseMotionListener() {//Anonymous internal class @Override public void mouseMoved(MouseEvent e) { int x1=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; int y1=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;//Convert the coordinate position of the mouse click into a grid index if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOver||findChess(x1,y1)){//The game has ended and cannot be dropped; it falls outside the chessboard, cannot be dropped; there are chess pieces in the x and y position, so you cannot be setCursor(new Cursor(Cursor.DEFAULT_CURSOR));//Set to default shape}else{ setCursor(new Cursor(Cursor.HAND_CURSOR));//Set to hand shape} } @Override public void mouseDragged(MouseEvent e) { } }); }3.3 Set up the mouse listener and make the hand smaller (inside the construction method)
addMouseMotionListener(new MouseMotionListener() {//Anonymous internal class @Override public void mouseMoved(MouseEvent e) { int x1=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; int y1=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;//Convert the coordinate position of the mouse click into a grid index if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOver||findChess(x1,y1)){//The game has ended and cannot be dropped; it falls outside the chessboard, cannot be dropped; there are chess pieces in the x and y position, so you cannot be setCursor(new Cursor(Cursor.DEFAULT_CURSOR));//Set to default shape}else{ setCursor(new Cursor(Cursor.HAND_CURSOR));//Set to hand shape} } @Override public void mouseDragged(MouseEvent e) { } });3.4 Mouse pressing event when clicking the chessboard
public void mousePressed(MouseEvent e) {//If(gameOver) is called when the mouse button is pressed on the component//The game has ended and cannot be returned; String colorName=isBack ? "Black" : "White Chess"; xIndex=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; yIndex=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;//Convert the coordinate position of the mouse click into a grid index if(xIndex<0||xIndex>ROWS||yIndex<0||yIndex>COLS)//The chess piece falls outside the chessboard and cannot be returned; if(findChess(xIndex,yIndex))//The chess piece already exists at x,y position, so you cannot be returned; Point ch=new Point(xIndex,yIndex,isBack ? Color.black : Color.white); chessList[chessCount++]=ch; repaint();//Notify the system to repaint if(isWin()){ String msg=String.format("Congratulations, %s win~", colorName); JOptionPane.showMessageDialog(this, msg); gameOver=true; } else if(chessCount==(COLS+1)*(ROWS+1)) { String msg=String.format("Chess drum is quite good, great~"); JOptionPane.showMessageDialog(this,msg); gameOver=true; } isBack=!isBack; }3.5 Draw a chessboard, chess pieces and red frames
public void paintComponent(Graphics g){ super.paintComponent(g);//Draw chessboard for(int i=0;i<=ROWS;i++){//Draw horizontal line g.drawLine(MARGIN, MARGIN+i*GRID_SPAN, MARGIN+COLS*GRID_SPAN, MARGIN+i*GRID_SPAN); } for(int i=0;i<=COLS;i++){//Draw straight line g.drawLine(MARGIN+i*GRID_SPAN, MARGIN, MARGIN+i*GRID_SPAN,MARGIN+ROWS*GRID_SPAN); } /*Draw chess pieces*/ for(int i=0;i<chessCount;i++){ int xPos=chessList[i].getX()*GRID_SPAN+MARGIN;//The x coordinates of grid crossing int yPos=chessList[i].getY()*GRID_SPAN+MARGIN;//The y coordinates of grid crossing g.setColor(chessList[i].getColor());//Set the color g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER); if(i==chessCount-1){ g.setColor(Color.red);// Mark the last piece as red g.drawRect(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER); } }3.6 Judge Win or Loss
/*Judge which side wins*/ private boolean isWin(){ int continueCount=1;//The number of continuous chess pieces for(int x=xIndex-1;x>=0;x--){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } for(int x=xIndex+1;x<=ROWS;x++){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins return true; }else continueCount=1; // for(int y=yIndex-1;y>=0;y--){//Look up vertically to Color c=isBack ? Color.black : Color.white; if(getChess(xIndex,y,c)!=null){ continueCount++; }else break; } for(int y=yIndex+1;y<=ROWS;y++){//Look downwards in vertical direction Color c=isBack ? Color.black : Color.white; if(getChess(xIndex,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins return true; }else continueCount=1; // for(int x=xIndex+1,y=yIndex-1;y>=0&&x<=COLS;x++,y--){//Look down on the lower right Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } for(int x=xIndex-1,y=yIndex+1;y<=ROWS&&x>=0;x--,y++){//Look for Color c=isBack? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins. Return true; }else continueCount=1; // for(int x=xIndex-1,y=yIndex-1;y>=0&&x>=0;x--,y--){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } for(int x=xIndex+1,y=yIndex+1;y<=ROWS&&x<=COLS;x++,y++){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins return true; }else continueCount=1; return false; }3.7 The corresponding message box pops up (inside the mouse press function)
if(isWin()){ String msg=String.format("Congratulations, %s win~", colorName); JOptionPane.showMessageDialog(this, msg); gameOver=true; } else if(chessCount==(COLS+1)*(ROWS+1))//Track{ String msg=String.format("Chess drum is quite good, great~"); JOptionPane.showMessageDialog(this,msg); gameOver=true; }3.8 A function used above to determine whether there are chess pieces in a certain point
private boolean findChess(int x,int y){ for(Point c:chessList){ if(c!=null&&c.getX()==x&&c.getY()==y) return true; } return false; }3.9 Because this chessboard class implements the mouse listening interface MonseListener, all methods in the interface need to be rewrite. The other methods are as follows
@Override public void mouseClicked(MouseEvent e) {//Called when the mouse button is clicked (pressed and released) on the component} @Override public void mouseReleased(MouseEvent e) {///Called when the mouse button is released on the component} @Override public void mouseEntered(MouseEvent e) {//Called when the mouse enters the component} @Override public void mouseExited(MouseEvent e) {//Called when the mouse leaves the component}4. Operation results
V. Code summary
The game has three classes in total, one is the interface StartChessJFrame, one is the chessboard class ChessBoard, and the other is the chess-subject class Point
5.1StartChessJFrame class
package chess.lcc.com; import javax.swing.*; import java.awt.event.*; import java.awt.*; /* * Gozi's main framework, program startup class*/ public class StartChessJFrame extends JFrame { private ChessBoard chessBoard;//Fight panel private Panel toolbar;//Toolbar panel private Button startButton;//Set the start button private Button backButton;//Set the regret button private Button exitButton;//Set the exit button public StartChessJFrame(){ setTitle("Standalone Goji");//Set the title chessBoard=new ChessBoard();//Initialize the panel object, create and add menu MyItemListener lis=new MyItemListener();//Initialize the button event listener internal class toolbar=new Panel();//Instance the toolbar bar startButton=new Button("Restart"); backButton=new Button("Reply"); exitButton=new Button("Exit");//Initialize toolbar.setLayout(new FlowLayout(FlowLayout.LEFT));// Use FlowLayout to layout toolbar.add(backButton); toolbar.add(startButton); toolbar.add(exitButton);// Add three buttons to the tool panel startButton.addActionListener(lis); backButton.addActionListener(lis); exitButton.addActionListener(lis);//Register the three button events to listen for event add(toolbar,BorderLayout.SOUTH);//Layout the tool panel to the south of the interface, that is, add(chessBoard);//Add the panel object to the form setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//Set the interface to close event pack();//Adaptive size} private class MyItemListener implements ActionListener{ public void actionPerformed(ActionEvent e) { Object obj=e.getSource();//Get the event source if(obj==startButton){ System.out.println("Restart...");//Start//JFiveFrame.this inner class references the outer class chessBoard.restartGame(); }else if(obj==exitButton){ System.exit(0);//End the application}else if(obj==backButton){ System.out.println("Reply Chess...");//Reply ChessBoard.goback(); } } } public static void main(String[] args) { StartChessJFrame f=new StartChessJFrame();//Create the main frame f.setVisible(true);//Show the main frame} } 5.2ChessBoard Class
package chess.lcc.com; import javax.swing.*; import java.awt.*; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.event.MouseEvent; /*Group-chess-chessboard class*/ public class ChessBoard extends JPanel implements MouseListener{ public static int MARGIN=30;//Marriage public static int GRID_SPAN=35;//Grid spacing public static int ROWS=15;//Number of chessboard rows public static int COLS=15;//Number of chessboard columns Point[] chessList=new Point[(ROWS+1)*(COLS+1)];//Initialize each array element to null boolean isBack=true;//The default start is black chess first gameOver=false;//Is the game ended int chessCount;//The number of chess pieces on the current chessboard int xIndex,yIndex;//The index of the chess piece just played public ChessBoard(){ setBackground(Color.LIGHT_GRAY);//Set the background color to yellow addMouseListener(this);//Add event listener addMouseMotionListener(new MouseMotionListener() {//Anonymous internal class @Override public void mouseMoved(MouseEvent e) { int x1=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; int y1=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;//Convert the coordinate position of the mouse click into a grid index if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOver||findChess(x1,y1)){//The game has ended and cannot be dropped; it falls outside the chessboard, cannot be dropped; there are chess pieces in the x and y position, so you cannot be setCursor(new Cursor(Cursor.DEFAULT_CURSOR));//Set to default shape}else{ setCursor(new Cursor(Cursor.HAND_CURSOR));//Set to hand shape} } @Override public void mouseDragged(MouseEvent e) { } }); } /*Draw*/ public void paintComponent(Graphics g){ super.paintComponent(g);//Draw chessboard for(int i=0;i<=ROWS;i++){//Draw horizontal line g.drawLine(MARGIN, MARGIN+i*GRID_SPAN, MARGIN+COLS*GRID_SPAN, MARGIN+i*GRID_SPAN); } for(int i=0;i<=COLS;i++){//Draw a straight line g.drawLine(MARGIN+i*GRID_SPAN, MARGIN, MARGIN+i*GRID_SPAN,MARGIN+ROWS*GRID_SPAN); } /*Draw chess pieces*/ for(int i=0;i<chessCount;i++){ int xPos=chessList[i].getX()*GRID_SPAN+MARGIN;//x coordinates of grid crossing int yPos=chessList[i].getY()*GRID_SPAN+MARGIN;//The y coordinates of the grid crossing g.setColor(chessList[i].getColor());//Set the color g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER); if(i==chessCount-1){ g.setColor(Color.red);//Sign up the last piece as red g.drawRect(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER); } } } @Override public void mousePressed(MouseEvent e) {//If(gameOver) is called when the mouse button is pressed on the component//The game has ended, you cannot return it; String colorName=isBack ? "Black" : "White Chess"; xIndex=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; yIndex=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;//Convert the coordinate position of the mouse click into a grid index if(xIndex<0||xIndex>ROWS||yIndex<0||yIndex>COLS)//The chess piece falls outside the chessboard and cannot be returned; if(findChess(xIndex,yIndex))//The chess piece already exists at x,y position, so you cannot be returned; Point ch=new Point(xIndex,yIndex,isBack ? Color.black : Color.white); chessList[chessCount++]=ch; repaint();//Notify the system to repaint if(isWin()){ String msg=String.format("Congratulations, %s win~", colorName); JOptionPane.showMessageDialog(this, msg); gameOver=true; } else if(chessCount==(COLS+1)*(ROWS+1)) { String msg=String.format("Chess drum is quite good, great~"); JOptionPane.showMessageDialog(this,msg); gameOver=true; } isBack=!isBack; } @Override public void mouseClicked(MouseEvent e) {//Called when the mouse button is clicked (pressed and released) on the component} @Override public void mouseReleased(MouseEvent e) {///Called when the mouse button is released on the component} @Override public void mouseEntered(MouseEvent e) {//Called when the mouse enters the component} @Override public void mouseExited(MouseEvent e){//Called when the mouse leaves the component} private boolean findChess(int x,int y){ for(Point c:chessList){ if(c!=null&&c.getX()==x&&c.getY()==y) return true; } return false; } /*Judge which side win*/ private boolean isWin(){ int continueCount=1;//The number of continuous chess pieces for(int x=xIndex-1;x>=0;x--){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } for(int x=xIndex+1;x<=ROWS;x++){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins return true; }else continueCount=1; // for(int y=yIndex-1;y>=0;y--){//Look up vertically to Color c=isBack ? Color.black : Color.white; if(getChess(xIndex,y,c)!=null){ continueCount++; }else break; } for(int y=yIndex+1;y<=ROWS;y++){//Look downwards in vertical direction Color c=isBack ? Color.black : Color.white; if(getChess(xIndex,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins return true; }else continueCount=1; // for(int x=xIndex+1,y=yIndex-1;y>=0&&x<=COLS;x++,y--){//Look down on the lower right Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } for(int x=xIndex-1,y=yIndex+1;y<=ROWS&&x>=0;x--,y++){//Look for Color c=isBack? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge the number of records is greater than or equal to five, which means that this side wins. Return true; }else continueCount=1; // for(int x=xIndex-1,y=yIndex-1;y>=0&&x>=0;x--,y--){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } for(int x=xIndex+1,y=yIndex+1;y<=ROWS&&x<=COLS;x++,y++){//Look for Color c=isBack ? Color.black : Color.white; if(getChess(x,y,c)!=null){ continueCount++; }else break; } if(continueCount>=5){//Judge that the number of records is greater than or equal to five, it means that this side wins return true; }else continueCount=1; return false; } private Point getChess(int xIndex,int yIndex,Color color){ for(Point c:chessList){ if(c!=null&&c.getX()==xIndex&&c.getY()==yIndex&&c.getColor()==color) return c; } return null; } public void restartGame(){//Clear the chess piece for(int i=0;i<chessList.length;i++) chessList[i]=null; /*Restore the game-related variable value*/ isBack=true; gameOver=false;//Whether the game ends chessCount=0;//The number of chess pieces on the current board is repaint(); } public void goback(){ if(chessCount==0) return ; chessList[chessCount-1]=null; chessCount--; if(chessCount>0){ xIndex=chessList[chessCount-1].getX(); yIndex=chessList[chessCount-1].getY(); } isBack=!isBack; repaint(); } //Dimension:Rectangle public Dimension getPreferredSize(){ return new Dimension(MARGIN*2+GRID_SPAN*COLS,MARGIN*2+GRID_SPAN*ROWS); } } 5.3Point class
package chess.lcc.com; import java.awt.*; public class Point { private int x;//x index value of chess piece in the chess board private int y;//y index value of chess piece in the chess board private Color color;//color public static int DIAMETER=30;//diameter public Point(int x,int y,Color color){ this.x=x; this.y=y; this.color=color; } //Get x index value of chess piece in the chess board public int getX(){ return x; } //Get y index value of chess piece in the chess board public int getY(){ return y; } //Get the chess piece color public Color getColor(){ return color; } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.