Stand-alone version Gobang
This little game is my sisters and I Java curriculum design, but also I did the first Java project, suitable for beginners, hoping to help those who are haunted by the Java class paper ~ ~ ~ ~
One, the game needs to achieve:
1, the design of the main frame, interface.
2, the use of ActionListener interface to implement the monitoring of button events.
3. Re-start the implementation of the function.
4, the realization of undo function.
5, the implementation of the Exit function.
6. The definition of the pawn point class in the chessboard.
7, using MouseListener interface to implement event monitoring, and implement all the methods in the interface.
8, when the mouse is moved to the intersection point on the board, and there is no piece on the spot can become small hand shape.
9, click on the chessboard, using the IF statement to determine whether the point points at the intersection, and using the foreach statement and the Getx (), GetY () method to determine the position of each piece to judge whether there are pieces.
10, when judged to be able to click on the point up and down, the use of a For loop to iterate over each point and use the Graphics class SetColor set color, using the Graphics class Filloval method to set the shape size.
11, when the finished pieces to be judged in time to win or lose, with the pieces of the index and for the loop to traverse the last piece of each direction, if there is a line in the same number of pieces is greater than five of the current piece represents the side win.
12, when the outcome has been decided, can pop the appropriate information.
Second, the function code realization
2.1 into the game
public static void Main (string[] args) {
startchessjframe f=new startchessjframe ();//create main frame
f.setvisible (True) ;//Show main frame
}
2.2 Initialization, define some amount to use.
Private chessboard chessboard;//battle panel
Private Panel toolbar;//bar panel
private button startbutton;//setting Start button
Private button backbutton;//Set Undo button
Private button exitbutton;//Set Exit button
2.3 The construction method of the interface (the frame of the game)
Public Startchessjframe () {
settitle ("standalone Gobang");//Set title
chessboard=new chessboard ();//Initialize Panel object, create and Add menus
Myitemlistener lis=new Myitemlistener ()//Initialize button event listener inner class
toolbar=new panel ()//tool palette bar instantiation
startbutton=new Button ("Start Again");
Backbutton=new button ("undo");
Exitbutton=new button ("exit");//three button to initialize
toolbar.setlayout (new FlowLayout (Flowlayout.left)); The tool panel button is FlowLayout layout
toolbar.add (Backbutton);
Toolbar.add (Startbutton);
Toolbar.add (Exitbutton);//Add three buttons to the tool panel
Startbutton.addactionlistener (LIS);
Backbutton.addactionlistener (LIS);
Exitbutton.addactionlistener (LIS)//Three button events registered listener Event
Add (Toolbar,borderlayout.south); The tool panel is laid out to the south. Add
(chessboard);//Adds a Panel object to the form
setdefaultcloseoperation (jframe.exit_on_close);/set interface Shutdown Event
pack () ;//Adaptive size
}
implementation and monitoring of 2.4 buttons (internal construction method)
Myitemlistener lis=new Myitemlistener ()//Initialize button event listener inner class
toolbar=new panel ()//tool palette bar instantiation
startbutton=new Button ("Start Again");
Backbutton=new button ("undo");
Exitbutton=new button ("exit");//three button to initialize
toolbar.setlayout (new FlowLayout (Flowlayout.left)); The tool panel button is FlowLayout layout
toolbar.add (Backbutton);
Toolbar.add (Startbutton);
Toolbar.add (Exitbutton);//Add three buttons to the tool panel
Startbutton.addactionlistener (LIS);
Backbutton.addactionlistener (LIS);
Exitbutton.addactionlistener (LIS)//Three button events registered to listen for events
2.5 Monitoring of button events
Private class Myitemlistener implements actionlistener{public
void actionperformed (ActionEvent e) {
Object obj =e.getsource ()//Get Event Source
if (Obj==startbutton) {
System.out.println ("Restart ...");//Start again
// Jfiveframe.this internal class reference external class
chessboard.restartgame ();
} else if (Obj==exitbutton) {
system.exit (0);//End application
}else if (Obj==backbutton) {
System.out.println ("Undo ... ");//Undo
Chessboard.goback ();}}}
2.6 Function Realization of restart button
public void Restartgame () {//Clear pawn for
(int i=0;i<chesslist.length;i++)
chesslist[i]=null;
/* Restore game-related variable value * *
isback=true;
gameover=false;//whether the game ends
chesscount=0;//the number of pieces on the current chessboard
repaint ();
}
2.7 Undo Button's function realization
public void GoBack () {
if (chesscount==0) return
;
Chesslist[chesscount-1]=null;
chesscount--;
if (chesscount>0) {
xindex=chesslist[chesscount-1].getx ();
Yindex=chesslist[chesscount-1].gety ();
}
Isback=!isback;
Repaint ();
}
2.8 When the Board on the need to grow or change the hours window should be changed
Dimension: Rectangle Chessboard Class Internal public
Dimension getPreferredSize () {return
new Dimension (Margin*2+grid_span *cols,margin*2+grid_span*rows);
}
Pack ();//Adaptive Size Startchessboard class internal
2.9 Defining a pawn class
Import java.awt.*;
public class Point {
private int x;//Pawn x index value in the chessboard
private int y;//The Y index value of the chess piece in the chessboard
private color color;//colors
public static int diameter=30;//diameter public point
(int x,int y,color Color) {
this.x=x;
this.y=y;
This.color=color;
}
Get the X index value of the pawn in the chessboard public
int GetX () {return
x;
}
Get the Y index value of the pawn in the chessboard public
int GetY () {return
y;
}
Get pieces Color public colors
GetColor () {return
color;
}
}
Third, the function part code realizes
3.1 initialization, define some amount to use.
public static int margin=30;//margin public
static int grid_span=35;//grid spacing public
static int rows=18;//Checkerboard line number
public static int cols=18;//checkerboard number
point[] chesslist=new point[(rows+1) * (cols+1)];//initialize each array element as null
Boolean isback=true;//The default start is black first
Boolean gameover=false;//whether the game ends
int chesscount;//The current chessboard of the number of pieces
int Xindex, yindex;//the current index of a pawn
the construction method of 3.2 Checkerboard Object
Public chessboard () {
setbackground (Color.light_gray);//Set background color to gray
Addmouselistener (this);//Add Event listener
Addmousemotionlistener (New Mousemotionlistener () {//anonymous inner class
@Override public
void mousemoved (MouseEvent e) {
int x1= (E.GETX ()-margin+grid_span/2)/grid_span;
int y1= (e.gety ()-MARGIN+GRID_SPAN/2)/grid_span;//converts the coordinate position of the mouse click to the grid index
if (x1<0| | x1>rows| | y1<0| | y1>cols| | gameover| | Findchess (x1,y1)) {//The game is over, cannot fall, falls outside the chessboard, cannot under, x,y position already has the piece existence, cannot under
setcursor (New Cursor (cursor.default_cursor)); Set to default shape
}else{
setcursor (New Cursor (cursor.hand_cursor));//set to hand type
}
}
@Override
public void mousedragged (MouseEvent e) {
}
});
3.3 Set the mouse listener, the small hand (in the construction method inside)
Addmousemotionlistener (New Mousemotionlistener () {//anonymous inner class
@Override public
void mousemoved (MouseEvent e) {
int x1= (E.GETX ()-margin+grid_span/2)/grid_span;
int y1= (e.gety ()-MARGIN+GRID_SPAN/2)/grid_span;//converts the coordinate position of the mouse click to the grid index
if (x1<0| | x1>rows| | y1<0| | y1>cols| | gameover| | Findchess (x1,y1)) {//The game is over, cannot fall, falls outside the chessboard, cannot under, x,y position already has the piece existence, cannot under
setcursor (New Cursor (cursor.default_cursor)); Set to default shape
}else{
setcursor (New Cursor (cursor.hand_cursor));//set to hand type
}
}
@Override
public void mousedragged (MouseEvent e) {
}
});
Mouse Press event at 3.4 Click on the Chessboard
The public void mousepressed (MouseEvent e) {//mouse button is pressed on the component to invoke
if (Gameover)/The game is over and cannot be return
;
String Colorname=isback? "Black Chess": "White chess";
Xindex= (E.getx ()-margin+grid_span/2)/grid_span;
Yindex= (E.gety ()-MARGIN+GRID_SPAN/2)/grid_span;//converts the coordinate position of the mouse click to the grid index
if (xindex<0| | xindex>rows| | yindex<0| | Yindex>cols)//Chess pieces fell on the board outside, can not return
;
if (findchess (xindex,yindex))//x,y position already has a piece exists, cannot return
;
Point Ch=new Point (xindex,yindex,isback?) Color.black:Color.white);
Chesslist[chesscount++]=ch;
Repaint ()//notifies
the system to redraw if (Iswin ()) {
String Msg=string.format ("Congratulations,%s win ~", colorname);
Joptionpane.showmessagedialog (this, msg);
gameover=true;
}
else if (chesscount== (cols+1) * (rows+1))
{
String msg=string.format ("Chess drum quite, bang-bang");
Joptionpane.showmessagedialog (this,msg);
gameover=true;
}
Isback=!isback;
}
3.5 To draw the chessboard, the pawn and the Red box
public void Paintcomponent (Graphics g) {
super.paintcomponent (g);//Draw a chessboard for
(int i=0;i<=rows;i++) {//Draw horizontal Line
g.drawline (MARGIN, Margin+i*grid_span, Margin+cols*grid_span, Margin+i*grid_span);
for (int i=0;i<=cols;i++) {//Draw straight line
G.drawline (Margin+i*grid_span, MARGIN, margin+i*grid_span,margin+rows*grid_ SPAN);
/* Draw pieces *
/for (int i=0;i<chesscount;i++) {
int xpos=chesslist[i].getx () *grid_span+margin;//grid intersection x coordinate
int ypos=chesslist[i].gety () *grid_span+margin;//grid intersection y-coordinate
G.setcolor (Chesslist[i].getcolor ());//Set Color
G.filloval (XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, Point.diameter, point.diameter);
if (i==chesscount-1) {
g.setcolor (color.red);//mark the last piece as a red
g.drawrect (XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, Point.diameter, Point.diameter);}}
3.6 to judge or lose
/* judge which side wins/private Boolean Iswin () {int continuecount=1;//contiguous pieces for (int x=xindex-1;x>=0;x--) {//horizontal left for Color c= Isback?
Color.black:Color.white;
if (getchess (x,yindex,c)!=null) {continuecount++;
}else break; for (int x=xindex+1;x<=rows;x++) {//horizontally looking to the right Color c=isback?
Color.black:Color.white;
if (getchess (x,yindex,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int y=yindex-1;y>=0;y--) {//portrait looking up Color c=isback?
Color.black:Color.white;
if (getchess (xindex,y,c)!=null) {continuecount++;
}else break; for (int y=yindex+1;y<=rows;y++) {//Portrait down search for Color c=isback?
Color.black:Color.white;
if (getchess (xindex,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int x=xindex+1,y=yindex-1;y>=0&&x<=cols;x++,y--) {//lower right look for Color c=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break; for (int x=xindex-1,y=yindex+1;y<=rows&&x>=0;x--, y++) {//top left to find Color C=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int x=xindex-1,y=yindex-1;y>=0&&x>=0;x--, y--) {//lower left to find Color C=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break; for (int x=xindex+1,y=yindex+1;y<=rows&&x<=cols;x++,y++) {//Right to look for Color c=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1;
return false; }
3.7 Popup corresponding message box (inside the mouse press function)
if (Iswin ()) {
String Msg=string.format ("Congratulations,%s wins ~", colorname);
Joptionpane.showmessagedialog (this, msg);
gameover=true;
}
else if (chesscount== (cols+1) * (rows+1))//Draw
{
String msg=string.format ("Chess drum quite, bang-bang");
Joptionpane.showmessagedialog (this,msg);
gameover=true;
}
3.8 A function used to determine whether a piece is in a certain point
Private Boolean findchess (int x,int y) {for
(point c:chesslist) {
if (C!=null&&c.getx () ==x&& C.gety () ==y) return
true;
}
return false;
}
3.9 Because the chessboard class implements the mouse listener interface Monselistener, to rewrite all the methods within the interface, the other methods are as follows
@Override public
void mouseclicked (MouseEvent e) {//mouse button is called when clicked (pressed and released) on the component
@Override public
Void mousereleased (MouseEvent e) {////mouse button is released on the assembly
@Override public
void mouseentered (MouseEvent e) {// Called when the mouse enters the component
@Override public
void mouseexited (MouseEvent e) {//Mouse leaves component
}
Iv. Results of operation
Five, Code summary
The game built a total of three classes, one is the interface Startchessjframe, one is a chessboard class chessboard, one is the chess class point
5.1StartChessJFrame class
Package chess.lcc.com;
Import javax.swing.*;
Import java.awt.event.*;
Import java.awt.*; * * Gobang main frame, program startup class * * public class Startchessjframe extends JFrame {private chessboard chessboard;//battle Panel private Pane L toolbar;//Bar Panel private button startbutton;//Set Start button Private button backbutton;//set Undo button Private button exitbutton;//settings Exit button public Startchessjframe () {settitle ("standalone Gobang");/Set the title Chessboard=new chessboard ();//Initialize Panel object, create and add menu Myitemli
Stener lis=new Myitemlistener ()//Initialize button event listener inner class toolbar=new panel ()//tool palette Bar Instantiate Startbutton=new button ("restart");
Backbutton=new button ("undo");
Exitbutton=new button ("exit");//three buttons initialize Toolbar.setlayout (new FlowLayout (Flowlayout.left))//tool panel buttons FlowLayout layout
Toolbar.add (Backbutton);
Toolbar.add (Startbutton);
Toolbar.add (Exitbutton);//Add three buttons to the tool panel Startbutton.addactionlistener (LIS);
Backbutton.addactionlistener (LIS); Exitbutton.addactionlistener (LIS)//Three button events registered to listen for event Add (Toolbar,borderlayout.south);//The tool panel is laid out to the South that's the following adD (chessboard);//Add a Panel object to the form setdefaultcloseoperation (jframe.exit_on_close);/set interface Shutdown Event Pack ();//Adaptive size} private Clas s Myitemlistener implements actionlistener{public void actionperformed (ActionEvent e) {Object obj=e.getsource ();//obtained Fetch Event Source if (Obj==startbutton) {System.out.println ("restart ...");//restart//jfiveframe.this internal class reference outer class Chessboard.restar
Tgame ();
}else if (Obj==exitbutton) {system.exit (0);//End Application}else if (Obj==backbutton) {System.out.println ("undo ...");//Undo
Chessboard.goback (); }} public static void Main (string[] args) {startchessjframe f=new startchessjframe ();//create main frame f.setvisible
(true);//Show Main Frame}}
5.2ChessBoard class
Package chess.lcc.com;
Import javax.swing.*;
Import java.awt.*;
Import Java.awt.event.MouseListener;
Import Java.awt.event.MouseMotionListener;
Import java.awt.event.MouseEvent; /* Gobang-Chessboard class/public class Chessboard extends JPanel implements mouselistener{public static int margin=30;//margin public sta tic int grid_span=35;//grid spacing public static int rows=15;//Checkerboard row number public static int cols=15;//checkerboard number point[] Chesslist=new Poi nt[(rows+1) * (cols+1)];//initializes each array element to null Boolean isback=true;//default start is black first Boolean gameover=false;//game whether end int chesscount;//the number of pieces in the current chessboard int xindex,yindex;//The index of the current pawn is public chessboard () {setbackground (Color.light_gray);/
Set the background color to yellow addmouselistener (this);//Add Event Listener Addmousemotionlistener (new Mousemotionlistener () {//anonymous inner class @Override
public void mousemoved (MouseEvent e) {int x1= (E.GETX ()-margin+grid_span/2)/grid_span; int y1= (e.gety ()-MARGIN+GRID_SPAN/2)/grid_span;//converts the coordinate position of the mouse click to the grid index if (x1<0| | x1>rows| | y1<0| | y1>cols| | gameover| | FindchesS (x1,y1)) {//The game is over, cannot fall, falls outside the chessboard, cannot be under; X,y position already has a piece exists, cannot under SetCursor (new Cursor (cursor.default_cursor));/Set as default shape}else{ SetCursor (New Cursor (Cursor.hand_cursor)),//set to hand type}} @Override public void mousedragged (MouseEvent E
) {
}
});
/* Draw */public void paintcomponent (Graphics g) {super.paintcomponent (g);//Draw a chessboard for (int i=0;i<=rows;i++) {//Draw horizontal Line
G.drawline (MARGIN, Margin+i*grid_span, Margin+cols*grid_span, Margin+i*grid_span); for (int i=0;i<=cols;i++) {//Draw straight line G.drawline (Margin+i*grid_span, MARGIN, Margin+i*grid_span,margin+rows*grid_span
); /* Draw pieces * * for (int i=0;i<chesscount;i++) {int xpos=chesslist[i].getx () *grid_span+margin;//grid cross x coordinate int ypos=ch Esslist[i].gety () *grid_span+margin;//the y-coordinate of the grid intersection G.setcolor (Chesslist[i].getcolor ());//Set Color G.filloval (
XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, Point.diameter, Point.diameter); if (i==chesscount-1) {g.setcolor (color.red);//mark the last pawn as a red g.drawrect (xpos-point.diameter/2, YPOS-POINT.DIAMETER/2, Point.diameter, Point.diameter);
}} @Override public void mousepressed (MouseEvent e) {//mouse button is pressed on the component to invoke if (Gameover)/The game is over and cannot be return; String Colorname=isback?
"Black Chess": "White Chess";
Xindex= (E.getx ()-margin+grid_span/2)/grid_span; Yindex= (E.gety ()-MARGIN+GRID_SPAN/2)/grid_span;//converts the coordinate position of the mouse click to the grid index if (xindex<0| | xindex>rows| | yindex<0| |
Yindex>cols)//Chess pieces fell on the board outside, can not return;
if (findchess (xindex,yindex))//x,y position already has a piece exists, cannot return; Point Ch=new Point (xindex,yindex,isback?)
Color.black:Color.white);
Chesslist[chesscount++]=ch;
Repaint ()//notifies the system to redraw if (Iswin ()) {String Msg=string.format ("Congratulations,%s win ~", colorname);
Joptionpane.showmessagedialog (this, msg);
Gameover=true;
else if (chesscount== (cols+1) * (rows+1)) {String Msg=string.format ("Chess drum quite, bang-bang");
Joptionpane.showmessagedialog (THIS,MSG);
Gameover=true;
} Isback=!isback; @Override public void mouseclicked (MouseEvent e) {//mouse button click on the component (press@Override public void mousereleased (MouseEvent e) {////mouse button is released on the assembly when called} @Override public void Mouseentere D (mouseevent e) {//When the mouse enters the component call} @Override public void mouseexited (MouseEvent e) {//mouse to leave the component when calling} private Boolean fin
dchess (int x,int y) {for (point c:chesslist) {if (C!=null&&c.getx () ==x&&c.gety () ==y) return true;
return false; }/* Judge the party to win/private Boolean Iswin () {int continuecount=1;//contiguous pieces for (int x=xindex-1;x>=0;x--) {//horizontal left to find Col or C=isback?
Color.black:Color.white;
if (getchess (x,yindex,c)!=null) {continuecount++;
}else break; for (int x=xindex+1;x<=rows;x++) {//horizontally looking to the right Color c=isback?
Color.black:Color.white;
if (getchess (x,yindex,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int y=yindex-1;y>=0;y--) {//portrait looking up Color c=isback?
Color.black:Color.white; if (GetcheSS (Xindex,y,c)!=null) {continuecount++;
}else break; for (int y=yindex+1;y<=rows;y++) {//Portrait down search for Color c=isback?
Color.black:Color.white;
if (getchess (xindex,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int x=xindex+1,y=yindex-1;y>=0&&x<=cols;x++,y--) {//lower right look for Color c=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break; for (int x=xindex-1,y=yindex+1;y<=rows&&x>=0;x--, y++) {//top left to find Color C=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1; for (int x=xindex-1,y=yindex-1;y>=0&&x>=0;x--, y--) {//lower left to find Color C=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++; }else break; for (int x=xindex+1,y=yindex+1;y<=rows&&x<=cols;x++,y++) {//Right to look for Color c=isback?
Color.black:Color.white;
if (getchess (x,y,c)!=null) {continuecount++;
}else break;
} if (continuecount>=5) {//The number of records is greater than or equal to five, that means the party wins return true;
}else continuecount=1;
return false; Private point getchess (int xindex,int yindex,color Color) {to (point c:chesslist) {if (C!=null&&c.getx () ==x
Index&&c.gety () ==yindex&&c.getcolor () ==color) return C;
return null;
public void Restartgame () {//Clear pawn for (int i=0;i<chesslist.length;i++) chesslist[i]=null;
/* Restore game-related variable value * * ISBACK=TRUE;
gameover=false;//whether the game ends chesscount=0;//the number of pieces of the current chessboard repaint ();
public void GoBack () {if (chesscount==0) return;
Chesslist[chesscount-1]=null;
chesscount--;
if (chesscount>0) {xindex=chesslist[chesscount-1].getx ();
Yindex=chesslist[chesscount-1].gety ();
} Isback=!isback;
Repaint (); //dimension: Rectangle public Dimension getpreferredsize () {return new Dimension (Margin*2+grid_span*cols,margin*2+grid_span
*rows);
}
}
5.3Point class
Package chess.lcc.com;
Import java.awt.*;
public class Point {
private int x;//Pawn x index value in the chessboard
private int y;//The Y index value of the chess piece in the chessboard
private color color;//colors
public static int diameter=30;//diameter public point
(int x,int y,color Color) {
this.x=x;
this.y=y;
This.color=color;
}
Get the X index value of the pawn in the chessboard public
int GetX () {return
x;
}
Get the Y index value of the pawn in the chessboard public
int GetY () {return
y;
}
Get pieces Color public colors
GetColor () {return
color;
}
}