Este artículo describe el código de juego de ajedrez chino implementado por Java. Se comparte con usted para su referencia. El código específico es el siguiente
1. Propósito práctico:
1. Aplicación y diferencia entre el clic del mouse, la arrastre y otros eventos
2. Guardar y leer los archivos de registro de ajedrez
3. Mejore las reglas del ajedrez.
2. Contenido práctico:
El ajedrez chino tiene una larga historia y ha atraído a innumerables personas para estudiar. Ahora hemos realizado el siguiente diseño y explicación de las batallas del ajedrez chino y la producción de puntajes de ajedrez para su referencia y aprendizaje.
1. Al jugar al ajedrez entre máquinas y máquinas, el lado rojo toma la delantera. Arrastre la pieza de ajedrez al destino si cumple con las reglas y se deja caer la ardilla.
Todos tocan el ajedrez
2. Haz un registro de ajedrez. Después de seleccionar el menú de registro de ajedrez, comienza el juego y se registra el proceso de ajedrez.
Seleccione el menú "hacer registro de ajedrez"
El lado rojo ganó después de que se terminó el puntaje de ajedrez
Después de que un lado gana, aparece el cuadro de diálogo Mensaje de victoria. Después de hacer clic en Aceptar, seleccione el menú "Guardar registro de ajedrez" y aparece el cuadro de diálogo Guardar archivo.
Guardar el cuadro de diálogo Registro de ajedrez
3. Demuestre el puntaje de ajedrez. Después de seleccionar el menú de puntuación de ajedrez de demostración, aparece un cuadro de diálogo abierto, seleccione la puntuación de ajedrez guardada para comenzar la demostración.
Demuestre el cuadro de diálogo Registro de ajedrez
Demostrar el proceso de registro de ajedrez (automático y manual)
3. Código de referencia:
1. Ajedrez Archivo principal chineseChess.java
paquete cn.edu.ounc.ChineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.linkedlist; / ** * clase principal de ajedrez * * @author cnlht */ public class chineseChess extiende jFrame implementos ActionListener {Boardboard Board = null; Demon demon = nulo; Makechessmanual registro = nulo; Contenedor con = nulo; Bar JMenubar; JMenu Filemenu; JMenuitem hace que la puntuación de ajedrez, salte el puntaje de ajedrez, demuestre el puntaje de ajedrez; Jfilechooser filechooser = null; LinkedList Chess stork = null; public chineseChess () {bar = new JMenubar (); fileMenu = new JMenu ("Ajedrez chino"); Hacer puntaje de ajedrez = new JMenuitem ("hacer puntaje de ajedrez"); Guardar el puntaje de ajedrez = new JMenuitem ("Guardar el puntaje de ajedrez"); Guardar el puntaje de ajedrez.setEnabled (falso); Puntaje de ajedrez de demostración = nuevo JMenuitem ("Puntuación de ajedrez de demostración"); fileMenu.add (hacer puntaje de ajedrez); fileMenu.Add (Save Save Chess Puntore); fileMenu.add (demuestre la puntuación de ajedrez); bar.add (fileMenu); setJMenubar (bar); settitle (hacer clases de ajedrez.gettext ()); hacer puntaje de ajedrez.addactionListener (esto); Guardar el puntaje de ajedrez.addactionListener (esto); demostrar la puntuación de ajedrez.addactionListener (esto); tablero = nuevo tablero de ajedrez (45, 45, 9, 10); registro = board.Record; con = getContentPane (); JSplitPane Split = new JSplitPane (jsplitpane.horizontal_split, true, board, registro); split.setDividersize (5); split.SetDividerLocation (460); Con.add (Split, BorderLayout.Center); addWindowlistener (new WindowAdapter () {public void WindowClosing (WindowsEvent E) {System.exit (0);}}); setVisible (verdadero); SetBounds (60, 20, 690, 540); fileCooser = new Jfilechooser (); con.validate (); validar(); } public void ActionPerformed (ActionEvent E) {if (e.getSource () == Make Chess Score) {con.RemoveAll (); Guardar el puntaje de ajedrez.setEnabled (verdadero); this.settitle (cree ajedrez score.gettext ()); tablero = nuevo tablero de ajedrez (45, 45, 9, 10); registro = board.Record; JSplitPane Split = new JSplitPane (jsplitpane.horizontal_split, true, board, registro); split.setDividersize (5); split.SetDividerLocation (460); Con.add (Split, BorderLayout.Center); validar(); } if (e.getSource () == Save Chess Score) {int state = fileChooser.showsavedialog (nulo); Archivo saveFile = fileCooser.getSelectedFile (); if (saveFile! = null && state == jfilechooser.approve_option) {try {fileOutputStream outone = new FileOutputStream (SaveFile); ObjectOutputStream outTWO = new ObjectOutputStream (outone); outTWO.WriteObject (registro.get Chess score ()); outone.close (); outTwo.Close (); } catch (Event ioException) {}}} if (e.getSource () == Demuestre el puntaje de ajedrez) {Con.RemoveAll (); con.Repaint (); con.validate (); validar(); guardar el puntaje de ajedrez.setEnabled (falso); int state = fileCooser.showopendialog (nulo); Archivo OpenFile = FileCooser.getSelectedFile (); if (OpenFile! = NULL && state == jfilechooser.approve_option) {try {fileInputStream inoNe = new FileInputStream (OpenFile); ObjectInputStream intwo = new ObjectInputStream (inoNe); Ajedrez = (LinkedList) intwo.readObject (); inoNe.close (); intwo.close (); Tablero de ajedrez = nuevo tablero de ajedrez (45, 45, 9, 10); demonio = nuevo demonio (tablero); Demon.set Registro de ajedrez (registro de ajedrez); Con.add (demonio, borderLayout.center); con.validate (); validar(); this.settitle (Demo Chess Record.gettext () + ":" + OpenFile); } catch (Event de excepción) {JLabel Label = new JLabel ("No archivo de registro de ajedrez"); etiqueta Label.setForeground (color.red); etiqueta.sethorizontalalignment (swingconstants.center); con.add (etiqueta, borderLayout.center); con.validate (); this.settitle ("No registro de ajedrez"); validar(); }} else {JLabel Label = new JLabel ("No se abre ningún archivo de registro de ajedrez"); etiqueta Label.setForeGround (color.pink); etiqueta.sethorizontalalignment (swingconstants.center); con.add (etiqueta, borderLayout.center); con.validate (); this.settitle ("El archivo de ajedrez no está abierto"); validar(); }}} public static void main (string args []) {new ChineseChess (); }} 2. Archivo Java.Java
paquete cn.edu.ounc.ChineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; / ** * clase de tablero de ajedrez * * @author cnlht */ public class Chessboard extiende jpanel implementa mouselistener, mouseMotionListener {public thesspoint Point [] []; Public int Unitwidth, UnithEight; Longitud privada del eje int x, longitud del eje y; privado int x, y; imagen privada img; Imagen protegida Pieceimg; movimiento booleano privado = falso; cadena pública color rojo cuadrado = "cuadrado rojo", color cuadrado negro = "cuadrado negro"; Peque de ajedrez carro rojo 1, carrito rojo 2, caballo rojo 1, caballo rojo 2, caballo rojo 1, caballo rojo 2, caballo rojo 3, soldados rojos 4, soldados rojos 5, cañón rojo 1, cañón rojo 2; Cartero negro Cart 1, carro negro 2, caballo negro 1, caballo negro 2, negro general, soldados negros 1, soldados negros 2, soldados negros 3, soldados negros 4, soldados negros 5, elefante negro 1, elefante negro 2, pistola negra 1, cañón negro 2; int iniciox, starty; int inicio, startj; Public Boolean Red Side Chess = True, Ajedrez del lado negro = falso; Regla regla = nulo; registro público de MakechessManual = NULL; Public Chessboard (int w, int h, int r, int c) {setLayout (null); addMouselistener (esto); AddMousEmotionListener (esto); Color bc = getBackground (); Unitwidth = W; UnithEight = H; longitud del eje x = r; longitud del eje y = c; punto = nuevo punto de ajuste [r + 1] [c + 1]; for (int i = 1; i <= r; i ++) {for (int j = 1; j <= c; j ++) {punto [i] [j] = new Chesspoint (i * unitwidth, j * unithEight, falso); }} regla = nueva regla (este, punto); registro = nuevo makechessmanual (this, punto); img = Toolkit.getDefaultToolkit (). getImage ("board.jpg"); PieceImg = Toolkit.getDefaultToolkit (). GetImage ("Piece.gif"); coche rojo 1 = nuevo ajedrez ("", color.red, bc, w - 4, h - 4, esto); Coche rojo 1. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Coche rojo 2 = nueva pieza de ajedrez ("", color.red, bc, w - 4, h - 4, esto); Coche rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Caballo rojo 1 = nuevo ajedrez ("", color. Red, BC, W - 4, H - 4, esto); Caballo rojo 1 = nuevo ajedrez ("", color. Red, BC, W - 4, H - 4, esto); Horse rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Cañón rojo 1 = nueva pieza de ajedrez ("火", color.rod, bc, w - 4, h - 4, esto); Categoría de la pieza de ajedrez del conjunto rojo (color cuadrado rojo); Cañón rojo 2 = nueva pieza de ajedrez ("火", color.rod, BC, W - 4, H - 4, esto); Categoría de la pieza de ajedrez del conjunto rojo (color rojo cuadrado); Cañón rojo 1 = nueva pieza de ajedrez ("火", color.rod, bc, w - 4, h - 4, esto); Categoría de la pieza de ajedrez del conjunto rojo (color cuadrado rojo); Cañón rojo 2 = nueva pieza de ajedrez ("火", color.rod, BC, W - 4, H - 4, esto); Categoría de la pieza de ajedrez del conjunto rojo (color cuadrado rojo); Cañón rojo 2 = nueva pieza de ajedrez ("火", color.rod, BC, W - 4, H - 4, esto); Rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Rojo 1 = nuevo ajedrez ("shi", color.red, bc, w - 4, h - 4, esto); Categoría de la pieza de ajedrez rojo 1.Set (color cuadrado rojo); Rojo 2 = nuevo ajedrez ("shi", color.red, bc, w - 4, h - 4, esto); Rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Rojo 2 = nuevo ajedrez ("shi", color.red, bc, w - 4, h - 4, esto); Rojo 1 = nuevo ajedrez ("shi", color.red, bc, w - 4, h - 4, esto); Soldado rojo 1. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Red Soldier 2 = nuevo ajedrez ("soldado", color. Red, BC, W - 4, H - 4, esto); Soldado rojo 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Soldado rojo 3 = nueva pieza de ajedrez ("soldado", color. Red, BC, W - 4, H - 4, esto); Soldado rojo 3 = nueva pieza de ajedrez ("soldado", color. Red, BC, W - 4, H - 4, esto); Red Soldier 4. Categoría de piezas de ajedrez del conjunto (color cuadrado rojo); Red Soldier 5 = nuevo ajedrez ("soldado", color. Red, BC, W - 4, H - 4, esto); Soldado rojo 5. Categoría de la pieza de ajedrez del conjunto (color cuadrado rojo); Soldado negro = nuevo ajedrez ("vendido", color.black, bc, w - 4, h - 4, esto); Soldado negro 1 = nuevo ajedrez ("soldado", color.black, bc, w - 4, h - 4, esto); Soldado negro 1 = nuevo ajedrez ("soldado", color.black, bc, w - 4, h - 4, esto); Soldado negro 1 = nuevo ajedrez ("auto", color.black, bc, w - 4, h - 4, esto); CARCHO NEGRO 1. Categoría de la pieza de ajedrez del conjunto (color cuadrado negro); Coche negro 2 = nuevo ajedrez ("auto", color.black, bc, w - 4, h - 4, esto); CARCULO NEGRO 2. Categoría de la pieza de ajedrez del conjunto (color cuadrado negro); Cannon negro 1 = nueva pieza de ajedrez ("cañón", color.black, bc, w - 4, h - 4, esto); Categoría de la pieza de ajedrez del cañón negro (color cuadrado negro); Black Cannon 2 = nuevo ajedrez ("cañón", color.black, bc, w - 4, h - 4, esto); Categoría de la pieza de ajedrez del cañón negro (color cuadrado negro); Elefante negro 1 = nuevo ajedrez ("elefante", color.black, bc, w - 4, h - 4, esto); Elefante negro 1. Categoría de la pieza de ajedrez del conjunto (color cuadrado negro); Elefante negro 2 = nuevo ajedrez ("elefante", color.black, bc, w - 4, h - 4, esto); Elephant negro 2. Categoría de pieza de ajedrez del conjunto (color cuadrado negro); Elefante negro 1 = nuevo ajedrez ("elefante", color.black, bc, w - 4, h - 4, esto); Elefante negro 1. Categoría de la pieza de ajedrez del conjunto (color cuadrado negro); Elefante negro 2 = nuevo ajedrez ("elefante", color.black, bc, w - 4, h - 4, esto); Horse negro 2. Categoría de piezas de ajedrez del conjunto (color negro); Pantalones negros 1 = nuevo ajedrez ("zhi", color.black, bc, w - 4, h - 4, esto); Pantalones negros 1. Categoría de la pieza de ajedrez del conjunto (color negro); Pantalones negros 2 = nuevo ajedrez ("Zhi", color.black, BC, W - 4, H - 4, esto); Pantalones negros 2. Categoría de piezas de ajedrez del conjunto (color negro); Pantalones negros 3 = nuevo ajedrez ("zhi", color.black, bc, w - 4, h - 4, esto); Pantalones negros 3. Categoría de piezas de ajedrez del conjunto (color negro); Pantalones negros 4 = nuevo ajedrez ("zhi", color.black, bc, w - 4, h - 4, esto); BLACK PHANTOM 4.Set Categoría de piezas de ajedrez (color cuadrado negro); Negro Phantom 5 = nuevo ajedrez ("zhi", color.black, bc, w - 4, h - 4, esto); BLACK PHANTOM 5.Set Piece de ajedrez (color cuadrado negro); punto [1] [10] .SetPiece (carro rojo 1, esto); punto [2] [10] .SetPiece (caballo rojo 1, esto); punto [3] [10] .SetPiece (fase roja 1, esto); punto [4] [10] .SetPiece (Sabio rojo 1, esto); punto [4] [10] .SetPiece (Sabio rojo 1, esto); punto [4] [10] .SetPiece (Sabio rojo 1, esto); punto [5] [10] .SetPiece (soldado rojo, esto); punto [6] [10] .SetPiece (Red Soldier 2, esto); punto [7] [10] .SetPiece (Red Soldier 2, esto); punto [8] [10] .SetPiece (caballo rojo 2, esto); punto [9] [10] .SetPiece (Red Soldier 2, esto); punto [2] [8] .SetPiece (Red Soldier 1, esto); punto [8] [8] .SetPiece (Red Soldier 2, esto); punto [1] [7] .SetPiece (Red Soldier 2, esto); punto [3] [7] .SetPiece (Red Soldier 2, esto); punto [3] [7] .SetPiece (Red Soldier 2, esto); punto [3] [7] .SetPiece (Red Soldier 2, esto); punto [5] [7] .SetPiece (Red Soldier 3, esto); punto [7] [7] .SetPiece (Red Soldier 4, esto); punto [9] [7] .SetPiece (Red Soldier 5, esto); punto [1] [1] .SetPiece (auto negro 1, esto); punto [2] [1] .SetPiece (Horse negro 1, esto); punto [3] [1] .SetPiece (elefante negro 1, esto); punto [4] [1] .SetPiece (elefante negro 1, esto); punto [5] [1] .SetPiece (Black General, esto); punto [6] [1] .SetPiece (elefante negro 1, esto); punto [4] [1] .SetPiece (negro general 1, esto); punto [5] [1] .SetPiece (Black General 2, esto); punto [6] [1] .SetPiece (Black General 2, esto); punto [7] [1] .SetPiece (elefante negro 2, esto); punto [8] [1] .SetPiece (Horse negro 2, esto); punto [9] [1] .SetPiece (CAR negro 2, esto); punto [2] [3] .SetPiece (cañón negro 1, esto); punto [8] [3] .SetPiece (cañón negro 2, esto); punto [1] [4] .SetPiece (cañón negro 1, esto); punto [3] [4] .SetPiece (cañón negro 2, esto); punto [5] [4] .SetPiece (cañón negro 3, esto); punto [7] [4] .SetPiece (cañón negro 4, esto); punto [7] [4] .SetPiece (cañón negro 4, esto); punto [3] [4] .SetPiece (cañón negro 4, esto); punto [5] [4] .SetPiece (cañón negro 3, esto); punto [7] [4] .SetPiece (cañón negro 4, esto); punto [9] [4] .SetPiece (bolso negro 5, esto); } public void PaintComponent (Graphics g) {super.PaintComponent (g); int imgwidth = img.getWidth (this); int imgheight = img.getheight (this); // Obtener el ancho y la altura de la imagen int fwidth = getWidth (); int fheight = getheight (); // Obtener el ancho y la altura de la ventana int x = (fwidth - imgwidth)/ 2; int y = (fheight - imghEight) / 2; G.Drawimage (img, x, y, nulo); for (int j = 1; j <= y-eje longitud; j ++) {g.drawline (punto [1] [j] .x, punto [1] [j] .y, punto [longitud del eje x] [j] .x, punto [longitud del eje x] [j] .y); } para (int i = 1; i <= x-exis longitud; i ++) {if (i! = 1 && i! = x-exis longitud) {g.drawline (punto [i] [1] .x, punto [i] [1] .y, punto [i] [y-eexis longitud-5] .x, punto [i] [y-eje longitud-5] .y); g.drawline (punto [i] [longitud del eje y 4] .x, punto [i] [longitud del eje y-4] .y, punto [i] [longitud del eje y] .x, punto [i] [longitud del eje y] .y); } else {g.drawline (punto [i] [1] .x, punto [i] [1] .y, punto [i] [longitud del eje y] .x, punto [i] [longitud del eje y] .y); }} G.Drawline (punto [4] [1] .x, punto [4] [1] .y, punto [6] [3] .x, punto [6] [3] .y); G.Drawline (punto [6] [1] .x, punto [6] [1] .y, punto [4] [3] .x, punto [6] [1] .y, punto [4] [3] .x, punto [4] [3] .y); G.Drawline (punto [4] [8] .x, punto [4] [8] .y, punto [6] [longitud del eje y] .x, punto [6] [longitud del eje y] .y); G.Drawline (punto [4] [longitud del eje y] .x, punto [4] [longitud del eje y] .y, punto [6] [8] .x, punto [6] [8] .y); para (int i = 1; i <= x-eje longitud; 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 ++; }} / ** Evento de prensa de mouse* / public void mousePressed (mouseEvent e) {ajedrez pieces = null; Rectángulo rect = nulo; if (e.getSource () == this) Move = false; if (Move == False) if (e.getSource () instancia de ajuste de ajedrez) {piezas = (ajedrez) E.getSource (); startx = pie.getBounds (). x; starty = pie.getBounds (). Y; rect = Piece.getBounds (); para (int i = 1; i <= x-eje longitud; i ++) {for (int j = 1; j <= y-eje longitud; j ++) {int x = punto [i] [j] .getx (); int y = punto [i] [j] .gety (); if (rect.contains (x, y)) {starti = i; startj = j; romper; }}}}}} public void mouseMoved (MouseEvent E) {} / ** Evento de arrastre de mouse* / public void MousedRagged (MouseEvent E) {Piece de ajedrez = null; if (e.getSource () instancia de ajedrez) {pieza = (ajedrez) e.getSource (); mover = verdadero; e = swingUtility.convertMouseVent (pieza, e, este); } 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); }}}} / ** Evento de ratón de liberación* / public void MouserelEmented (MouseEvent E) {PIEZA DE CHESSPIET = NULL; mover = falso; Rectángulo rect = nulo; if (e.getSource () instancia de ajedrez) {pieza = (ajedrez) E.getSource (); rect = Piece.getBounds (); e = swingUtility.convertMouseVent (pieza, e, este); } if (e.getSource () == this) {boolean contenschesspoint = false; int x = 0, y = 0; int m = 0, n = 0; if (pie! = null) {for (int i = 1; i <= x-eje longitud; i ++) {for (int j = 1; j <= y-eje longitud; j ++) {x = punto [i] [j] .getx (); y = punto [i] [j] .gety (); if (rect.contains (x, y)) {contenerChessPoint = true; m = i; n = j; romper; }}}}} if (Piece! = Null && ContAnsChessPoint) {color piezas = pie if (punto [m] [n] .Ispiece ()) {color c = (punto [m] [n] .getPiece ()). Obtener color de ajedrez (); if (titelor.getRgb () == c.getrgb ()) {Piece.setLocation (startx, starty); (punto [starti] [startj]). set tiene piezas de ajedrez (verdaderas); } else {boolean ok = rule.movePiecerule (pieza, starti, startj, m, n); if (ok) {ajhespiece Priteremoved = Point [m] [n] .getPiece (); punto [m] [n] .removePiece (Priteremoved, esto); punto [m] [n] .setPiece (pieza, esta); (punto [starti] [startj]). set tiene piezas de ajedrez (falsas); Record.Record Chess Score (Piece, Starti, StartJ, M, N); registrar. Recorre las piezas de ajedrez comidas (a paso a paso); regla.iswine (Priteremed); 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 (); repintado (); } else {Piece.setLocation (startx, starty); (punto [starti] [startj]). set tiene piezas de ajedrez (verdaderas); }}} else {boolean ok = rule .movePiecerule (pieza, starti, startj, m, n); if (ok) {punto [m] [n] .setPiece (pieza, esto); (punto [starti] [startj]). set tiene piezas de ajedrez (falsas); Record.Record Chess Score (Piece, Starti, StartJ, M, N); Record.Record Piezas de ajedrez comidas ("Sin piezas de ajedrez"); if (Piece.paper Category (). Equals (Red Square Color)) {Red Square Achess = False; Ajedrez cuadrado negro = verdadero; } if (Piece.paper Category (). Equals (Black Square Color)) {Black Square Achess = False; Ajedrez cuadrado rojo = verdadero; }} else {piezas.setLocation (startx, starty); (punto [starti] [startj]). set tiene piezas de ajedrez (verdaderas); }}} if (Piece! = Null &&! ContenceChessPoint) {Piece.setLocation (startx, starty); (punto [starti] [startj]). set tiene piezas de ajedrez (verdaderas); }}} public void mouseentered (mouseevent e) {} public void mouseExited (mouseevent e) {} public void mouseClicked (mouseevent e) {}} 3. Archivo Java.
paquete cn.edu.ounc.ChineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; / ** * clase de ajedrez * * @author cnlht */ public classpiece de ajedrez extiende jlabel {name de cadena; // Nombre del ajedrez Color BackColor = Null, ForeColor; // Categoría de color de la cadena de color y en primer plano Color = NULL; Tablero de ajedrez = nulo; inthip, altura; // tamaño de ajedrez público (nombre de cadena, color fc, color bc, int ancho, int altura, placa de tablero de ajedrez) {// construye la pieza de ajedrez this.name = name; this.board = tablero; this.width = ancho; this.Height = altura; pronóstico = fc; backcolor = bc; setSize (ancho, altura); Segfraackground (BC); AddMousEmotionListener (Junta); addMousElistener (tablero); } // Dibuja la pieza de ajedrez public void Paint (Graphics G) {G.DrawImage (Board.PieceMg, 2, 2, ancho-2, altura-2, nulo); G.SetColor (forecolor); G.SetFont (nueva fuente ("kaiti", font.bold, 26)); G.DrawString (nombre, 7, altura - 8); // Dibuja "Nombre del ajedrez" en la pieza de ajedrez G.SetColor (color.black); //g.Drawoval(1, 1, ancho - 1, altura - 1); flotante linewidth = 2.3f; ((Graphics2d) G) .SetStroke (nuevo BasicStroke (LineWidth)); ((Graphics2d) G) .Drawoval (2, 2, ancho-2, altura-2); } public int getwidth () {Width de retorno; } public int getheight () {altura de retorno; } public String getName () {nombre de retorno; } Color público Obtenga el color de ajedrez () {return ForeColor; } Categoría de ajedrez de set public void (categoría de cadena) {categoría de color = categoría; } categoría de ajedrez de cadena pública () {categoría de color return; }} 4. Archivo de coordenadas de punto de ajuste
paquete cn.edu.ounc.ChineseChess; / *** clase de punto de ajedrez** @author cnlht*/ public class Chesspoint {/ ** Coordenadas de correos*/ int x, y; / ** ¿Esta coordenada tiene una pieza*/ boolean tiene una pieza; /** PIEZA DE CORTE DE CARDE = NULL; / ** TODA DE ACHESS A ALTRO COORDINATION PERTILE*/ BOLDBORDOBLO = NULL; Public Chesspoint (int x, int y, boolean boo) {this.x = x; this.y = y; Tener una pieza = boo; } public boolean isPiece () {return hay piezas de ajedrez; } Public void set tiene piezas de ajedrez (boolean boo) {Pieces de ajedrez = boo; } public int getx () {return x; } public int gety () {return y; } // Establecer puntos de cambio en piezas de ajedrez public void setPiece (pieza de ajedrez, placa de tablero de ajedrez) {this.board = board; this.piece = pieza; junta.Add (pieza); int w = (board.unitwidth); int h = (board.unitheTight); Piece.setBounds (x - w / 2, y - h / 2, w, h); // posición de pieza de ajedrez, ancho, altura con piezas de ajedrez = verdadero; junta.validate (); } publicidad de ajedrez pública getPiece () {pieza de retorno; } public void RemoLePiece (pieza de colchón de ajedrez, placa de tablero de ajedrez) {this.board = board; this.piece = pieza; junta.remove (pieza); junta.validate (); Piezas de ajedrez = falso; }} 5. Regla de archivo de clase de regla de juego. Java
paquete cn.edu.ounc.ChineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; / ** * clase de reglas de juego de ajedrez * * @author cnlht */ public class regla {Chessboard Board = null; Pieza de ajedrez = nulo; Punto de punto de ajuste [] []; int inicio, startj, endi, endj; Regla pública (Jessboard Board, Chesspoint Point [] []) {this.board = board; this.Point = Point; } public void iswine (pieza de ajedrez) {this.piece = pieza; if (pie.getName () == "Alineado" || Piece.getName () == "Handy") {if (Piece.Color Category == "Lado rojo") {jOptionPane.ShowMessEdialog (NULL, "Victoria del lado negro!"); } else {joptionPane.ShowMessEdialog (NULL, "¡Victoria del lado rojo!"); }}} public boolean MovePiecerule (Piece de correos de ajedrez, int inicio, int inicioj, int endi, int endj) {this.piece = pieza; 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); booleano ¿puedes jugar ajedrez = falso; if (pie.getName (). Equals ("Car")) {if (starti == endi) {int j = 0; para (j = minj+1; j <= maxj - 1; j ++) {if (punto [starti] [j] .ispiece ()) {¿Puedes mover ajedrez = falso; romper; }} if (j == maxj) {¿Puedes mover ajedrez = true; }} else if (startj == endj) {int i = 0; para (i = mini+1; i <= maxi - 1; i ++) {if (punto [i] [startj] .ispiece ()) {¿Puedes mover ajedrez = falso; romper; }} if (i == maxi) {¿Puedes mover ajedrez = true; }} else {¿Puedes mover ajedrez = falso; }}} else if (pie.getName (). Equals ("")) {if (starti == endi) {int j = 0; para (j = minj+1; j <= maxj - 1; j ++) {if (punto [starti] [j] .ispiece ()) {¿Puedes mover ajedrez = falso; romper; }} if (j == maxj) {¿Puedes mover ajedrez = true; }} else if (startj == endj) {int i = 0; para (i = mini+1; i <= maxi - 1; i ++) {if (punto [i] [startj] .ispiece ()) {¿Puedes mover ajedrez = falso; romper; }} if (i == maxi) {puedo mover el ajedrez = true; }} else {¿Puedo mover ajedrez = falso; }} else if (pie.getName (). Equals ("ma")) {int xaxle = math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (xaxle == 2 && yaxle == 1) {if (endi> starti) {if (punto [starti + 1] [startj] .IsPiece ()) {puedo mover ajedrez = falso; } else {¿Puedo mover el ajedrez = true; }} if (endi <starti) {if (punto [starti - 1] [startj] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }}} else if (xaxle == 1 && yaxle == 2) {if (endj> startj) {if (point [starti] [startj + 1] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }} if (endj <startj) {if (punto [starti] [startj - 1] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }} if (endj <startj) {if (punto [starti] [startj - 1] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; } verdadero; }}} else {¿Puedo mover el ajedrez = falso; }} else if (pie.getName (). Equals ("")) {int xaxle = math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (xaxle == 2 && yaxle == 1) {if (endi> starti) {if (punto [starti + 1] [startj] .IsPiece ()) {puedo mover ajedrez = falso; } else {¿Puedo mover el ajedrez = true; }} if (endi <starti) {if (punto [starti - 1] [startj] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }}} else if (xaxle == 1 && yaxle == 2) {if (endj> startj) {if (point [starti] [startj + 1] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }} if (endj <startj) {if (punto [starti] [startj - 1] .IsPiece ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }}} else {¿Puedes mover ajedrez = falso; }} else if (pie.getName (). Equals ("icon")) {int centroi = (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 (punto [centeri] [centerj] .ispec ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }} else {¿Puedes mover ajedrez = falso; }} else if (pie.getName (). Equals ("fase")) {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 (punto [centeri] [centerj] .ispec ()) {¿puede mover ajedrez = falso; } else {¿Puedes mover ajedrez = verdadero; }} else {¿Puedes mover ajedrez = verdadero; }} else {¿Puedes mover ajedrez = verdadero; }} else {¿Puedes mover ajedrez = falso; }} else if (pie.getName (). Equals ("Cannon")) {int number = 0; if (starti == endi) {int j = 0; para (j = minj+1; j <= maxj - 1; j ++) {if (punto [starti] [j] .ispiece ()) {número ++; }} if (número> 1) {¿puede mover ajedrez = falso; } else if (número == 1) {if (punto [endi] [endj] .IsPiece ()) {¿Puedes mover ajedrez = verdadero; }} else if (número == 0 &&! Point [endi] [endj] .IsPiece ()) {¿Puedes mover ajedrez = verdadero; }} else if (startj == endj) {int i = 0; para (i = mini+1; i <= maxi - 1; i ++) {if (punto [i] [startj] .ispiece ()) {número ++; }} if (número> 1) {¿puede mover ajedrez = falso; } else if (número == 1) {if (punto [endi] [endj] .IsPiece ()) {¿Puedes mover ajedrez = verdadero; }} else if (número == 0 &&! Point [endi] [endj] .IsPiece ()) {¿Puedes mover ajedrez = verdadero; }} else {¿Puedes mover ajedrez = falso; }} else if (pie.getName (). Equals ("Soldier")) {int xaxle = Math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (endj> = 6) {if (startj - endj == 1 && xaxle == 0) {¿Puedes mover ajedrez = verdadero; } else {¿Puedes mover ajedrez = falso; }} else if (endj <= 5) {if ((startj - endj == 1) && (xaxle == 0)) {puedo mover el ajedrez = true; } else if ((endj - startj == 0) && (xaxle == 1)) {puedo mover el ajedrez = true; } else {¿Puedo mover ajedrez = falso; }}} else if (pie.getName (). Equals ("zhi")) {int xaxle = math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (endj <= 5) {if (endj - startj == 1 && xaxle == 0) {puedo mover el ajedrez = true; } else {¿Puedes mover ajedrez = falso; }} else if (endj> = 6) {if ((endj - startj == 1) && (xaxle == 0)) {¿puede mover el ajedrez = true; } else if ((endj - startj == 0) && (xaxle == 1)) {¿puede mover ajedrez = true; } else {¿Puedes mover ajedrez = falso; }}} else if (pie.getName (). Equals ("shi")) {int xaxle = math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (endi <= 6 && endi> = 4 && xaxle == 1 && yaxle == 1) {¿puede mover ajedrez = true; } else {¿Puedes mover ajedrez = falso; }} else if (pie.getName (). Equals ("State")) {int xaxle = Math.abs (starti - endi); int yaxle = math.abs (startj - endj); if (endi <= 6 && endi> = 4 && xaxle == 1 && yaxle == 1) {¿puede mover ajedrez = true; } else {¿Puedes mover ajedrez = falso; }} else if ((Piece.getName (). Equals ("Handsome")) || (Piece.getName (). Equals ("Reemplazar"))) {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)) {puede mover ajedrez = true; } else {¿Puedes mover ajedrez = falso; }} else {¿Puedes mover ajedrez = falso; }} return ¿Puede mover el ajedrez? }} 6. archivo mOveStep.java
paquete cn.edu.ounc.ChineseChess; import java.awt.point; / ** * Clase de caminar * * @author cnlht * */ public class MoveStep implementa java.io.Serializable {public Point PStart, Pend; Public MoveStep (Point P1, Point P2) {pStart = P1; pend = p2; }} 7. Haga de Chessmanual.java
paquete cn.edu.ounc.ChineseChess; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.linkedlist; / ** * hacer clases de registro de ajedrez * * @author cnlht */ public class MakechessManual extiende jpanel implementos actionListener {jtexTarea text = null; JSCrollPane Scroll = NULL; Tablero de ajedrez = nulo; Punto de Chesspoint [] []; LinkedList Chess Note = null; Linkedlist Eated Chess Pieces = Null; JButton ButtonUdo; int i = 0; Public MakechessManual (Jessboard Board, Chesspoint [] [] Point) {this.board = board; this.Point = Point; text = new JTextArea (); scroll = new JScrollPane (texto); Nota de ajedrez = new LinkedList (); Piezas de ajedrez comidas = new LinkedList (); ButtonUndo = new JButton ("Ajedrez de Arrepent"); ButtonUdo.setFont (nueva fuente ("lishu", font.plain, 18)); setLayout (new BorderLayout ()); agregar (desplazarse, borderLayout.center); Agregar (ButtonUdo, BorderLayout.South); ButtonUdo.AddactionListener (this); } public Char numberToletter (int n) {char c = '/0'; switch (n) {caso 1: c = 'a'; romper; caso 2: c = 'b'; romper; Caso 3: c = 'c'; romper; Caso 4: c = 'd'; romper; Caso 5: C = 'E'; romper; caso 6: c = 'f'; romper; Caso 7: C = 'G'; romper; Caso 8: C = 'H'; romper; Caso 9: c = 'i'; romper; Caso 10: c = 'j'; romper; } return c; } Public void Record Chess Score (Piece de ajedrez, int inicio, int inicioj, int endi, int endj) {Point pStart = new Point (starti, startj); Punto pend = nuevo punto (endi, endj); MoveStep step = new MoveStep (PStart, Pend); Puntaje de ajedrez.add (paso); Categoría de ajedrez de cadena = Piece.Chess Category (); Name de cadena = pieza.getName (); Cadena m = "#" + categoría de ajedrez + nombre + ":" + starti + numberToletter (startj) + "a" + endi + numberToletter (endj); text.append (m); if (pieza. Categoría de ajedrez (). Equals (Board.Black Square Color)) Text.append ("/n"); } public void registro la pieza de ajedrez comida (objeto objeto) {comed Achess Piece.Add (objeto); } public LinkedList obtenga la pieza de ajedrez () {return Chess Piece; } public void ActionPerformed (ActionEvent E) {int Position = Text.Gettext (). LastIndexOf ("#"); if (posición! = -1) text.replacRange ("", posicion, text.gettext (). longitud ()); if (Chess Piece.Size ()> 0) {Movestep LastStep = (Movestep) Piece de ajedrez.getLast (); Ajedrez registro.removelast (); Objeto qizi = Eated Chess Piece.getLast (); Pieza de ajedrez comida.removelast (); Cadena temp = qizi.ToString (); if (temp.equals ("No Piece de ajedrez")) {int inicio = laststep.pstart.x; int startj = laststep.pstart.y; int endi = laststep.pend.x; int endj = laststep.pend.y; PIEZA DEL PIEZA DE CARDE = Point [Endi] [Endj] .getPiece (); punto [starti] [startj] .setPiece (pieza, placa); (punto [endi] [endj]). Set tiene piezas de ajedrez (falsas); 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; tablero. Red Square Move = False; }} else {CHESSPIEZ eliminada = (PIEZA DE CARDE) QIZI; int inicio = laststep.pstart.x; int startj = laststep.pstart.y; int endi = laststep.pend.x; int endj = laststep.pend.y; PIEZA DEL PIEZA DE CARDE = Point [Endi] [Endj] .getPiece (); punto [starti] [startj] .setPiece (pieza, placa); 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(Time interval.getText().trim()); } catch (NumberFormatException ee) { time = 1000; } if (!(automatic demonstration.isAlive())) {automatic demonstration = 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); automatic demonstration.start(); } } if (e.getSource() == stop) { if (e.getActionCommand().equals("Pause Demo")) { Demo process = "Pause Demo"; stop.setText("Continue Demo"); stop.repaint(); } if (e.getActionCommand().equals("Continue Demo")) { Demo process = "Continue Demo"; Automatic demonstration.interrupt(); stop.setText("Pause Demo"); stop.repaint(); } } } public synchronized void run() { for (index = 0; index < chess score.size(); index++) { try { Thread.sleep(time); } catch (InterruptedException e) { } while (Demo process.equals("Pause demo")) { try { wait(); } catch (InterruptedException e) { notifyAll(); } } Demo step(index); } if (index >= Chess Note.size()) { Demo end("Chess Note demonstration completed"); next.setEnabled(true); replay.setEnabled(true); } } public void Demo step(int index) { MoveStep step = (MoveStep) Chess Note.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 has chess pieces (false); board.repaint(); } else { (board.point)[endI][endJ].setPiece(piece, board); (board.point)[startI][startJ].set has chess pieces (false); } String chess piece category = piece.chess piece category(); String name = piece.getName(); String m = "#" + chess class + name + ": " + startI + numberToLetter(startJ) + " to " + endI + numberToLetter(endJ); text.append(m); if (piece. chess class().equals(board.black square color)) text.append("/n"); } public void demonstration end(String message) { splitH.remove(board); splitH.setDividerSize(5); splitH.setDividerLocation(460); JLabel label = new JLabel(message); label.setFont(new Font("Lishu", Font.BOLD, 40)); label.setForeground(Color.blue); label.setHorizontalAlignment(SwingConstants.CENTER); splitH.setLeftComponent(label); splitH.validate(); } }四、总结与要求
1.理解8个文件,没有太复杂的代码。
2.理解鼠标的MouseListener,MouseMotionListener两个接口的区别,五子棋的实现不需要MouseMotionListener。
3.使用LinkedList记录棋谱的方法。
希望大家喜欢这篇文章,制作一款属于自己的中国象棋游戏。