이 기사에서는 Java로 구현 된 Gozi Chess 게임 코드에 대해 설명합니다. 참조를 위해 귀하와 공유됩니다. 특정 코드는 다음과 같습니다
1. 실용적인 목표
1. Javagui 인터페이스 디자인을 마스터하십시오
2. 마우스 이벤트 모니터링 마스터 (Mouselistener, MousemotionListener)
2. 실제 콘텐츠
Gochi Chess 게임 프로세스를 실현할 수있는 간단한 Gochi 프로그램을 설계하십시오. 아래 그림과 같이
1. Gozi Chess Board
패키지 cn.edu.ouc.fivechess; import java.awt.color; import java.awt.cursor; java.awt.dimension import; java.awt.graphics 가져 오기; import java.awt.graphics2d; import java.awt.image; import java.awt.radialgradientPaint; Java.awt.RenderingHints 가져 오기; java.awt.toolkit import; java.awt.event.mouseevent import; import java.awt.event.mouselistener; import java.awt.event.mouseMotionListener; java.awt.geom.ellipse2d; javax.swing을 가져옵니다.*; /*** Goziqi-Chess-Chess-Board Class*/Public Class Chessboard 확장 JPanel 구현 Mouselistener {public static final int margin = 30; // margin public static final grid_span = 35; // 그리드 간격 공개 정적 최종 int 줄 = 15; // Chessboard Public int cols = 15; // chessboard public inth int cols = // 포인트 [(행+1)*(cols+1)]; // 초기 각 배열 요소는 null boolean isblack = true; // 기본값은 검은 색 체스 첫 부울 게임 오버 = 거짓으로 시작합니다. // 게임은 int xindex, yindex, yindex; 이미지 그림자; 컬러 colortemp; public chessboard () {// setbackgroun 섀도우 = 툴킷 .getDefaultToolKit (). getImage ( "Shadows.jpg"); AddMousElistener (this); AddMouseMotionListener (New MouseMotionListener () {public void MousedRagged (Mouseevent e) {} public void mousemoved (mouseevent e) {int x1 = (e.getx ()-margin+grid_span/2)/grid_span; // grid index int로 조정 위치를 변환합니다. y1 = (e.gety ()-margin+grid_span/2)/grid_span; // 체스 보드 외부에있는 곳은 없으며, y 위치에 존재합니다. setCursor (cursor.default_cursor); // setcursor (cursor.hand_cursor)); } // public void paintcomponent (그래픽 g) {super.paintcomponent (g); // Chessboard 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 i = 0; i <= rows; i ++) {// 수평 선 G.Drawline (마진, 마진+i*grid_span, margin+cols*grid_span, margin+i*grid_span); } for (int i = 0; i <= cols; i ++) {// 수직선 G.DrawLine (마진+i*grid_span, 마진, 마진+i*grid_span); } // (int i = 0; i <chesscount; i ++) {// 그리드 교차로 x, y coordinate int xpos = chesslist [i] .getx ()*grid_span+margin; int ypos = chesslist [i] .gety ()*grid_span+margin; g.setColor (ChessList [i] .getColor ()); // 색상 설정 // g.filloval (xpos-point.diameter/2, ypos-point.diameter/2, //point.diameter, point.diameter); //g.drawimage(shadows, xpos-point.diameter/2, ypos-point.diameter/2, point.diameter, point.diameter, null); colortemp = chesslist [i] .getColor (); if (colortemp == color.black) {radialgradientPaint Paint = new radialgradientPaint (XPOS-POINT.DIAMETER/2+25, ypos-Point.Diameter/2+10, 20, New Float [] {0f, 1f}, New Color [] {Color.White, Color.Black}); ((Graphics2d) g) .setpaint (페인트); ((Graphics2d) G) .SetRenderingHint (renderingHints.Key_antialiasing, renderingHints.Value_antialias_on); ((Graphics2d) g) .SetRenderingHint (renderingHints.Key_Alpha_InterPolation, renderingHints.Value_alpha_InterPolation_Default); } else if (colortemp == color.white) {radialgradientPaint Paint = new radialgradientPaint (XPOS-POINT.DIAMETER/2+25, ypos-Point.Diameter/2+10, 70, New Float [] {0f, 1f}, New Color [] {Color.White, Color.Black}); ((Graphics2d) g) .setpaint (페인트); ((Graphics2d) G) .SetRenderingHint (renderingHints.Key_antialiasing, renderingHints.Value_antialias_on); ((Graphics2d) g) .SetRenderingHint (renderingHints.Key_Alpha_InterPolation, renderingHints.Value_alpha_InterPolation_Default); } elipse2d e = new Ellipse2d.float (xpos-point.diameter/2, ypos-point.diameter/2, 34, 35); ((Graphics2d) g) .fill (e); // 마지막 체스 조각을 표시하는 빨간색 직사각형 상자 (i == chessCount-1) {// 마지막 체스 조각 인 경우 g.setColor (color.red); G.DrawRect (XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, 34, 35); }}} public void mousepressed (mouseevent e) {// 구성 요소를 눌렀을 때 마우스가 호출됩니다. // 게임은 더 이상 재생할 수 없습니다. 문자열 colorname = isblack? "black": "화이트 체스"; // 마우스의 좌표 위치를 그리드 인덱스로 클릭하십시오 XINDEX = (e.getx () -Grid_span/2)/grid_span; yindex = (e.gety ()-마진+grid_span/2)/grid_span; // 체스 판 밖으로 떨어지면 (xindex <0 || xindex> 행 || yindex <0 || yindex> cols) return; // X와 Y 위치에 체스 조각이있는 경우 (FindChess (xindex, yindex))가 반환하면 넣을 수 없습니다. // 완료되면 할 수 있다면 완료되면 넣을 수 없습니다. 포인트 (xindex, yindex, isblack? color.black : color.white); 체스리스트 [ChessCount ++] = ch; Refaint (); // 시스템에 다시 드로 이동하도록 통지하십시오. // 이기면 즉시 메시지를 보내고 즉각적인 메시지를 제공하고 (iswin ()) {string msg = string.format ( "축하, %s Won!", Colorname); joptionpane.showmessagedialog (this, msg); GameOver = true; } isblack =! isblack; } // mouselistener public void mouseclicked (mouseevent e)를 덮어 쓰는 방법 {// 마우스 버튼이 구성 요소를 클릭 할 때} public void mouseentered (mouseevent e)를 클릭 할 때 호출 {// 마우스가 public void mouseexited (mouseevent e) {// 호출 할 때 {// component lefeencent remonter remont remonter} mouserEleled (mouseevent e) {// 마우스 버튼이 구성 요소에서 릴리스 될 때 호출} // 체스 배열에서 호출하여 개인 부울 findchess (int x, int y) {for (point c : chesslist) {if (c! = null && c.get x && c.gety ()); } false를 반환합니다. } private boolean iswin () {int continuecount = 1; // 연속 체스 조각의 수 // (int x = xindex-1; x> = 0; x-) {color c = isblack? color.black : color.white; if (getchess (x, yindex, c)! = null) {continuecount ++; } else break; } // (int x = xindex+1; x <= cols; x ++) {color c = isblack? color.black : color.white; if (getchess (x, yindex, c)! = null) {continuecount ++; } else break; } if (continueCount> = 5) {return true; } else continueCount = 1; // 다른 검색을 수직으로 계속 계속하십시오 // (int y = yindex-1; y> = 0; y-) {color c = isblack? color.black : color.white; if (getchess (xindex, y, c)! = null) {continuecount ++; } else break; } // (int y = yindex+1; y <= 행; y ++) {color c = isblack? color.black : color.white; if (getchess (xindex, y, c)! = null) continuecount ++; 다른 휴식; } if (continueCount> = 5)를 반환합니다. else continuecount = 1; // 다른 상황을 계속 검색하십시오. if (getchess (x, y, c)! = null) {continuecount ++; } else break; } // (int x = xindex-1, y = yindex+1; x> = 0 && y <= rows; x-, y ++) {color c = isblack? color.black : color.white; if (getchess (x, y, c)! = null) {continuecount ++; } else break; } if (continueCount> = 5)를 반환합니다. else continuecount = 1; // 다른 상황에서 검색을 계속하십시오 : Oblique // (int x = xindex-1, y = yindex-1; x> = 0 && y> = 0; x-, y-) {color c = isblack? color.black : color.white; if (getchess (x, y, c)! = null) continuecount ++; 다른 휴식; } // 남동쪽을 찾으십시오 (int x = xindex+1, y = yindex+1; x <= cols && y <= 행; x ++, y ++) {color c = isblack? color.black : color.white; if (getchess (x, y, c)! = null) continuecount ++; 다른 휴식; } if (continueCount> = 5)를 반환합니다. else continuecount = 1; 거짓을 반환합니다. } private point getchess (int xindex, int yindex, color color) {for (point p : chesslist) {if (p! = null && p.getx () == xindex && p.gety () == yindex && p.getColor () == color) return p; } return null; } public void RETARTGAME () {// 체스 조각 (int i = 0; i <chesslist.length; i ++) {chesslist [i] = null; } // 게임 관련 변수 값 isblack = true를 복원합니다. 게임 오버 = 거짓; // 게임 종료 체스 칸트 = 0; // 현재 체스 조각의 수는 Refaint (); } // 체스 공개 void goback () {if (chesscount == 0) return; Chesslist [Chesscount-1] = null; ChessCount--; if (chesscount> 0) {xindex = chesslist [chesscount-1] .getx (); yindex = chesslist [chesscount-1] .gety (); } isblack =! isblack; 리 페인트 (); } // 직사각형 치수 공용 치수 getPreferredSize () {return new Dimension (마진*2 +grid_span*cols, margin*2 +grid_span*행); }} 2. 체스 조각
패키지 cn.edu.ouc.fivechess; import java.awt.color; /*** 체스 클래스*/public class point {private int x; // 체스 보드의 개인 in in index in in index private int y; // 체스 보드의 개인 색상 색상; // 색상 public static final int 직경 = 30; 직경 공개 포인트 (int x, int y, color color) {this.x = x; this.y = y; this.color = 색상; } public int getx () {// 체스 보드 return x에서 x의 색인을 가져옵니다. } public int gety () {return y; } public color getColor () {// 체스 조각의 색상을 얻습니다. }} 3. 고지 메인 프레임 클래스
패키지 cn.edu.ouc.fivechess; import java.awt.event.*; java.awt.*; javax.swing을 가져옵니다.*; /* Goji Main Framework, 프로그램*/ public class startchessjframe 확장 jframe {private chessboard chessboard; 개인 jpanel 도구 모음; 개인 JBUTTON STARTBUTTON, BACKBUTTON, EXITBUTTON; 개인 jmenubar menubar; 개인 jmenu sysmenu; private jmenuitem startmenuitem, exitmenuitem, backmenuitem; // 다시 시작, 종료 및 후회 메뉴 항목 public startchessjframe () {settitle ( "stand-alone goji"); // 제목을 설정하여 Chessboard = new Chessboard (); 컨테이너 contentpane = getContentPane (); contentpane.add (Chessboard); Chessboard.setopaque (true); // 메뉴 생성 및 추가 메뉴 바 = 새로운 jmenubar (); // 메뉴를 초기화합니다. sysmenu = new Jmenu ( "System"); // 메뉴 초기화 // 초기화 메뉴 항목 startMenuitem = new Jmenuitem ( "다시 시작"); exitmenuitem = new jmenuitem ( "Exit"); backmenuitem = new jmenuitem ( "Repent"); // 메뉴에 세 가지 메뉴 항목을 추가하십시오. SysMenu.add (startMenuitem); sysmenu.add (exitmenuitem); sysmenu.add (backmenuitem); // 내부 클래스 초기화 MyItemListener LIS = New MyItemListener (); // 이벤트 리스너에 세 가지 메뉴를 등록하십시오. backmenuitem.addactionListener (LIS); exitmenuitem.addactionListener (LIS); menubar.add (sysmenu); // 메뉴 바에 시스템 메뉴 추가 Setjmenubar (menubar); // menubar를 메뉴 바에 도구 모음으로 설정하십시오. new jpanel (); // 도구 패널을 인스턴스화하십시오. 3 개의 버튼은 startbutton = new JButton ( "시작"); ExitButton = New JButton ( "Exit"); backbutton = New Jbutton ( "Repent"); // FlowLayout 도구 모음을 사용하여 도구 패널 버튼을 레이아웃 (New FlowLayout (FlowLayout.left)); // 도구 패널 도구 모음에 3 개의 버튼을 추가합니다. ADD (startButton); Toolbar.add (exitbutton); Toolbar.add (backbutton); // 이벤트를 들으려면 세 개의 버튼을 등록 startButton.AddActionListener (LIS); exitButton.AdDactionListener (LIS); backbutton.addactionListener (LIS); backbutton.addactionListener (LIS); // 도구 패널을 인터페이스 "South"에 넣습니다. 추가 (Chessboard); // 패널 객체를 형태로 추가하십시오. // 인터페이스를 설정하십시오 닫기 이벤트 setDefaultCloseOperation (jframe.exit_on_close); // setSize (800,800); pack (); // Adaptive size} private class myItemListener는 ActionListener {public void actionPerformed (actionEvent e) {object obj = e.getSource (); // 이벤트 소스를 가져옵니다. 클래스 System.out.println ( "시작"); Chessboard.restartGame (); } else if (obj == exitMenuitem || obj == exitButton) system.exit (0); else if (obj == backmenuitem || obj == backbutton) {System.out.println ( "Repent Chess ..."); chessboard.goback (); }}} public static void main (string [] args) {startChessJframe f = new startChessJframe (); 메인 프레임 생성 F.setVisible (true); 메인 프레임 표시}}}} 3. 요약
1. 메뉴의 설계 및 구현?
2. 마우스가 체스 판을 클릭 한 후 체스 조각을 그리는 방법은 무엇입니까? 방금 설정 한 체스 조각의 빨간색 상자를 그리는 방법은 무엇입니까?
3. 체스 점수의 데이터 구조는 무엇입니까?
위의 내용은이 기사에 관한 모든 것입니다. 모든 사람들이 Java 프로그래밍을 배우는 것이 도움이되기를 바랍니다.