This article describes the Gozi chess game code implemented in Java. It is shared with you for your reference. The specific code is as follows
1. Practical Objectives
1. Master the JavaGUI interface design
2. Master the monitoring of mouse events (MouseListener, MouseMotionListener)
2. Practical content
Design a simple Gochi program that can realize Gochi chess game process. As shown in the figure below
1. Gozi Chess Board
package cn.edu.ouc.fiveChess; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RadialGradientPaint; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Ellipse2D; import javax.swing.*; /** * Goziqi-chess-chess-board class*/ public class ChessBoard extends JPanel implements MouseListener { public static final int MARGIN=30;//margin public static final int GRID_SPAN=35;//Grid spacing public static final int ROWS=15;//Chessboard rows public static final int COLS=15;//Number of chessboard columns Point[] chessList=new Point[(ROWS+1)*(COLS+1)];//Initial each array element is null boolean isBlack=true;//The default starts with black chess first boolean gameOver=false;//Is the game ended int chessCount;//The current number of chess pieces int xIndex,yIndex;//The index of the chess piece just played Image img; Image shadows; Color colortemp; public ChessBoard(){ // setBackground(Color.blue);//Set the background color to orange img=Toolkit.getDefaultToolkit().getImage("board.jpg"); shadows=Toolkit.getDefaultToolkit().getImage("shadows.jpg"); addMouseListener(this); addMouseMotionListener(new MouseMotionListener(){ public void mouseDragged(MouseEvent e){ } public void mouseMoved(MouseEvent e){ int x1=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; //Convert the coordinate position of the mouse click to the grid index int y1=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN; //The game has ended and cannot be put on//There is no place outside the chessboard. //The chess piece exists at the y position, and cannot be put on if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOver||findChess(x1,y1)) setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //Set to the default status else setCursor(new Cursor(Cursor.HAND_CURSOR)); } } }); } //Draw public void paintComponent(Graphics g){ super.paintComponent(g);//Draw chessboard int imgWidth=img.getWidth(this); int imgHeight=img.getHeight(this);//Get the width and height of the picture int FWidth=getWidth(); int FHeight=getHeight();//Get the width and height of the window int x=(FWidth-imgWidth)/2; int y=(FHeight-imgHeight)/2; g.drawImage(img, x, y, null); 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 vertical line g.drawLine(MARGIN+i*GRID_SPAN, MARGIN, MARGIN+i*GRID_SPAN); } //Draw chess pieces for(int i=0;i<chessCount;i++){ //Grid intersection x, y coordinate int xPos=chessList[i].getX()*GRID_SPAN+MARGIN; int yPos=chessList[i].getY()*GRID_SPAN+MARGIN; g.setColor(chessList[i].getColor()); //Set color// g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, //Point.DIAMETER, Point.DIAMETER); //g.drawImage(shadows, xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER, null); colortemp=chessList[i].getColor(); if(colortemp==Color.black){ RadialGradientPaint paint = new RadialGradientPaint(xPos-Point.DIAMETER/2+25, yPos-Point.DIAMETER/2+10, 20, new float[]{0f, 1f} , new Color[]{Color.WHITE, Color.BLACK}); ((Graphics2D) g).setPaint(paint); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT); } else if(colortemp==Color.white){ RadialGradientPaint paint = new RadialGradientPaint(xPos-Point.DIAMETER/2+25, yPos-Point.DIAMETER/2+10, 70, new float[]{0f, 1f} , new Color[]{Color.WHITE, Color.BLACK}); ((Graphics2D) g).setPaint(paint); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT); } Ellipse2D e = new Ellipse2D.Float(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, 34, 35); ((Graphics2D) g).fill(e); //The red rectangular box marking the last chess piece if(i==chessCount-1){//If it is the last chess piece g.setColor(Color.red); g.drawRect(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, 34, 35); } } } public void mousePressed(MouseEvent e){//The mouse is called when pressed on the component //The game can no longer play if(gameOver) return; String colorName=isBlack?"Black":"White chess"; //Convert the coordinate position of the mouse click into the grid index xIndex=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN; yIndex=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN; //If you fall outside the chessboard, you can't put it if(xIndex<0||xIndex>ROWS||yIndex<0||yIndex>COLS) return; //If there is a chess piece in the x and y position, you can't put it if(findChess(xIndex,yIndex)) return; //If you can do it when it is done, you can't put it when it is done. Point(xIndex,yIndex,isBlack?Color.black:Color.white); chessList[chessCount++]=ch; repaint();//Notify the system to re-draw//If you win, give a prompt message and cannot continue playing chess if(isWin()){ String msg=String.format("Congratulations, %s won!", colorName); JOptionPane.showMessageDialog(this, msg); gameOver=true; } isBlack=!isBlack; } // Method to overwrite mouseListener public void mouseClicked(MouseEvent e){ // Called when the mouse button clicks on the component} public void mouseEntered(MouseEvent e){ //Called when the mouse enters the component} public void mouseExited(MouseEvent e){ //Called when the mouse leaves the component} public void mouseReleased(MouseEvent e){ //Called when the mouse button is released on the component} //Called in the chess array to see if there are chess pieces with index x and y that exist private boolean findChess(int x,int y){ for(Point c:chessList){ if(c!=null&&c.getX()==x&&c.getY()==y) return true; } return false; } private boolean isWin(){ int continueCount=1;//The number of continuous chess pieces//Look horizontally westward for(int x=xIndex-1;x>=0;x--){ Color c=isBlack?Color.black:Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } //Look horizontally eastward for(int x=xIndex+1;x<=COLS;x++){ Color c=isBlack?Color.black:Color.white; if(getChess(x,yIndex,c)!=null){ continueCount++; }else break; } if(continueCount>=5){ return true; }else continueCount=1; //Continue another search vertically//Search upward for(int y=yIndex-1;y>=0;y--){ Color c=isBlack?Color.black:Color.white; if(getChess(xIndex,y,c)!=null){ continueCount++; }else break; } //Look downwardly for(int y=yIndex+1;y<=ROWS;y++){ Color c=isBlack?Color.black:Color.white; if(getChess(xIndex,y,c)!=null) continueCount++; else break; } if(continueCount>=5) return true; else continueCount=1; //Continue search for another situation: obliquely //Northeast search for for(int x=xIndex+1,y=yIndex-1;y>=0&&x<=COLS;x++,y--){ Color c=isBlack?Color.black:Color.white; if(getChess(x,y,c)!=null){ continueCount++; } else break; } //Southwest search for for(int x=xIndex-1,y=yIndex+1;x>=0&&y<=ROWS;x--,y++){ Color c=isBlack?Color.black:Color.white; if(getChess(x,y,c)!=null){ continueCount++; } else break; } if(continueCount>=5) return true; else continueCount=1; //Continue search in another situation: oblique//Northwest search for(int x=xIndex-1,y=yIndex-1;x>=0&&y>=0;x--,y--){ Color c=isBlack?Color.black:Color.white; if(getChess(x,y,c)!=null) continueCount++; else break; } //Southeast look for for(int x=xIndex+1,y=yIndex+1;x<=COLS&&y<=ROWS;x++,y++){ Color c=isBlack?Color.black:Color.white; if(getChess(x,y,c)!=null) continueCount++; else break; } if(continueCount>=5) return true; else continueCount=1; return false; } private Point getChess(int xIndex,int yIndex,Color color){ for(Point p:chessList){ if(p!=null&&p.getX()==xIndex&&p.getY()==yIndex &&p.getColor()==color) return p; } return null; } public void restartGame(){ //Clear chess pieces for(int i=0;i<chessList.length;i++){ chessList[i]=null; } //Restore the game-related variable value isBlack=true; gameOver=false; //Is the game ending chessCount =0; //The current number of chess pieces repaint(); } //Reply to chess 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(); } isBlack=!isBlack; repaint(); } //Rectangle Dimension public Dimension getPreferredSize(){ return new Dimension(MARGIN*2+GRID_SPAN*COLS,MARGIN*2 +GRID_SPAN*ROWS); } } 2. Chess pieces
package cn.edu.ouc.fiveChess; import java.awt.Color; /** * chess class*/ public class Point { private int x;//x index in the chess board private int y;//y index in the chess board private Color color;//color public static final int DIAMETER=30;//diameter public Point(int x,int y,Color color){ this.x=x; this.y=y; this.color=color; } public int getX(){//get the index of x in the chess board return x; } public int getY(){ return y; } public Color getColor(){//Get the color of the chess piece return color; } } 3. Gozi main frame class
package cn.edu.ouc.fiveChess; import java.awt.event.*; import java.awt.*; import javax.swing.*; /* Goji main framework, program*/ public class StartChessJFrame extends JFrame { private ChessBoard chessBoard; private JPanel toolbar; private JButton startButton,backButton,exitButton; private JMenuBar menuBar; private JMenu sysMenu; private JMenuItem startMenuItem,exitMenuItem,backMenuItem; //Restart, exit, and regret menu item public StartChessJFrame(){ setTitle("stand-alone Goji"); //Set the title chessBoard=new ChessBoard(); Container contentPane=getContentPane(); contentPane.add(chessBoard); chessBoard.setOpaque(true); //Create and add menu menuBar =new JMenuBar(); //Initialize menu bar sysMenu=new JMenu("System"); //Initialize menu//Initialize menu item startMenuItem=new JMenuItem("Restart"); exitMenuItem =new JMenuItem("Exit"); backMenuItem =new JMenuItem("Repent"); //Add three menu items to the menu sysMenu.add(startMenuItem); sysMenu.add(exitMenuItem); sysMenu.add(backMenuItem); //Initialize the internal class MyItemListener lis=new MyItemListener(); //Register three menus to the event listener this.startMenuItem.addActionListener(lis); backMenuItem.addActionListener(lis); exitMenuItem.addActionListener(lis); menuBar.add(sysMenu);//Add the system menu to the menu bar setJMenuBar(menuBar);//Set menuBar to menubar toolbar=new JPanel();//Instantiate the tool panel //Three buttons initialize startButton=new JButton("Start Restart"); exitButton=new JButton("Exit"); backButton=new JButton("Repent"); //Layout the tool panel buttons with FlowLayout toolbar.setLayout(new FlowLayout(FlowLayout.LEFT)); //Add three buttons to the tool panel toolbar.add(startButton); toolbar.add(exitButton); toolbar.add(backButton); //Register the three buttons to listen for the event startButton.addActionListener(lis); exitButton.addActionListener(lis); backButton.addActionListener(lis); backButton.addActionListener(lis); //Lay the tool panel to the interface "south" that is, add(toolbar,BorderLayout.SOUTH); add(chessBoard);//Add panel object to the form//Set the interface close event setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setSize(800,800); pack();//Adaptive size} private class MyItemListener implements ActionListener{ public void actionPerformed(ActionEvent e){ Object obj=e.getSource();//Get the event source if(obj==StartChessJFrame.this.startMenuItem||obj==startButton){ //Start//JFiveFrame.this inner class references the outer class System.out.println("Start"); chessBoard.restartGame(); } else if (obj==exitMenuItem||obj==exitButton) System.exit(0); else if (obj==backMenuItem||obj==backButton){ System.out.println("Repent Chess..."); chessBoard.goback(); } } } public static void main(String[] args){ StartChessJFrame f=new StartChessJFrame();//Create the main frame f.setVisible(true);//Show the main frame} } 3. Summary
1. Design and implementation of menus?
2. How to draw chess pieces after the mouse clicks on the chessboard? How to draw a red box for the chess piece you just set up?
3. What is a data structure for chess scores?
The above is all about this article, I hope it will be helpful for everyone to learn Java programming.