Java Swing Gobang Source code and implementation of Java Development graphical interface program Gobang implementation mode

Source: Internet
Author: User
Tags gety stub

Today to introduce you how to use Java Swing to implement Gobang development is Java Development GUI program Gobang, code because too much, only paste part, the most below will be attached, nonsense not to say, below we first look at the results of the operation:


Next we look at the code:

The first is to create the main frame interface:

Package Org.liky.game.frame;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import Java.awt.toolkit;import Java.awt.event.mouseevent;import Java.awt.event.mouselistener;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.ioexception;import Javax.imageio.ImageIO;import Javax.swing.jframe;import Javax.swing.joptionpane;public class Fivechessframe extends JFrame implements MouseListener , Runnable {//Gets the width of the screen int width = Toolkit.getdefaulttoolkit (). Getscreensize (). width;//get the height of the screen int height = Toolkit.getdefaulttoolkit (). Getscreensize (). height;//background picture BufferedImage bgimage = null;//Save a piece's coordinates int x = 0;int y = 0;//Save  The coordinates of all the pieces that were previously played///where the data content 0: Indicates that this point is not a pawn, 1: Indicates that this point is a sunspot, 2: Indicates that this point is a white child int[][] allchess = new int[19][19];//identifies whether the current should be black or white next to the next Boolean Isblack = true;//identifies whether the current game can continue with a Boolean canPlay = true;//Save the displayed prompt string message = "Black first";//Save up to how much time (seconds) int maxtime = 0; Do the countdown thread t = new Thread (this),//preserve black and white for the remainder of the time int blacktime = 0;int Whitetime = 0;//Save both sides of the remaining time of the explicitMessage string blackmessage = "unlimited"; String whitemessage = "Unrestricted";p ublic Fivechessframe () {//Set caption This.settitle ("Gobang");//Set Form size This.setsize (500, 500);// The setup form appears this.setlocation ((width-500)/2, (height-500)/2);//Set the form to a size that cannot be changed this.setresizable (false);//Set the form to default off Close the program End This.setdefaultcloseoperation (jframe.exit_on_close);//Add listener to the form this.addmouselistener (this);// Show the form this.setvisible (true); T.start (); T.suspend ();//Refresh the screen to prevent the event from appearing when the game starts. This.repaint (); String ImagePath = ""; try {ImagePath = System.getproperty ("User.dir") + "/src/image/background.jpg"; bgimage = Imageio.read (New File (Imagepath.replaceall ("\\\\", "/")));} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} public void Paint (Graphics g) {//double buffering technology prevents screen flicker bufferedimage bi = new BufferedImage ($, 500,BUFFEREDIMAGE.TYPE_INT_RGB); Graphics g2 = Bi.creategraphics (); G2.setcolor (color.black);//Draw Background g2.drawimage (Bgimage, 1, this);// Output header information G2.setfont (new Font ("bold", Font.Bold,)) g2.drawstring ("Game info:" + Message, 130, 60);//Output Time information G2.setfont (new Font ("Arial", 0, +)); G2.drawstring ("Black Time:" + blackmessage, 470); G2.drawstri Ng ("White Time:" + whitemessage, 260, 470);//Draw checkerboard for (int i = 0; i <; i++) {G2.drawline (ten, + * I, 370, + +) ); G2.drawline (Ten + * I, 430);} Callout Point G2.filloval (4, 4); G2.filloval (308, 4, 4) G2.filloval (308, 368, 4, 4); G2.filloval (368, 4, 4); g2.fi  Lloval (308, 248, 4, 4); G2.filloval (188,, 4, 4); G2.filloval (248, 4, 4); G2.filloval (188, 368, 4, 4); G2.filloval (188, 248, 4, 4);/* *//Draw Checkers x = (x-10)/20 * 20 + 10; y = (y-70)/20 * 20 + 70; *//Sunspot G.filloval (x-7, Y-7, 14, 14); White son G.setcolor (color.white); * G.filloval (X-7, Y-7, 14, 14); G.setcolor (Color.Black); * G.drawoval (X-7, Y-7, 14, 14); *///Draw all pieces for (int i = 0; i <; i++) {for (int j = 0; J < + j + +) {if (allchess[i][j] = = 1) {//sunspots int tempx = i * + 10;int Tempy = J * + 70;g2.filloval (tempX-7, TempY-7, 14, 14);} if (AllchESS[I][J] = = 2) {//Shirako int tempx = i * + 10;int Tempy = J * + 70;g2.setcolor (color.white); G2.filloval (tempX-7, Temp Y-7, G2.setcolor (Color.Black); G2.drawoval (TempX-7, TempY-7, 14, 14);}}} G.drawimage (BI, 0, 0, this);}  public void mouseclicked (MouseEvent e) {//Todo auto-generated method stub}public void mouseentered (MouseEvent e) {//TODO Auto-generated method Stub}public void mouseexited (MouseEvent e) {//TODO auto-generated method stub}public void Mousepre ssed (MouseEvent e) {//TODO auto-generated Method stub/* * SYSTEM.OUT.PRINTLN ("X:" +e.getx ()); System.out.println ("Y:" +e.gety ());  */if (CanPlay = = true) {x = E.getx (); y = E.gety (); if (x >= && x <= 370 && y >=) && y <= 430) {x = (x-10)/20;y = (y-70)/20;if (allchess[x][y] = = 0) {//Determine what color is currently under the pawn if (Isblack = True) {Allches S[x][y] = 1;isblack = False;message = "Turn white side";} else {Allchess[x][y] = 2;isblack = True;message = "Turn black Side";} Determine if the piece is connected to another piece of 5, that is, whether the game ends with a Boolean winFlag = This.checkwin (), if (Winflag = = True) {Joptionpane.showmessagedialog (this, "Game Over," + (allchess[x][y] = = 1?) "Black": "White Side") + "Win!" "); canPlay = false;}} else {Joptionpane.showmessagedialog (this, "the current position already has a pawn, please re-lazi!") ");} This.repaint ();}} /* SYSTEM.OUT.PRINTLN (E.GETX () + "--" + e.gety ()); *///Click Start Game button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 70&& e.gety () <= {int result = Joptionpane.showconfirmdialog (this, "Do you want to start the game again?"); if (result = = 0) {//start the game again//start over: 1) empty the board, allchess all the data in this array to 0.//2) to change the game information: the display to the beginning//3) to change the next step of chess to black side for (int i = 0; I < 19; i++) {for (int j = 0; J <; J + +) {Allchess[i][j] = 0;}} Another way allchess = new Int[19][19];message = "Black side first"; isblack = True;blacktime = Maxtime;whitetime = Maxtime;if (MaxTime &G T 0) {blackmessage = maxtime/3600 + ":" + (maxtime/60-maxtime/3600 *) + ":" + (MAXTIME-MAXTIME/60 *); whiteme Ssage = maxtime/3600 + ":" + (maxtime/60-maxtime/3600 *) + ":" + (MAXTIME-MAXTIME/60 *); T.resume ();} else {blackmessage = "unrestricted"; whitemessage = "Unrestricted";} This.canplay = true; This.repaint ();}} Click the Game Settings button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 120&& e.gety () <= 1 {String input = Joptionpane.showinputdialog ("Enter the maximum time (in minutes) of the game, if you enter 0, indicating no time limit:"); try {maxtime = Integer.parseint ( Input) * 60;IF (MaxTime < 0) {Joptionpane.showmessagedialog (this, "Please enter the correct information, not allowed to enter negative numbers!");} if (MaxTime = = 0) {int result = Joptionpane.showconfirmdialog (this, "set complete, do you want to start the game again?"); if (result = = 0) {for (int i = 0; i <, i++) {for (int j = 0; J < + j + +) {Allchess[i][j] = 0;}}  Another way allchess = new Int[19][19];message = "Black side first"; isblack = True;blacktime = Maxtime;whitetime = Maxtime;blackmessage = "Unrestricted"; whitemessage = "Unrestricted"; this.canplay = true; This.repaint ();}} if (MaxTime > 0) {int result = Joptionpane.showconfirmdialog (this, "set complete, do you want to start the game again?"); if (result = = 0) {for (int i = 0; i <, i++) {for (int j = 0; j < 19;J + +) {Allchess[i][j] = 0;}}  Another way allchess = new Int[19][19];message = "Black side first"; isblack = True;blacktime = Maxtime;whitetime = Maxtime;blackmessage = maxtime/3600 + ":" + (maxtime/60-maxtime/3600 *) + ":" + (MAXTIME-MAXTIME/60 *); whitemessage = MaxTime/ 3600 + ":" + (maxtime/60-maxtime/3600 *) + ":" + (MAXTIME-MAXTIME/60 *); T.resume (); this.canplay = true; This.repaint ();}}} catch (NumberFormatException E1) {//TODO auto-generated catch Blockjoptionpane.showmessagedialog (This, "Please enter information correctly!");} Click the game description button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 170&& e.gety () <= 2 XX) {Joptionpane.showmessagedialog (this, "a Gobang game program, in which the black and white parties take turns playing chess, when one party connects to five, the game is over. ");} Click the Defeat button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 270&& e.gety () <= 300 {int result = Joptionpane.showconfirmdialog (this, "Are you sure to concede?"); if (result = = 0) {if (isblack) {Joptionpane.showmessagedialog (this, "Black has conceded, the game is over!");}else {Joptionpane.showmessagedialog (this, "White has conceded, the game is over!");} CanPlay = false;}} Click about button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 320&& e.gety () <= 350 {Joptionpane.showmessagedialog (this, "The game is made by MLDN, there are related issues can be accessed www.mldn.cn");} Click the Exit button if (E.getx () >= && e.getx () <= 470 && e.gety () >= 370&& e.gety () <= 400 {Joptionpane.showmessagedialog (this, "Game Over"); System.exit (0);}} public void mousereleased (MouseEvent e) {//TODO auto-generated method Stub}private Boolean Checkwin () {Boolean flag = Fal se;//save a common color how many pieces are connected int count = 1;//Determine if there are 5 pieces connected, the feature ordinate is the same, that is, allchess[x][y] The Y value is the same int color = allchess[x][y];/* * IF (CO Lor = = Allchess[x+1][y]) {count++; if (color = = * Allchess[x+2][y]) {count++; if (color = = Allchess[x+3][y]) {* count++ ; }}} *///by looping to make a piece connected to the judgment */* int i = 1; while (color = = allchess[x + i][y + 0]) {count++; i++;} * i = 1; while (color = = allchess[x-i][y-0]) {count++; i++;} If * (COUNT >= 5) {flag = true;}//longitudinal judgment int i2 = 1; int count2 = 1; * while (color = = allchess[x + 0][y + i2]) {count2++; i2++;} i2 = 1; * while (color = = Allchess[x-0][y-i2]) {count2++; i2++;} if * (Count2 >= 5) {flag = true;}//Judgment in oblique direction (upper right + bottom left) int i3 = 1; int * Count3 = 1; while (color = = allchess[x + I3][y-i3]) {count3++; * i3++;} i3 = 1; while (color = = Allchess[x-i3][y + i3]) {count3++; * i3++;} if (Count3 >= 5) {flag = true;}//Oblique direction (bottom right + upper left) I NT I4 = * 1; int count4 = 1; while (color = = allchess[x + i4][y + i4]) {* count4++; i4++;} i4 = 1; while (color = = Allchess[x-i4][y-i4]) {* count4++; i4++;} if (Count4 >= 5) {flag = true;} *///judging horizontal count = Thi S.checkcount (1, 0, color); if (Count >= 5) {flag = true;} else {//determines portrait count = This.checkcount (0, 1, color); if (Count &G T;= 5) {flag = true;} else {//judgment upper right, bottom left count = This.checkcount (1,-1, color); if (Count >= 5) {flag = true;} else {//judgment right Bottom, top left count = This.checkcount (1, 1, color); (Count >= 5) {flag = True;}}}} return flag;} Determine the number of pieces connected private int checkcount (int xChange, int ychange, int color) {int count = 1;int tempx = Xchange;int Tempy = yCh  Ange;while (x + xChange >= 0 && x + xChange <= && y + ychange >= 0&& y + ychange <= 18&& color = = allchess[x + xchange][y + Ychange]) {count++;if (XChange! = 0) xchange++;if (ychange! = 0) {if (Ycha Nge > 0) ychange++;else {ychange--;}}} XChange = Tempx;ychange = Tempy;while (x-xchange >= 0 && x-xchange <= && y-ychange >= 0& amp;& y-ychange <= 18&& color = = Allchess[x-xchange][y-ychange]) {count++;if (XChange! = 0) xchange++; if (Ychange! = 0) {if (Ychange > 0) ychange++;else {ychange--;}}} return count;} public void Run () {//TODO auto-generated method stub//Determines if there is a time limit if (MaxTime > 0) {while (true) {if (isblack) {Blacktim E--;if (Blacktime = = 0) {Joptionpane.showmessagedialog (this, "Black side timeout, game over!");}} else {whitetime--;if (Whitetime = = 0) {Joptionpane.showmessagedialog (this, "Bai Fangsu, Game over!");}} Blackmessage = blacktime/3600 + ":" + (blacktime/60-blacktime/3600 *) + ":" + (BLACKTIME-BLACKTIME/60 *); w Hitemessage = whitetime/3600 + ":" + (whitetime/60-whitetime/3600 *) + ":" + (WHITETIME-WHITETIME/60 *); th Is.repaint (); try {thread.sleep ()} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} System.out.println (Blacktime + "--" + Whitetime);}}}
Then create a sub-frame interface:

Package Org.liky.game.frame;import Java.awt.color;import Java.awt.font;import java.awt.graphics;import Java.awt.toolkit;import Java.awt.event.mouseevent;import Java.awt.event.mouselistener;import Java.awt.image.bufferedimage;import Java.io.file;import Java.io.ioexception;import Javax.imageio.ImageIO;import Javax.swing.jframe;public class Mychessframe extends JFrame implements MouseListener {public mychessframe () { This.settitle ("five sons"); This.setsize (+), this.setresizable (false); This.setdefaultcloseoperation (Jframe.exit_ on_close); int width = Toolkit.getdefaulttoolkit (). Getscreensize (). Width;int height = Toolkit.getdefaulttoolkit (). Getscreensize (). Height;/*system.out.println ("width:" +width); System.out.println ("Height:" +height); */this.setlocation ((width-200)/2, (height-100)/2); This.addmouselistener (This) ; This.setvisible (true);} public void Paint (Graphics g) {/*g.drawstring ("Gobang game", Max.), *//*g.drawoval (20, 40, 40, 4 0); *//*g.drawline (*//*G);. DrawRect (G.fillrect, Max, max); */bufferedimage image = null;try {image = Imageio.read (new File ("e:/i") Mage/mldn text 01.jpg "));} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} G.drawimage (Image,0,0,this), G.drawoval ((), G.setcolor (Color.Blue), G.fillrect (+--), G.setfont ( New Font ("Arial", 40,40)); g.DrawString ("Gobang game", 20, 100);} public void mouseclicked (MouseEvent arg0) {//TODO auto-generated method stub}public void mouseentered (MouseEvent arg0) {/  /Todo auto-generated method stub}public void mouseexited (MouseEvent arg0) {//Todo auto-generated method stub}public void mousepressed (MouseEvent arg0) {//Todo auto-generated method stub}public void mousereleased (MouseEvent arg0) {//Todo Aut o-generated method Stub}}

The next call can be.

: Click to download

For more resources, please click: Mesh Search mu yi artifact Xiu Pan net

Java Swing Gobang Source code and implementation of Java Development graphical interface program Gobang implementation mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.