This article describes the Chinese chess game code implemented by Java. It is shared with you for your reference. The specific code is as follows
1. Practical purpose:
1. Application and difference between mouse click, drag and other events
2. Saving and reading of chess record files
3. Improve the rules of chess.
2. Practical content:
Chinese chess has a long history and has attracted countless people to study. Now we have made the following design and explanation of the battles of Chinese chess and the production of chess scores for your reference and learning.
1. When playing chess between machines and machines, the red side takes the lead. Drag the chess piece to the destination if it meets the rules and the squirrel is dropped.
Everyone plays chess
2. Make a chess record. After selecting the chess record menu, the game begins and the chess process is recorded.
Select the "Make Chess Record" menu
The red side won after the chess score was finished
After one side wins, the victory message dialog box pops up. After clicking OK, select the "Save Chess Record" menu to bring up the Save File dialog box.
Save chess record dialog box
3. Demonstrate the chess score. After selecting the Demonstration chess score menu, an open dialog box pops up, select the saved chess score to start the demonstration.
Demonstrate chess record dialog box
Demonstrate the chess record process (automatic and manual)
3. Reference code:
1. Chess main file ChineseChess.java
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.LinkedList; /** * Chess main class* * @author cnlht */ public class ChineseChess extends JFrame implements ActionListener { ChessBoard board = null; Demon demon = null; MakeChessManual record = null; Container con = null; JMenuBar bar; JMenu fileMenu; JMenuItem Make chess score, save chess score, demonstrate chess score; JFileChooser fileChooser = null; LinkedList chess score= null; public ChineseChess() { bar = new JMenuBar(); fileMenu = new JMenu("Chinese chess"); Make chess score= new JMenuItem("Make chess score"); Save chess score= new JMenuItem("Save chess score"); Save chess score.setEnabled(false); Demonstration chess score= new JMenuItem("Demonstration chess score"); fileMenu.add(make chess score); fileMenu.add(save chess score); fileMenu.add(demonstrate chess score); bar.add(fileMenu); setJMenuBar(bar); setTitle(make chess score.getText()); make chess score.addActionListener(this); save chess score.addActionListener(this); demonstrate chess score.addActionListener(this); board = new ChessBoard(45, 45, 9, 10); record = board.record; con = getContentPane(); JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, board, record); split.setDividerSize(5); split.setDividerLocation(460); con.add(split, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setVisible(true); setBounds(60, 20, 690, 540); fileChooser = new JFileChooser(); con.validate(); validate(); } public void actionPerformed(ActionEvent e) { if (e.getSource() == Make chess score) { con.removeAll(); Save chess score.setEnabled(true); this.setTitle(Create chess score.getText()); board = new ChessBoard(45, 45, 9, 10); record = board.record; JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, board, record); split.setDividerSize(5); split.setDividerLocation(460); con.add(split, BorderLayout.CENTER); validate(); } if (e.getSource() == Save chess score) { int state = fileChooser.showSaveDialog(null); File saveFile = fileChooser.getSelectedFile(); if (saveFile != null && state == JFileChooser.APPROVE_OPTION) { try { FileOutputStream outOne = new FileOutputStream(saveFile); ObjectOutputStream outTwo = new ObjectOutputStream(outOne); outTwo.writeObject(record.get chess score()); outOne.close(); outTwo.close(); } catch (IOException event) { } } } if (e.getSource() == Demonstrate chess score) { con.removeAll(); con.repaint(); con.validate(); validate(); save chess score.setEnabled(false); int state = fileChooser.showOpenDialog(null); File openFile = fileChooser.getSelectedFile(); if (openFile != null && state == JFileChooser.APPROVE_OPTION) { try { FileInputStream inOne = new FileInputStream(openFile); ObjectInputStream inTwo = new ObjectInputStream(inOne); Chess = (LinkedList) inTwo.readObject(); inOne.close(); inTwo.close(); ChessBoard board = new ChessBoard(45, 45, 9, 10); demon = new Demon(board); demon.set chess record(chess record); con.add(demon, BorderLayout.CENTER); con.validate(); validate(); this.setTitle(demo chess record.getText() + ":" + openFile); } catch (Exception event) { JLabel label = new JLabel("not chess record file"); label.setFont(new Font("Lishu", Font.BOLD, 60)); label.setForeground(Color.red); label.setHorizontalAlignment(SwingConstants.CENTER); con.add(label, BorderLayout.CENTER); con.validate(); this.setTitle("No chess record"); validate(); } } else { JLabel label = new JLabel("No chess record file is not opened"); label.setFont(new Font("Lishu", Font.BOLD, 50)); label.setForeground(Color.pink); label.setHorizontalAlignment(SwingConstants.CENTER); con.add(label, BorderLayout.CENTER); con.validate(); this.setTitle("The chess file is not opened"); validate(); } } } public static void main(String args[]) { new ChineseChess(); } } 2. ChessBoard.java file
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * chessboard class* * @author cnlht */ public class ChessBoard extends JPanel implements MouseListener, MouseMotionListener { public ChessPoint point[][]; public int unitWidth, unitHeight; private int x-axis length, y-axis length; private int x, y; private Image img; protected Image pieceImg; private boolean move = false; public String Red square color = "Red square", Black square color = "Black square"; ChessPiece Red cart 1, Red cart 2, Red horse 1, Red horse 2, Red horse 1, Red horse 2, Red horse 3, Red soldiers 4, Red soldiers 5, Red cannon 1, Red cannon 2; ChessPiece Black cart 1, Black cart 2, Black horse 1, Black horse 2, Black general, Black soldiers 1, Black soldiers 2, Black soldiers 3, Black soldiers 4, Black soldiers 5, Black elephant 1, Black elephant 2, Black gun 1, Black cannon 2; int startX, startY; int startI, startJ; public boolean Red side chess = true, black side chess = false; Rule rule = null; public MakeChessManual record = null; public ChessBoard(int w, int h, int r, int c) { setLayout(null); addMouseListener(this); addMouseMotionListener(this); Color bc = getBackground(); unitWidth = w; unitHeight = h; x-axis length = r; y-axis length = c; point = new ChessPoint[r + 1][c + 1]; for (int i = 1; i <= r; i++) { for (int j = 1; j <= c; j++) { point[i][j] = new ChessPoint(i * unitWidth, j * unitHeight, false); } } rule = new Rule(this, point); record = new MakeChessManual(this, point); img = Toolkit.getDefaultToolkit().getImage("board.jpg"); pieceImg = Toolkit.getDefaultToolkit().getImage("piece.gif"); red car 1 = new ChessPiece("", Color.red, bc, w - 4, h - 4, this); Red car 1.set chess piece category (red square color); Red car 2 = new ChessPiece("", Color.red, bc, w - 4, h - 4, this); Red car 2.set chess piece category (red square color); Red horse 1 = new ChessPiece("", Color.red, bc, w - 4, h - 4, this); Red horse 1 = new ChessPiece("", Color.red, bc, w - 4, h - 4, this); Red horse 2.set chess piece category (red square color); Red Cannon 1 = new ChessPiece("火", Color.red, bc, w - 4, h - 4, this); Red Cannon 1.set chess piece category (red square color); Red Cannon 2 = new ChessPiece("火", Color.red, bc, w - 4, h - 4, this); Red Cannon 2.set chess piece category (red square color); Red Cannon 1 = new ChessPiece("火", Color.red, bc, w - 4, h - 4, this); Red Cannon 1.set chess piece category (red square color); Red Cannon 2 = new ChessPiece("火", Color.red, bc, w - 4, h - 4, this); Red Cannon 1.set chess piece category (red square color); Red Cannon 2 = new ChessPiece("火", Color.red, bc, w - 4, h - 4, this); Red 2.set chess piece category (red square color); Red 1 = new ChessPiece("Shi", Color.red, bc, w - 4, h - 4, this); Red 1.set chess piece category (red square color); Red 2 = new ChessPiece("Shi", Color.red, bc, w - 4, h - 4, this); Red 2.set chess piece category (red square color); Red 2.set chess piece category (red square color); Red 2 = new ChessPiece("Shi", Color.red, bc, w - 4, h - 4, this); Red 1 = new ChessPiece("Shi", Color.red, bc, w - 4, h - 4, this); Red Soldier 1.set chess piece category (red square color); Red Soldier 2 = new ChessPiece("Soldier", Color.red, bc, w - 4, h - 4, this); Red Soldier 2.set chess piece category (red square color); Red Soldier 3 = new ChessPiece("Soldier", Color.red, bc, w - 4, h - 4, this); Red Soldier 3 = new ChessPiece("Soldier", Color.red, bc, w - 4, h - 4, this); Red Soldier 4.set chess piece category (red square color); Red Soldier 5 = new ChessPiece("Soldier", Color.red, bc, w - 4, h - 4, this); Red Soldier 5.set chess piece category (red square color); Black Soldier = new ChessPiece("Sold", Color.black, bc, w - 4, h - 4, this); Black Soldier 1 = new ChessPiece("Soldier", Color.black, bc, w - 4, h - 4, this); Black Soldier 1 = new ChessPiece("Soldier", Color.black, bc, w - 4, h - 4, this); Black Soldier 1 = new ChessPiece("car", Color.black, bc, w - 4, h - 4, this); Black car 1.set chess piece category (black square color); Black car 2 = new ChessPiece("car", Color.black, bc, w - 4, h - 4, this); Black car 2.set chess piece category (black square color); Black cannon 1 = new ChessPiece("cannon", Color.black, bc, w - 4, h - 4, this); Black cannon 1.set chess piece category (black square color); Black cannon 2 = new ChessPiece("cannon", Color.black, bc, w - 4, h - 4, this); Black Cannon 2.set chess piece category (black square color); Black Elephant 1 = new ChessPiece("Elephant", Color.black, bc, w - 4, h - 4, this); Black Elephant 1.set chess piece category (black square color); Black Elephant 2 = new ChessPiece("Elephant", Color.black, bc, w - 4, h - 4, this); Black Elephant 2.set chess piece category (black square color); Black Elephant 1 = new ChessPiece("Elephant", Color.black, bc, w - 4, h - 4, this); Black Elephant 1.set chess piece category (black square color); Black Elephant 2 = new ChessPiece("Elephant", Color.black, bc, w - 4, h - 4, this); Black Horse 2.set chess piece category (black color); Black Pants 1 = new ChessPiece("Zhi", Color.black, bc, w - 4, h - 4, this); Black Pants 1.set chess piece category (black color); Black Pants 2 = new ChessPiece("Zhi", Color.black, bc, w - 4, h - 4, this); Black Pants 2.set chess piece category (black color); Black Pants 3 = new ChessPiece("Zhi", Color.black, bc, w - 4, h - 4, this); Black Pants 3.set chess piece category (black color); Black Pants 4 = new ChessPiece("Zhi", Color.black, bc, w - 4, h - 4, this); Black Phantom 4.set chess piece category (black square color); Black Phantom 5 = new ChessPiece("Zhi", Color.black, bc, w - 4, h - 4, this); Black Phantom 5.set chess piece category (black square color); point[1][10].setPiece(Red Carriage 1, this); point[2][10].setPiece(Red Horse 1, this); point[3][10].setPiece(Red Phase 1, this); point[4][10].setPiece(Red Sage 1, this); point[4][10].setPiece(Red Sage 1, this); point[4][10].setPiece(Red Sage 1, this); point[5][10].setPiece(Red Soldier, this); point[6][10].setPiece(Red Soldier 2, this); point[7][10].setPiece(Red Soldier 2, this); point[8][10].setPiece(Red Horse 2, this); point[9][10].setPiece(Red Soldier 2, this); point[2][8].setPiece(Red Soldier 1, this); point[8][8].setPiece(Red Soldier 2, this); point[1][7].setPiece(Red Soldier 2, this); point[3][7].setPiece(Red Soldier 2, this); point[3][7].setPiece(Red Soldier 2, this); point[3][7].setPiece(Red Soldier 2, this); point[5][7].setPiece(Red Soldier 3, this); point[7][7].setPiece(Red Soldier 4, this); point[9][7].setPiece(Red Soldier 5, this); point[1][1].setPiece(Black Car 1, this); point[2][1].setPiece(Black Horse 1, this); point[3][1].setPiece(Black Elephant 1, this); point[4][1].setPiece(Black Elephant 1, this); point[5][1].setPiece(Black General, this); point[6][1].setPiece(Black Elephant 1, this); point[4][1].setPiece(Black General 1, this); point[5][1].setPiece(Black General 2, this); point[6][1].setPiece(Black General 2, this); point[7][1].setPiece(Black Elephant 2, this); point[8][1].setPiece(Black Horse 2, this); point[9][1].setPiece(Black Car 2, this); point[2][3].setPiece(Black Cannon 1, this); point[8][3].setPiece(Black Cannon 2, this); point[1][4].setPiece(Black Cannon 1, this); point[3][4].setPiece(Black Cannon 2, this); point[5][4].setPiece(Black Cannon 3, this); point[7][4].setPiece(Black Cannon 4, this); point[7][4].setPiece(Black Cannon 4, this); point[3][4].setPiece(Black Cannon 4, this); point[5][4].setPiece(Black Cannon 3, this); point[7][4].setPiece(Black Cannon 4, this); point[9][4].setPiece(Black Purse 5, this); } public void paintComponent(Graphics g) { super.paintComponent(g); 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 j = 1; j <= y-axis length; j++) { g.drawLine(point[1][j].x, point[1][j].y, point[x-axis length][j].x, point[x-axis length][j].y); } for (int i = 1; i <= x-axis length; i++) { if (i != 1 && i != x-axis length) { g.drawLine(point[i][1].x, point[i][1].y, point[i][y-axis length-5].x, point[i][y-axis length-5].y); g.drawLine(point[i][y-axis length-4].x, point[i][y-axis length - 4].y, point[i][y-axis length].x, point[i][y-axis length].y); } else { g.drawLine(point[i][1].x, point[i][1].y, point[i][y-axis length].x, point[i][y-axis length].y); } } g.drawLine(point[4][1].x, point[4][1].y, point[6][3].x, point[6][3].y); g.drawLine(point[6][1].x, point[6][1].y, point[4][3].x, point[6][1].y, point[4][3].x, point[4][3].y); g.drawLine(point[4][8].x, point[4][8].y, point[6][y-axis length].x, point[6][y-axis length].y); g.drawLine(point[4][y-axis length].x, point[4][y-axis length].y, point[6][8].x, point[6][8].y); for (int i = 1; i <= x-axis length; i++) { g.drawString("" + i, i * unitWidth, unitHeight / 2); } int j = 1; for (char c = 'A'; c <= 'J'; c++) { g.drawString("" + c, unitWidth / 4, j * unitHeight); j++; } } /**Mouse press event*/ public void mousePressed(MouseEvent e) { ChessPiece piece = null; Rectangle rect = null; if (e.getSource() == this) move = false; if (move == false) if (e.getSource() instanceof ChessPiece) { piece = (ChessPiece) e.getSource(); startX = piece.getBounds().x; startY = piece.getBounds().y; rect = piece.getBounds(); for (int i = 1; i <= x-axis length; i++) { for (int j = 1; j <= y-axis length; j++) { int x = point[i][j].getX(); int y = point[i][j].getY(); if (rect.contains(x, y)) { startI = i; startJ = j; break; } } } } } } public void mouseMoved(MouseEvent e) { } /**Mouse drag event*/ public void mouseDragged(MouseEvent e) { ChessPiece piece = null; if (e.getSource() instance of ChessPiece) { piece = (ChessPiece) e.getSource(); move = true; e = SwingUtilities.convertMouseEvent(piece, e, this); } if (e.getSource() == this) { if (move && piece != null) { x = e.getX(); y = e.getY(); if (Red Square Chess && ((piece.chess subcategory()).equals(Red Square Color))) { piece.setLocation(x - piece.getWidth() / 2, y - piece.getHeight() / 2); } if (Black chess move&& (piece.chess class().equals(black font color))) { piece.setLocation(x - piece.getWidth() / 2, y - piece.getHeight() / 2); } } } } /**Release mouse event*/ public void mouseReleased(MouseEvent e) { ChessPiece piece = null; move = false; Rectangle rect = null; if (e.getSource() instanceof ChessPiece) { piece = (ChessPiece) e.getSource(); rect = piece.getBounds(); e = SwingUtilities.convertMouseEvent(piece, e, this); } if (e.getSource() == this) { boolean containsChessPoint = false; int x = 0, y = 0; int m = 0, n = 0; if (piece != null) { for (int i = 1; i <= x-axis length; i++) { for (int j = 1; j <= y-axis length; j++) { x = point[i][j].getX(); y = point[i][j].getY(); if (rect.contains(x, y)) { containsChessPoint = true; m = i; n = j; break; } } } } } if (piece != null && containsChessPoint) { Color pieceColor = piece.get piece.get color(); if (point[m][n].isPiece()) { Color c = (point[m][n].getPiece()).get color of chess(); if (pieceColor.getRGB() == c.getRGB()) { piece.setLocation(startX, startY); (point[startI][startJ]).set has chess pieces(true); } else { boolean ok = rule.movePieceRule(piece, startI, startJ, m, n); if (ok) { ChessPiece pieceRemoved = point[m][n].getPiece(); point[m][n].reMovePiece(pieceRemoved, this); point[m][n].setPiece(piece, this); (point[startI][startJ]).set has chess pieces(false); record.Record chess score(piece, startI, startJ, m, n); record.Record the eaten chess pieces (pieceRemoved); rule.isWine(pieceRemoved); if (piece.Paper category().equals(red square color)) { Red square move = false; Black square move = true; } if (piece.Paper category().equals(black square color)) { Black square move = false; Red square move = true; } validate(); repaint(); } else { piece.setLocation(startX, startY); (point[startI][startJ]).set has chess pieces (true); } } } else { boolean ok = rule .movePieceRule(piece, startI, startJ, m, n); if (ok) { point[m][n].setPiece(piece, this); (point[startI][startJ]).set has chess pieces (false); record.Record chess score(piece, startI, startJ, m, n); record.Record chess pieces eaten ("No chess pieces"); if (piece.Paper category().equals(Red Square color)) { Red Square chess = false; Black Square chess = true; } if (piece.Paper category().equals(Black Square color)) { Black Square chess = false; Red Square chess = true; } } else { piece.setLocation(startX, startY); (point[startI][startJ]).set has chess pieces(true); } } } if (piece != null && !containChessPoint) { piece.setLocation(startX, startY); (point[startI][startJ]).set has chess pieces(true); } } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } } 3. ChessPiece.java file
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * chess class* * @author cnlht */ public class ChessPiece extends JLabel { String name; // Chess name Color backColor = null, foreColor;// Background and foreground color String Color category= null; ChessBoard board = null; int width, height;// Size public ChessPiece(String name, Color fc, Color bc, int width, int height, ChessBoard board) {// Construct the chess piece this.name = name; this.board = board; this.width = width; this.height = height; foreColor = fc; backColor = bc; setSize(width, height); setBackground(bc); addMouseMotionListener(board); addMouseListener(board); } // Draw chess piece public void paint(Graphics g) { g.drawImage(board.pieceImg, 2, 2, width-2, height-2, null); g.setColor(foreColor); g.setFont(new Font("KaiTi", Font.BOLD, 26)); g.drawString(name, 7, height - 8);// draw "chess name" on the chess piece g.setColor(Color.black); //g.drawOval(1, 1, width - 1, height - 1); float lineWidth = 2.3f; ((Graphics2D)g).setStroke(new BasicStroke(lineWidth)); ((Graphics2D)g).drawOval(2, 2, width-2, height-2); } public int getWidth() { return width; } public int getHeight() { return height; } public String getName() { return name; } public Color Get the chess color() { return foreColor; } public void set chess category (String category) { color category = category; } public String chess category() { return color category; } } 4. Chess piece point coordinate file
package cn.edu.ouc.chineseChess; /** * Chess Point class* * @author cnlht */ public class ChessPoint { /** Chesspiece coordinates*/ int x, y; /** Does this coordinate have a piece*/ boolean have a piece; /** ChessPiece piece = null; /** Chessboard to which the coordinate belongs*/ ChessBoard board = null; public ChessPoint(int x, int y, boolean boo) { this.x = x; this.y = y; Have a piece = boo; } public boolean isPiece() { return There are chess pieces; } public void set has chess pieces(boolean boo) { chess pieces = boo; } public int getX() { return x; } public int getY() { return y; } // Set change points to chess pieces public void setPiece(ChessPiece piece, ChessBoard board) { this.board = board; this.piece = piece; board.add(piece); int w = (board.unitWidth); int h = (board.unitHeight); piece.setBounds(x - w / 2, y - h / 2, w, h);// chess piece position, width, height with chess pieces = true; board.validate(); } public ChessPiece getPiece() { return piece; } public void reMovePiece(ChessPiece piece, ChessBoard board) { this.board = board; this.piece = piece; board.remove(piece); board.validate(); chess pieces = false; } } 5. Gameplay Rule Class File Rule.java
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Chess-playing rules class* * @author cnlht */ public class Rule { ChessBoard board = null; ChessPiece piece = null; ChessPoint point[][]; int startI, startJ, endI, endJ; public Rule(ChessBoard board, ChessPoint point[][]) { this.board = board; this.point = point; } public void isWine(ChessPiece piece) { this.piece = piece; if (piece.getName() == "Aligned" || piece.getName() == "Handy") { if (piece.color category== "Red Side") { JOptionPane.showMessageDialog(null, "Black Side Victory!"); } else { JOptionPane.showMessageDialog(null, "Red Side Victory!"); } } } public boolean movePieceRule(ChessPiece piece, int startI, int startJ, int endI, int endJ) { this.piece = piece; this.startI = startI; this.startJ = startJ; this.endI = endI; this.endJ = endJ; int minI = Math.min(startI, endI); int maxI = Math.max(startI, endI); int minJ = Math.min(startJ, endJ); int maxJ = Math.max(startJ, endJ); boolean Can you play chess= false; if (piece.getName().equals("car")) { if (startI == endI) { int j = 0; for (j = minJ + 1; j <= maxJ - 1; j++) { if (point[startI][j].isPiece()) { Can you move chess = false; break; } } if (j == maxJ) { Can you move chess = true; } } else if (startJ == endJ) { int i = 0; for (i = minI + 1; i <= maxI - 1; i++) { if (point[i][startJ].isPiece()) { Can you move chess = false; break; } } if (i == maxI) { Can you move chess = true; } } else { Can you move chess = false; } } } else if (piece.getName().equals("")) { if (startI == endI) { int j = 0; for (j = minJ + 1; j <= maxJ - 1; j++) { if (point[startI][j].isPiece()) { Can you move chess = false; break; } } if (j == maxJ) { Can you move chess = true; } } else if (startJ == endJ) { int i = 0; for (i = minI + 1; i <= maxI - 1; i++) { if (point[i][startJ].isPiece()) { Can you move chess = false; break; } } if (i == maxI) { Can I move chess = true; } } else { Can I move chess = false; } } else if (piece.getName().equals("Ma")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (xAxle == 2 && yAxle == 1) { if (endI > startI) { if (point[startI + 1][startJ].isPiece()) { Can I move chess = false; } else { Can I move chess = true; } } if (endI < startI) { if (point[startI - 1][startJ].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } }else if (xAxle == 1 && yAxle == 2) { if (endJ > startJ) { if (point[startI][startJ + 1].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } if (endJ < startJ) { if (point[startI][startJ - 1].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } if (endJ < startJ) { if (point[startI][startJ - 1].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } true; } } } else { Can I move chess = false; } } else if (piece.getName().equals("")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (xAxle == 2 && yAxle == 1) { if (endI > startI) { if (point[startI + 1][startJ].isPiece()) { Can I move chess = false; } else { Can I move chess = true; } } if (endI < startI) { if (point[startI - 1][startJ].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } }else if (xAxle == 1 && yAxle == 2) { if (endJ > startJ) { if (point[startI][startJ + 1].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } if (endJ < startJ) { if (point[startI][startJ - 1].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } } else { Can you move chess = false; } } else if (piece.getName().equals("icon")) { int centerI = (startI + endI) / 2; int centerJ = (startJ + endJ) / 2; int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (xAxle == 2 && yAxle == 2 && endJ <= 5) { if (point[centerI][centerJ].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } else { Can you move chess = false; } } else if (piece.getName().equals("phase")) { int centerI = (startI + endI) / 2; int centerJ = (startJ + endJ) / 2; int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (xAxle == 2 && yAxle == 2 && endJ >= 6) { if (point[centerI][centerJ].isPiece()) { Can you move chess = false; } else { Can you move chess = true; } } else { Can you move chess = true; } } else { Can you move chess = true; } } else { Can you move chess = false; } } else if (piece.getName().equals("cannon")) { int number = 0; if (startI == endI) { int j = 0; for (j = minJ + 1; j <= maxJ - 1; j++) { if (point[startI][j].isPiece()) { number++; } } if (number > 1) { Can you move chess = false; } else if (number == 1) { if (point[endI][endJ].isPiece()) { Can you move chess = true; } } else if (number == 0 && !point[endI][endJ].isPiece()) { Can you move chess = true; } } else if (startJ == endJ) { int i = 0; for (i = minI + 1; i <= maxI - 1; i++) { if (point[i][startJ].isPiece()) { number++; } } if (number > 1) { Can you move chess = false; } else if (number == 1) { if (point[endI][endJ].isPiece()) { Can you move chess = true; } } else if (number == 0 && !point[endI][endJ].isPiece()) { Can you move chess = true; } } else { Can you move chess = false; } } else if (piece.getName().equals("Soldier")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (endJ >= 6) { if (startJ - endJ == 1 && xAxle == 0) { Can you move chess = true; } else { Can you move chess = false; } } else if (endJ <= 5) { if ((startJ - endJ == 1) && (xAxle == 0)) { Can I move chess = true; } else if ((endJ - startJ == 0) && (xAxle == 1)) { Can I move chess = true; } else { Can I move chess = false; } } } else if (piece.getName().equals("Zhi")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (endJ <= 5) { if (endJ - startJ == 1 && xAxle == 0) { Can I move chess = true; } else { Can you move chess = false; } } else if (endJ >= 6) { if ((endJ - startJ == 1) && (xAxle == 0)) { Can you move chess = true; } else if ((endJ - startJ == 0) && (xAxle == 1)) { Can you move chess = true; } else { Can you move chess = false; } } } else if (piece.getName().equals("Shi")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (endI <= 6 && endI >= 4 && xAxle == 1 && yAxle == 1) { Can you move chess = true; } else { Can you move chess = false; } } else if (piece.getName().equals("State")) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (endI <= 6 && endI >= 4 && xAxle == 1 && yAxle == 1) { Can you move chess = true; } else { Can you move chess = false; } } else if ((piece.getName().equals("Handsome")) || (piece.getName().equals("Replace"))) { int xAxle = Math.abs(startI - endI); int yAxle = Math.abs(startJ - endJ); if (endI <= 6 && endI >= 4) { if ((xAxle == 1 && yAxle == 0) || (xAxle == 0 && yAxle == 1)) { Can you move chess = true; } else { Can you move chess = false; } } else { Can you move chess = false; } } return Can you move chess; } } 6. MoveStep.java file
package cn.edu.ouc.chineseChess; import java.awt.Point; /** * Walking class* * @author cnlht * */ public class MoveStep implements java.io.Serializable { public Point pStart, pEnd; public MoveStep(Point p1, Point p2) { pStart = p1; pEnd = p2; } } 7. Make ChessManual.java
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.LinkedList; /** * Make chess record class* * @author cnlht */ public class MakeChessManual extends JPanel implements ActionListener { JTextArea text = null; JScrollPane scroll = null; ChessBoard board = null; ChessPoint[][] point; LinkedList Chess Note = null; LinkedList Eated chess pieces = null; JButton buttonUndo; int i = 0; public MakeChessManual(ChessBoard board, ChessPoint[][] point) { this.board = board; this.point = point; text = new JTextArea(); scroll = new JScrollPane(text); Chess Note = new LinkedList(); Eated chess pieces = new LinkedList(); buttonUndo = new JButton("Repent Chess"); buttonUndo.setFont(new Font("Lishu", Font.PLAIN, 18)); setLayout(new BorderLayout()); add(scroll, BorderLayout.CENTER); add(buttonUndo, BorderLayout.SOUTH); buttonUndo.addActionListener(this); } public char numberToLetter(int n) { char c = '/0'; switch (n) { case 1: c = 'A'; break; case 2: c = 'B'; break; case 3: c = 'C'; break; case 4: c = 'D'; break; case 5: c = 'E'; break; case 6: c = 'F'; break; case 7: c = 'G'; break; case 8: c = 'H'; break; case 9: c = 'I'; break; case 10: c = 'J'; break; } return c; } public void record chess score(ChessPiece piece, int startI, int startJ, int endI, int endJ) { Point pStart = new Point(startI, startJ); Point pEnd = new Point(endI, endJ); MoveStep step = new MoveStep(pStart, pEnd); Chess score.add(step); String chess category = piece.chess category(); String name = piece.getName(); String m = "#" + chess category + name + ": " + startI + numberToLetter(startJ) + " to " + endI + numberToLetter(endJ); text.append(m); if (piece. chess category().equals(board.black square color)) text.append("/n"); } public void record the eaten chess piece (Object object) { eaten chess piece.add(object); } public LinkedList Get the chess piece() { return chess piece; } public void actionPerformed(ActionEvent e) { int position = text.getText().lastIndexOf("#"); if (position != -1) text.replaceRange("", position, text.getText().length()); if (chess piece.size() > 0) { MoveStep lastStep = (MoveStep) chess piece.getLast(); Chess record.removeLast(); Object qizi = Eated chess piece.getLast(); Eated chess piece.removeLast(); String temp = qizi.toString(); if (temp.equals("No chess piece")) { int startI = lastStep.pStart.x; int startJ = lastStep.pStart.y; int endI = lastStep.pEnd.x; int endJ = lastStep.pEnd.y; ChessPiece piece = point[endI][endJ].getPiece(); point[startI][startJ].setPiece(piece, board); (point[endI][endJ]).set has chess pieces (false); if (piece.chess piece category().equals(board.red square color)) { board.red square move = true; board.black square move = false; } if (piece.chess piece category().equals(board.black square color)) { board.black square move = true; board.red square move = false; } } else { ChessPiece removedPiece = (ChessPiece) qizi; int startI = lastStep.pStart.x; int startJ = lastStep.pStart.y; int endI = lastStep.pEnd.x; int endJ = lastStep.pEnd.y; ChessPiece piece = point[endI][endJ].getPiece(); point[startI][startJ].setPiece(piece, board); point[endI][endJ].setPiece(removedPiece, board); (point[endI][endJ]).set has chess pieces(true); if (piece.Paper category().equals(board.Red square color)) { board.Red square move = true; board.Black square move = false; } if (piece.Paper Category().equals(board.Black Square Color)) { board.Black Square Chess = true; board.Red Square Chess = false; } } } } } } 8. Demon.java
package cn.edu.ouc.chineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; /** * Demo chess class* * @author cnlht */ public class Demon extends JPanel implements ActionListener, Runnable { public JButton replay = null, next = null, auto = null, stop = null; LinkedList chess = null; Thread Automatic demonstration = null; int index = -1; ChessBoard board = null; JTextArea text; JTextField Time interval= null; int time = 1000; String Demo process = ""; JSplitPane splitH = null, splitV = null; public Demon(ChessBoard board) { this.board = board; replay = new JButton("Redemo"); next = new JButton("Next"); auto = new JButton("Automatic Demo"); stop = new JButton("Pause Demo"); Automatic Demo= new Thread(this); replay.addActionListener(this); next.addActionListener(this); auto.addActionListener(this); stop.addActionListener(this); text = new JTextArea(); Time interval = new JTextField("1"); setLayout(new BorderLayout()); JScrollPane pane = new JScrollPane(text); JPanel p = new JPanel(new GridLayout(3, 2)); p.add(next); p.add(replay); p.add(auto); p.add(stop); p.add(new JLabel("Time interval (seconds), SwingConstants.CENTER)); p.add(time interval); splitV = new JSplitPane(JSplitPane.VERTICAL_SPLIT, pane, p); splitH = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, board, splitV); splitV.setDividerSize(5); splitV.setDividerLocation(400); splitH.setDividerSize(5); splitH.setDividerLocation(460); add(splitH, BorderLayout.CENTER); validate(); } public void set chess score(LinkedList chess score) { this. chess score= chess score; } public char numberToLetter(int n) { char c = '/0'; switch (n) { case 1: c = 'A'; break; case 2: c = 'B'; break; case 3: c = 'C'; break; case 4: c = 'D'; break; case 5: c = 'E'; break; case 6: c = 'F'; break; case 7: c = 'G'; break; case 8: c = 'H'; break; case 9: c = 'I'; break; case 10: c = 'J'; break; } return c; } public void actionPerformed(ActionEvent e) { if (e.getSource() == next) { index++; if (index < chess score.size()) { demonstration step(index); } else { demonstration end ("chess score demonstration completed"); } } if (e.getSource() == replay) { board = new ChessBoard(45, 45, 9, 10); splitH.remove(board); splitH.setDividerSize(5); splitH.setDividerLocation(460); splitH.setLeftComponent(board); splitH.validate(); index = -1; text.setText(null); } if (e.getSource() == auto) { next.setEnabled(false); replay.setEnabled(false); try { time = 1000 * Integer.parseInt(时间间隔.getText().trim()); } catch (NumberFormatException ee) { time = 1000; } if (!(自动演示.isAlive())) { 自动演示= new Thread(this); board = new ChessBoard(45, 45, 9, 10); splitH.remove(board); splitH.setDividerSize(5); splitH.setDividerLocation(460); splitH.setLeftComponent(board); splitH.validate(); text.setText(null); 自动演示.start(); } } if (e.getSource() == stop) { if (e.getActionCommand().equals("暂停演示")) { 演示过程= "暂停演示"; stop.setText("继续演示"); stop.repaint(); } if (e.getActionCommand().equals("继续演示")) { 演示过程= "继续演示"; 自动演示.interrupt(); stop.setText("暂停演示"); stop.repaint(); } } } public synchronized void run() { for (index = 0; index < 棋谱.size(); index++) { try { Thread.sleep(time); } catch (InterruptedException e) { } while (演示过程.equals("暂停演示")) { try { wait(); } catch (InterruptedException e) { notifyAll(); } } 演示一步(index); } if (index >= 棋谱.size()) { 演示结束("棋谱演示完毕"); next.setEnabled(true); replay.setEnabled(true); } } public void 演示一步(int index) { MoveStep step = (MoveStep) 棋谱.get(index); Point pStart = step.pStart; Point pEnd = step.pEnd; int startI = pStart.x; int startJ = pStart.y; int endI = pEnd.x; int endJ = pEnd.y; ChessPiece piece = (board.point)[startI][startJ].getPiece(); if ((board.point)[endI][endJ].isPiece() == true) { ChessPiece pieceRemoved = (board.point)[endI][endJ].getPiece(); (board.point)[endI][endJ].reMovePiece(pieceRemoved, board); board.repaint(); (board.point)[endI][endJ].setPiece(piece, board); (board.point)[startI][startJ].set有棋子(false); board.repaint(); } else { (board.point)[endI][endJ].setPiece(piece, board); (board.point)[startI][startJ].set有棋子(false); } String 棋子类别= piece.棋子类别(); String name = piece.getName(); String m = "#" + 棋子类别+ name + ": " + startI + numberToLetter(startJ) + " 到" + endI + numberToLetter(endJ); text.append(m); if (piece.棋子类别().equals(board.黑方颜色)) text.append("/n"); } public void 演示结束(String message) { splitH.remove(board); splitH.setDividerSize(5); splitH.setDividerLocation(460); JLabel label = new JLabel(message); label.setFont(new Font("隶书", Font.BOLD, 40)); label.setForeground(Color.blue); label.setHorizontalAlignment(SwingConstants.CENTER); splitH.setLeftComponent(label); splitH.validate(); } }四、总结与要求
1.理解8个文件,没有太复杂的代码。
2.理解鼠标的MouseListener,MouseMotionListener两个接口的区别,五子棋的实现不需要MouseMotionListener。
3.使用LinkedList记录棋谱的方法。
希望大家喜欢这篇文章,制作一款属于自己的中国象棋游戏。