이 기사에서는 Java가 구현 한 중국 체스 게임 코드에 대해 설명합니다. 참조를 위해 귀하와 공유됩니다. 특정 코드는 다음과 같습니다
1. 실제 목적 :
1. 마우스 클릭, 드래그 및 기타 이벤트의 응용 및 차이
2. 체스 레코드 파일 저장 및 읽기
3. 체스의 규칙을 향상시킵니다.
2. 실제 콘텐츠 :
중국 체스는 오랜 역사를 가지고 있으며 수많은 사람들이 공부할 수있는 사람들을 끌어 들였습니다. 이제 우리는 중국 체스 전투와 참조 및 학습을위한 체스 점수 제작에 대한 다음과 같은 디자인과 설명을 만들었습니다.
1. 기계와 기계 사이에서 체스를 재생할 때 빨간색이 리드를 차지합니다. 규칙을 충족하고 다람쥐가 떨어지면 체스 조각을 목적지로 드래그하십시오.
모두가 체스를합니다
2. 체스 기록을 만드십시오. 체스 레코드 메뉴를 선택한 후 게임이 시작되고 체스 프로세스가 기록됩니다.
"체스 레코드 만들기"메뉴를 선택하십시오
체스 점수가 끝난 후 빨간색이 승리했습니다.
한쪽이 승리 한 후 승리 메시지 대화 상자가 나타납니다. 확인을 클릭 한 후 "체스 레코드 저장"메뉴를 선택하여 파일 저장 대화 상자를 나타냅니다.
체스 기록 대화 상자를 저장하십시오
3. 체스 점수를 보여줍니다. 데모 체스 스코어 메뉴를 선택한 후 열린 대화 상자가 나타나고 저장된 체스 점수를 선택하여 데모를 시작하십시오.
체스 레코드 대화 상자를 보여줍니다
체스 기록 과정을 보여줍니다 (자동 및 매뉴얼)
3. 참조 코드 :
1. 체스 메인 파일 chinesechess.java
패키지 cn.edu.ouc.chinesechess; javax.swing을 가져옵니다.*; java.awt.*; import java.awt.event.*; java.io.*; java.util.linkedList 가져 오기; / ** * 체스 메인 클래스 * * @author cnlht */ public class chinesechess는 jframe emplesments actionlistener {chessboard board = null; 악마 악마 = null; makechessmanual record = null; 컨테이너 con = null; Jmenubar 바; Jmenu filemenu; jmenuitem은 체스 점수를 올리고 체스 점수를 저장하고 체스 점수를 보여줍니다. JFILECHOOSER FILECHOOSER = NULL; 링크드리스트 체스 점수 = null; public chinesechess () {bar = new jmenubar (); filemenu = New Jmenu ( "중국 체스"); 체스 점수 = 새로운 jmenuitem ( "체스 점수 만들기"); 저장 체스 점수 = 새로운 jmenuitem ( "체스 점수 저장"); Chess Sc 데모 체스 점수 = 새로운 jmenuitem ( "데모 체스 점수"); filemenu.add (체스 점수 만들기); filemenu.add (체스 점수 저장); filemenu.add (체스 점수 시연); bar.add (filemenu); setjmenubar (bar); settitle (체스 make score.getText ()); 체스 점수를 만듭니다 .addactionListener (this); Chess Score.AdDactionListener (this) 저장; 체스 점수를 보여줍니다 .addactionListener (this); 보드 = 새로운 체스 판 (45, 45, 9, 10); 레코드 = 보드. 레코드; 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); 세트 바운드 (60, 20, 690, 540); filechooser = new jfilechooser (); con.validate (); validate (); } public void ActionPerformed (ActionEvent e) {if (e.getSource () == 체스 점수 make) {con.removeall (); Chess Score.setenabled (true) 저장; this.settitle (체스 score.getText () 만들기); 보드 = 새로운 체스 판 (45, 45, 9, 10); 레코드 = 보드. 레코드; 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 () == 체스 점수 저장) {int state = filechooser.showsavedialog (null); 파일 savefile = filechooser.getSelectedFile (); if (savefile! = null && state == jfileChooser.Approve_Option) {try {fileoutputStream OutOne = new FileOutputStream (SaveFile); ObjectOutputStream outtwo = 새로운 ObjectOutputStream (OutOne); outtwo.writeobject (record.get chess score ()); OUTONE.CLOSE (); outtwo.close (); } catch (ioexception event) {}}} if (e.getSource () == 체스 점수를 보여줍니다) {con.removeall (); con.repaint (); con.validate (); validate (); Chess Sc int state = filechooser.showopendialog (null); 파일 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); 악마 = 새로운 악마 (보드); 악마. 세트 체스 레코드 (체스 레코드); con.add (Demon, BorderLayout.Center); con.validate (); validate (); this.settitle (Demo Chess Record.getText () + ":" + OpenFile); } catch (예외 이벤트) {jlabel label = new Jlabel ( "체스 레코드 파일이 아님"); 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 ( "체스 기록 없음"); validate (); }} else {jlabel label = new Jlabel ( "체스 레코드 파일이 열리지 않음"); 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 ( "체스 파일이 열리지 않음"); validate (); }}} public static void main (String args []) {new chinesechess (); }} 2. Chessboard.java 파일
패키지 cn.edu.ouc.chinesechess; javax.swing을 가져옵니다.*; java.awt.*; import java.awt.event.*; / ** * Chessboard Class * * @author Cnlht */ public class chessboard 확장 jpanel 구현 mouselistener, mousemotionListener {public chesspoint point [] []; 공개 int -unitwidth, 단단한; 비공개 INT X 축 길이, y 축 길이; 개인 int x, y; 개인 이미지 IMG; 보호 된 이미지 조각; 개인 부울 이동 = 거짓; 공개 문자열 빨간 사각형 색상 = "빨간 사각형", 검은 색 정사각형 색상 = "검은 사각형"; 체스 피스 레드 카트 1, 레드 카트 2, 붉은 말 1, 레드 말 2, 레드 말 1, 레드 말 2, 붉은 말 3, 붉은 군인 4, 붉은 군인 5, 붉은 대포 1, 붉은 대포 2; 체스 피스 블랙 카트 1, 블랙 카트 2, 검은 말 1, 검은 말 2, 검은 장군 1, 검은 군인 2, 검은 군인 2, 검은 군인 3, 검은 병사 4, 검은 병사 5, 검은 코끼리 1, 검은 코끼리 2, 검은 총 1, 검은 대포 2; int startx, 스타디; int starti, startj; 공개 부울 붉은 사이드 체스 = 참, 검은 색 사이드 = 거짓; 규칙 규칙 = null; 공개 makechessmanual record = null; 공개 체스 보드 (int w, int h, int r, int c) {setlayout (null); AddMousElistener (this); AddMousEmotionListener (this); 색상 BC = getbackground (); initwidth = w; uneitheight = h; x 축 길이 = r; y 축 길이 = C; 포인트 = 새로운 체스 포인트 [R + 1] [C + 1]; for (int i = 1; i <= r; i ++) {for (int j = 1; j <= c; j ++) {point [i] [j] = new Chesspoint (i * initwidth, j * uneitheight, false); }} 규칙 = 새 규칙 (이, 포인트); 레코드 = 새로운 Makechessmanual (이, 포인트); img = toolkit.getDefaultToolKit (). getImage ( "board.jpg"); siteimg = toolkit.getDefaultToolKit (). getImage ( "piece.gif"); 빨간 차 1 = 새로운 체스 피스 ( "", Color.red, Bc, W -4, H -4, this); 빨간 자동차 1. 세트 체스 조각 범주 (빨간색 정사각형); 빨간 차 2 = 새로운 체스 피스 ( "", color.red, bc, w -4, h -4, this); 빨간 자동차 2. 세트 체스 조각 범주 (빨간색 정사각형); Red Horse 1 = 새로운 체스 피스 ( "", color.red, bc, w -4, h -4, this); Red Horse 1 = 새로운 체스 피스 ( "", color.red, bc, w -4, h -4, this); 붉은 말 2. 체스 조각 범주 (빨간색 정사각형); 빨간 대포 1 = 새로운 체스 피스 ( "火", color.red, bc, w -4, h -4, this); 빨간 대포 1. 체스 조각 범주 (빨간색 정사각형); Red Cannon 2 = 새로운 체스 피스 ( "火", Color.red, BC, W -4, H -4, this); 레드 캐논 2. 세트 체스 조각 범주 (빨간색 정사각형); 빨간 대포 1 = 새로운 체스 피스 ( "火", color.red, bc, w -4, h -4, this); 빨간 대포 1. 체스 조각 범주 (빨간색 정사각형); Red Cannon 2 = 새로운 체스 피스 ( "火", Color.red, BC, W -4, H -4, this); 빨간 대포 1. 체스 조각 범주 (빨간색 정사각형); Red Cannon 2 = 새로운 체스 피스 ( "火", Color.red, BC, W -4, H -4, this); 빨간색 2. 세트 체스 조각 범주 (빨간색 정사각형); 빨간색 1 = 새로운 체스 피스 ( "Shi", Color.red, BC, W -4, H -4, this); 빨간색 1. 체스 조각 범주 (빨간색 정사각형); 빨간색 2 = 새로운 체스 피스 ( "Shi", Color.red, BC, W -4, H -4, this); 빨간색 2. 세트 체스 조각 범주 (빨간색 정사각형); 빨간색 2. 세트 체스 조각 범주 (빨간색 정사각형); 빨간색 2 = 새로운 체스 피스 ( "Shi", Color.red, BC, W -4, H -4, this); 빨간색 1 = 새로운 체스 피스 ( "Shi", Color.red, BC, W -4, H -4, this); 붉은 군인 1. 체스 조각 범주 (빨간 정사각형); Red Soldier 2 = 새로운 체스 피스 ( "Soldier", Color.red, BC, W -4, H -4, this); 붉은 군인 2. 세트 체스 피스 카테고리 (레드 스퀘어 컬러); 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); 붉은 군인 4. 세트 체스 조각 범주 (빨간 정사각형); Red Soldier 5 = 새로운 체스 피스 ( "Soldier", Color.red, BC, W -4, H -4, this); 붉은 군인 5. 세트 체스 조각 범주 (빨간 정사각형); Black Soldier = 새로운 체스 피스 ( "판매", Color.black, BC, W -4, H -4, this); Black Soldier 1 = 새로운 체스 피스 ( "Soldier", Color.black, BC, W -4, H -4, this); Black Soldier 1 = 새로운 체스 피스 ( "Soldier", Color.black, BC, W -4, H -4, this); Black Soldier 1 = 새로운 체스 피스 ( "Car", Color.black, BC, W -4, H -4, this); 검은 색 자동차 1. 세트 체스 조각 범주 (검은 색 제곱 색); Black Car 2 = 새로운 체스 피스 ( "Car", Color.black, BC, W -4, H -4, this); 검은 색 차량 2. 세트 체스 조각 범주 (검은 색 제곱 색); Black Cannon 1 = 새로운 체스 피스 ( "대포", Color.black, BC, W -4, H -4, this); 검은 대포 1. 체스 조각 범주 (검은 색 제곱 색); Black Cannon 2 = 새로운 체스 피스 ( "대포", Color.black, BC, W -4, H -4, this); 검은 색 대포 2. 세트 체스 조각 범주 (검은 색 제곱 색); 검은 코끼리 1 = 새로운 체스 피스 ( "코끼리", Color.black, BC, W -4, H -4, this); 검은 코끼리 1. 체스 조각 범주 (검은 색 제곱 색); 검은 코끼리 2 = 새로운 체스 피스 ( "코끼리", Color.black, BC, W -4, H -4, this); 검은 코끼리 2. 세트 체스 조각 범주 (검은 색 제곱 색); 검은 코끼리 1 = 새로운 체스 피스 ( "코끼리", Color.black, BC, W -4, H -4, this); 검은 코끼리 1. 체스 조각 범주 (검은 색 제곱 색); 검은 코끼리 2 = 새로운 체스 피스 ( "코끼리", Color.black, BC, W -4, H -4, this); 검은 말 2. 체스 조각 범주 (검은 색); 검은 색 바지 1 = 새로운 체스 피스 ( "Zhi", Color.black, BC, W -4, H -4, this); 검은 색 바지 1. 체스 조각 범주 (검은 색); 검은 색 바지 2 = 새로운 체스 피스 ( "Zhi", Color.black, BC, W -4, H -4, this); 검은 색 바지 2. 세트 체스 조각 범주 (검은 색); 검은 색 바지 3 = 새로운 체스 피스 ( "Zhi", Color.black, BC, W -4, H -4, this); 검은 색 바지 3. 체스 조각 범주 (검은 색); 검은 색 바지 4 = 새로운 체스 피스 ( "Zhi", Color.black, BC, W -4, H -4, this); 검은 색 팬텀 4. 세트 체스 조각 범주 (검은 색 제곱 색); Black Phantom 5 = 새로운 체스 피스 ( "Zhi", Color.black, BC, W -4, H -4, this); Black Phantom 5. 세트 체스 조각 범주 (검은 색 제곱 색); 포인트 [1] [10] .setpiece (빨간 캐리지 1, this); 포인트 [2] [10]. 세트 피스 (Red Horse 1, this); 포인트 [3] [10] .setpiece (빨간 단계 1, this); 포인트 [4] [10]. 세트 피스 (Red Sage 1, this); 포인트 [4] [10]. 세트 피스 (Red Sage 1, this); 포인트 [4] [10]. 세트 피스 (Red Sage 1, this); 포인트 [5] [10]. 세트 피스 (Red Soldier, this); 포인트 [6] [10]. 세트 피스 (Red Soldier 2, this); 포인트 [7] [10]. 세트 피스 (Red Soldier 2, this); 포인트 [8] [10]. 세트 피스 (Red Horse 2, this); 포인트 [9] [10]. 세트 피스 (Red Soldier 2, this); 포인트 [2] [8]. 세트 피스 (Red Soldier 1, this); 포인트 [8] [8]. 세트 피스 (Red Soldier 2, this); 포인트 [1] [7]. 세트 피스 (Red Soldier 2, this); 포인트 [3] [7]. 세트 피스 (Red Soldier 2, this); 포인트 [3] [7]. 세트 피스 (Red Soldier 2, this); 포인트 [3] [7]. 세트 피스 (Red Soldier 2, this); 포인트 [5] [7]. 세트 피스 (Red Soldier 3, this); 포인트 [7] [7]. 세트 피스 (Red Soldier 4, this); 포인트 [9] [7]. 세트 피스 (Red Soldier 5, this); 포인트 [1] [1] .setpiece (검은 색 자동차 1, this); 포인트 [2] [1]. 세트 피스 (Black Horse 1, this); 포인트 [3] [1]. 세트 피스 (검은 코끼리 1, this); 포인트 [4] [1]. 세트 피스 (검은 코끼리 1, this); 포인트 [5] [1]. 세트 피스 (Black General, this); 포인트 [6] [1]. 세트 피스 (검은 코끼리 1, this); 포인트 [4] [1]. 세트 피스 (Black General 1, this); 포인트 [5] [1]. 세트 피스 (Black General 2, this); 포인트 [6] [1]. 세트 피스 (Black General 2, this); 포인트 [7] [1]. 세트 피스 (검은 코끼리 2, this); 포인트 [8] [1]. 세트 피스 (Black Horse 2, this); 포인트 [9] [1]. 세트 피스 (Black Car 2, this); 포인트 [2] [3]. 세트 피스 (검은 대포 1, this); 포인트 [8] [3]. 세트 피스 (Black Cannon 2, this); 포인트 [1] [4]. 세트 피스 (검은 대포 1, this); 포인트 [3] [4]. 세트 피스 (Black Cannon 2, this); 포인트 [5] [4]. 세트 피스 (Black Cannon 3, this); 포인트 [7] [4]. 세트 피스 (Black Cannon 4, this); 포인트 [7] [4]. 세트 피스 (Black Cannon 4, this); 포인트 [3] [4]. 세트 피스 (Black Cannon 4, this); 포인트 [5] [4]. 세트 피스 (Black Cannon 3, this); 포인트 [7] [4]. 세트 피스 (Black Cannon 4, this); 포인트 [9] [4]. 세트 피스 (Black Purse 5, this); } public void paintcomponent (그래픽 g) {super.paintcomponent (g); int imgwidth = img.getWidth (this); int imgheight = img.getheight (this); // 그림의 너비와 높이를 얻습니다 int fwidth = getWidth (); int fheight = getheight (); // 창의 너비와 높이를 가져옵니다 int x = (fwidth -imgwidth)/ 2; int y = (fheight -Imgheight) / 2; G.DrawImage (IMG, X, Y, NULL); for (int j = 1; j <= y 축 길이; j ++) {g. drawline (point [1] [j] .x, point [1] [j] .y, point [x-x-x-x-x-x-x-axis 길이] [j] .x, 포인트 [x 축 길이] [j] .y); } for (int i = 1; i <= x 축 길이; i ++) {if (i! = 1 && i! = x 축 길이) {g.drawline (point [i] [1] .x, point [i] [1] .y, point [i] [y-axis length-5] .x, point [i] [y-axis 길이 -5]. g. drawline (point [i] [y 축 길이 -4] .x, 포인트 [i] [y 축 길이 -4] .y, point [i] [y 축 길이] .x, 포인트 [i] [y 축 길이] .y); } else {g. drawline (point [i] [1] .x, point [i] [1] .y, point [i] [y 축 길이] .x, 포인트 [i] [y 축 길이] .y); }} G.DrawLine (점 [4] [1] .x, 점 [4] [1] .y, 점 [6] [3] .x, 점 [6] [3] .y); G. drawline (점 [6] [1] .x, 포인트 [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 축 길이] .x, 포인트 [6] [y 축 길이] .y); G. drawline (점 [4] [y 축 길이] .x, 포인트 [4] [y 축 길이] .y, point [6] [8] .x, point [6] [8] .y); for (int i = 1; i <= x 축 길이; i ++) {g.drawstring ( ""+i, i * initwidth, unitheight / 2); } int j = 1; for (char c = 'a'; c <= 'j'; c ++) {g.drawString ( ""+c, initwidth / 4, j * unitheight); J ++; }} / ** 마우스 프레스 이벤트* / public void mousepressed (mouseevent e) {chesspiece piece = null; 사각형 rect = null; if (e.getSource () == this) move = false; if (mak == false) if (e.getSource () instancef chessfife) {piece = (Chesspiece) e.getSource (); startx = piece.getBounds (). x; starty = piece.getBounds (). y; rect = piece.getBounds (); for (int i = 1; i <= x- 축 길이; i ++) {for (int j = 1; j <= y 축 길이; j ++) {int x = point [i] [j] .getx (); int y = point [i] [j] .gety (); if (rect.contains (x, y)) {starti = i; startj = j; 부서지다; }}}}}} public void mousemoved (mouseevent e) {} / ** 마우스 드래그 이벤트* / public void mousedRagged (mouseevent e) {chesspiece piece = null; if (e.getSource () 체스 피스의 인스턴스) {piece = (chesspiece) e.getSource (); 이동 = 참; e = swingUtilities.convertMouseevent (조각, e, this); } if (e.getSource () == this) {if (move && piece! = null) {x = e.getx (); y = e.gety (); if (red square chess && ((site.chess subcategory ()). equals (빨간색 제곱 색))) {piece.setlocation (x- stec.getWidth () / 2, y -getheight () / 2); } if (Black Chess Move && (site.chess class (). Equals (black font color)))) {piece.setLocation (x- stec.getWidth () / 2, y -getheight () / 2); }}}} / ** 릴리스 마우스 이벤트* / public void mouserEleled (mouseevent e) {chesspiece piece = null; 이동 = 거짓; 사각형 rect = null; if (e.getSource () instanceof chessfife) {piece = (chesspiece) e.getSource (); rect = piece.getBounds (); e = swingUtilities.convertMouseevent (조각, 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 축 길이; i ++) {for (int j = 1; j <= y 축 길이; j ++) {x = point [i] [j] .getx (); y = point [i] [j] .gety (); if (rect.contains (x, y)) {containschesspoint = true; m = i; n = J; 부서지다; }}}}} if (piece! = null && containSchessPoint) {color priceColor = piece.get color (); if (point [m] [n] .ispiece ()) {color c = (point [m] [n] .getpiece ()). chess ()의 색상을 얻습니다. if (priceColor.getRGB () == c.getRGB ()) {startx, Starty); (point [starti] [startj]). 세트는 체스 조각 (true); } else {boolean ok = rule.movePiecerule (조각, starti, startj, m, n); if (ok) {chesspiece pistremoved = point [m] [n] .getpiece (); 포인트 [m] [n] .removepiece (pistremoved, this); 포인트 [m] [n] .setpiece (조각, this); (point [starti] [startj]). 세트는 체스 조각이 있습니다 (false); 레코드. 레코드 체스 점수 (조각, starti, startj, m, n); record. rule.iswine (pistremoved); if (piece.paper category (). Equals (빨간색 정사각형)) {빨간색 사각형 이동 = false; 블랙 스퀘어 이동 = 참; } if (piece.paper category (). equals (검은 색 제곱 색상)) {black square move = false; 빨간 정사각형 이동 = true; } validate (); 리 페인트 (); } else {startx, starty); (point [starti] [startj]). 세트는 체스 조각 (true); }}} else {boolean ok = rule .movePiecerule (step, starti, startj, m, n); if (ok) {point [m] [n] .setpiece (조각, this); (point [starti] [startj]). 세트는 체스 조각이 있습니다 (false); 레코드. 레코드 체스 점수 (조각, starti, startj, m, n); 레코드. 레코드 체스 조각을 먹었다 ( "체스 조각 없음"); if (piece.paper category (). Equals (빨간색 정사각형)) {빨간색 체스 = 거짓; 블랙 스퀘어 체스 = 참; } if (piece.paper category (). equals (검은 색 제곱 색)) {black square chess = false; 레드 스퀘어 체스 = 참; }} else {startx, starty); (point [starti] [startj]). 세트는 체스 조각 (true); }}} if (piece! = null &&! containchesspoint) {startx, starty); (point [starti] [startj]). 세트는 체스 조각 (true); }}} public void mouseentered (mouseevent e) {} public void mouseexited (mouseevent e) {} public void mouseclicked (mouseevent e) {}} 3. Chesspiece.java 파일
패키지 cn.edu.ouc.chinesechess; javax.swing을 가져옵니다.*; java.awt.*; import java.awt.event.*; / ** * 체스 클래스 * * @author cnlht */ public class chesspiece jlabel {문자열 이름; // 체스 이름 컬러 백 컬러 = null, 예측 류; // 배경 및 전경 색상 문자열 색상 범주 = null; 체스 보드 보드 = null; int 너비, 높이; // 크기 공개 체스 피스 (문자열 이름, 색상 FC, 컬러 BC, int 너비, int 높이, 체스 보드 보드) {// 체스 조각을 구성 this.name = 이름; this.board = 보드; this.width = 너비; this.height = 높이; 예측 olor = fc; 백 콜러 = BC; setSize (너비, 높이); 좌절장 (BC); AddMousEmotionListener (보드); AddMousElistener (보드); } // 체스 조각을 그리기 공개 void 페인트 (그래픽 g) {G.DrawImage (Board. Profeesimg, 2, 2, width-2, height-2, null); G. 세트 콜러 (예측 olor); g.setfont (new font ( "Kaiti", font.bold, 26)); G.DrawString (이름, 7, 높이 -8); // 체스 조각 G.SetColor (Color.Black)에 "체스 이름"을 그리십시오. //g. drawoval(1, 1, 너비 -1, 높이 -1); float linewidth = 2.3f; ((Graphics2d) G) .SetStroke (New BasicStroke (Linewidth)); ((Graphics2d) g) .Drawoval (2, 2, width-2, height-2); } public int getWidth () {리턴 너비; } public int getheight () {리턴 높이; } public String getName () {return name; } public color 체스 색상 () {return forecolor; } public void 세트 체스 범주 (문자열 범주) {색상 범주 = 범주; } public String Chess Category () {리턴 색상 범주; }} 4. 체스 피스 포인트 좌표 파일
패키지 cn.edu.ouc.chinesechess; / *** 체스 포인트 클래스** @author cnlht*/ public class chesspoint {/ ** chesspiece 좌표*/ int x, y; / **이 좌표는 조각*/ boolean에 조각이 있습니다. /** 체스 피스 조각 = null; / ** 좌표가 속한 Chessboard*/ Chessboard Board = null; 공개 체스 포인트 (int x, int y, boolean boo) {this.x = x; this.y = y; 조각이 있습니다 = boo; } public boolean ispiece () {return 체스 조각이 있습니다. } public void 세트는 체스 조각 (부울 부) {체스 조각 = boo; } public int getx () {return x; } public int gety () {return y; } // 체스 조각에 대한 변경 사항 설정 공개 무효 세트 (Chesspiece Piece, Chessboard Board) {this.board = 보드; this.piece = 조각; Board.add (조각); int w = (board.unitwidth); int h = (보드 .UnitHeight); setsbounds (x -w / 2, y -h / 2, w, h); // 체스 조각 위치, 너비, 체스 조각의 높이 = true; Board.Validate (); } public chesspiece getpiece () {return 조각; } public void removepiece (체스 피스 조각, 체스 보드 보드) {this.board = 보드; this.piece = 조각; Board.remove (조각); Board.Validate (); 체스 조각 = 거짓; }} 5. 게임 플레이 규칙 클래스 파일 규칙 .java
패키지 cn.edu.ouc.chinesechess; javax.swing을 가져옵니다.*; java.awt.*; import java.awt.event.*; / ** * 체스 플레이 규칙 클래스 * * @author cnlht */ public 클래스 규칙 {chessboard board = null; 체스 피스 조각 = null; 체스 포인트 포인트 [] []; int starti, startj, endi, endj; 공개 규칙 (Chessboard Board, Chesspoint Point [] []) {this.board = 보드; this.point = point; } public void iswine (체스 피스 조각) {this.piece = piece; if (site.getName () == "aLigned"|| site.getName () == "handy") {if (site.color category = "red side") {joptionpane.showmessagedialog (null, "black side victory!"); } else {joptionpane.showmessagedialog (null, "Red Side Victory!"); }}} public boolean movepiecerule (체스 피스 피스, int starti, int startj, int endi, int endj) {this.pief = 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); 부울은 체스 = 거짓을 할 수 있습니다. if (site.getName (). equals ( "car")) {if (starti == endi) {int j = 0; for (J = minj+1; 부서지다; }} if (j == maxj) {chess = true를 움직일 수 있습니까? }} else if (startj == endj) {int i = 0; for (i = mini+1; i <= maxi -1; i ++) {if (point [i] [startj] .ispiece ()) {chess = false를 이동할 수 있습니까? 부서지다; }} if (i == maxi) {chess = true를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }}} else if (site.getName (). Equals ( "")) {if (starti == endi) {int j = 0; for (J = minj+1; 부서지다; }} if (j == maxj) {chess = true를 움직일 수 있습니까? }} else if (startj == endj) {int i = 0; for (i = mini+1; i <= maxi -1; i ++) {if (point [i] [startj] .ispiece ()) {chess = false를 이동할 수 있습니까? 부서지다; }} if (i == maxi) {chess = true를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }} else if (site.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 ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} if (endi <starti) {if (point [starti -1] [startj] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }}} else if (xaxle == 1 && yaxle == 2) {if (endj> startj) {if (point [starti] [startj + 1] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} if (endj <startj) {if (point [starti] [startj -1] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} if (endj <startj) {if (point [starti] [startj -1] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? } 진실; }}} else {chess = false를 움직일 수 있습니까? }} else if (site.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 ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} if (endi <starti) {if (point [starti -1] [startj] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }}} else if (xaxle == 1 && yaxle == 2) {if (endj> startj) {if (point [starti] [startj + 1] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} if (endj <startj) {if (point [starti] [startj -1] .ispiece ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }}} else {chess = false를 움직일 수 있습니까? }} else if (site.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 ()) {chess = false를 움직일 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }} else if (site.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 ()) {chess = false를 이동할 수 있습니까? } else {chess = true를 움직일 수 있습니까? }} else {chess = true를 움직일 수 있습니까? }} else {chess = true를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }} else if (site.getName (). equals ( "cannon")) {int number = 0; if (starti == endi) {int j = 0; for (j = minj+1; }} if (번호> 1) {chess = false를 이동할 수 있습니까? } else if (number == 1) {if (point [endi] [endj] .ispiece ()) {chess = true를 움직일 수 있습니까? }} else if (number == 0 &&! point [endi] [endj] .ispiece ()) {chess = true를 움직일 수 있습니까? }} else if (startj == endj) {int i = 0; for (i = mini+1; i <= maxi -1; i ++) {if (point [i] [startj] .ispiece ()) {번호 ++; }} if (번호> 1) {chess = false를 이동할 수 있습니까? } else if (number == 1) {if (point [endi] [endj] .ispiece ()) {chess = true를 움직일 수 있습니까? }} else if (number == 0 &&! point [endi] [endj] .ispiece ()) {chess = true를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }} else if (site.getName (). equals ( "Soldier")) {int xaxle = math.abs (starti -endi); int yaxle = math.abs (startj -endj); if (endj> = 6) {if (startj -endj == 1 && xaxle == 0) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }} else if (endj <= 5) {if ((startj -endj == 1) && (xaxle == 0)) {chess = true를 움직일 수 있습니까? } else if ((endj -startj == 0) && (xaxle == 1)) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }}} else if (site.getName (). equals ( "zhi")) {int xaxle = math.abs (starti -endi); int yaxle = math.abs (startj -endj); if (endj <= 5) {if (endj -startj == 1 && xaxle == 0) {내가 chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }} else if (endj> = 6) {if ((endj -startj == 1) && (xaxle == 0)) {chess = true를 움직일 수 있습니까? } else if ((endj -startj == 0) && (xaxle == 1)) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }}} else if (site.getName (). equals ( "shi")) {int xaxle = math.abs (starti -endi); int yaxle = math.abs (startj -endj); if (endi <= 6 && endi> = 4 && xaxle == 1 && yaxle == 1) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }} else if (site.getName (). equals ( "state")) {int xaxle = math.abs (starti -endi); int yaxle = math.abs (startj -endj); if (endi <= 6 && endi> = 4 && xaxle == 1 && yaxle == 1) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }} else if ((sites.getName (). equals ( "handsome")) || (site.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)) {chess = true를 움직일 수 있습니까? } else {chess = false를 움직일 수 있습니까? }} else {chess = false를 움직일 수 있습니까? }} return 체스를 움직일 수 있습니까? }} 6. movestep.java 파일
패키지 cn.edu.ouc.chinesechess; Java.awt.Point 가져 오기; / ** * 워킹 클래스 * * @author cnlht * */ public class movestep는 java.io.serializable {public point pstart, pend; public movestep (Point P1, Point P2) {PSTART = P1; pend = p2; }} 7. Chessmanual.java를 만드십시오
패키지 cn.edu.ouc.chinesechess; javax.swing을 가져옵니다.*; java.awt.*; import java.awt.event.*; java.util.linkedList 가져 오기; / ** * 체스 레코드 클래스 만들기 * * @author cnlht */ public class makeSsmanual 확장 jpanel 구현 actionListener {jtextArea text = null; jscrollpane scroll = null; 체스 보드 보드 = null; 체스 포인트 [] [] 포인트; Linkedlist Chess Note = NULL; Linkedlist는 먹은 체스 조각 = null; JBUTTON BUTCYUNDO; int i = 0; Public Makechessmanual (Chessboard Board, Chesspoint [] [] Point) {this.board = 보드; this.point = point; 텍스트 = 새로운 jtextArea (); 스크롤 = 새로운 jscrollpane (텍스트); 체스 노트 = New LinkedList (); 먹은 체스 조각 = 새로운 LinkedList (); ButtonUndo = New Jbutton ( "Repent Chess"); buttonUndo.setfont (새 글꼴 ( "Lishu", font.plain, 18)); setLayout (New BorderLayout ()); 추가 (Scroll, BorderLayout.Center); 추가 (ButtonUndo, BorderLayout.South); buttonUndo.addactionListener (this); } public char numbertoletter (int n) {char c = '/0'; 스위치 (n) {case 1 : c = 'a'; 부서지다; 사례 2 : c = 'b'; 부서지다; 사례 3 : C = 'C'; 부서지다; 사례 4 : c = 'd'; 부서지다; 사례 5 : c = 'e'; 부서지다; 사례 6 : c = 'f'; 부서지다; 사례 7 : c = 'g'; 부서지다; 사례 8 : c = 'h'; 부서지다; 사례 9 : c = 'i'; 부서지다; 사례 10 : c = 'j'; 부서지다; } 반환 c; } public void 레코드 체스 점수 (체스 피스 조각, int starti, int startj, int endi, int endj) {point pstart = new Point (starti, startj); 포인트 펜 = 새로운 포인트 (endi, endj); Movestep Step = New Movestep (Pstart, Pend); 체스 score.add (단계); 문자열 체스 카테고리 = piece.chess category (); 문자열 이름 = piece.getName (); 문자열 m = "#" + 체스 카테고리 + 이름 + ":" + starti + numbertoletter (startj) + "to" + endi + numbertoletter (endj); Text.Append (m); if (piece. chess category (). equals (board.black square color)) text.append ( "/n"); } 공개 void 레코드를 먹은 체스 조각 (물체 객체) {먹은 체스 조각 .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 sites.size ()> 0) {movestep laststep = (movestep) chess piece.getLast (); 체스 레코드 .removelast (); Object Qizi = 먹은 체스 조각 .getLast (); 먹은 체스 조각 .removelast (); 문자열 temp = qizi.tostring (); if (temp.equals ( "체스 조각")) {int starti = laststep.pstart.x; int startj = laststep.pstart.y; int endi = laststep.pend.x; int endj = laststep.pend.y; 체스 피스 조각 = point [endi] [endj] .getpiece (); 포인트 [starti] [startj] .setpiece (조각, 보드); (point [endi] [endj]). 세트는 체스 조각이 있습니다 (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; 체스 피스 조각 = point [endi] [endj] .getpiece (); 포인트 [starti] [startj] .setpiece (조각, 보드); 포인트 [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记录棋谱的方法。
希望大家喜欢这篇文章,制作一款属于自己的中国象棋游戏。