Java Board Game Practice stand-alone version of Gobang _java

Source: Internet
Author: User
Tags event listener getcolor gety set background

This article describes the Java implementation of the Gobang game code, shared for everyone to reference, the specific code as follows

First, the practical goal
1. Master Javagui Interface Design
2. Master the Monitor of Mouse event (Mouselistener,mousemotionlistener)
Ii. content of Practice
Design a simple Gobang program, can realize Gobang chess process. As shown in the following figure

1. Gobang Board Class

Package cn.edu.ouc.fiveChess; 
Import Java.awt.Color; 
Import Java.awt.Cursor; 
Import java.awt.Dimension; 
Import Java.awt.Graphics; 
Import Java.awt.Graphics2D; 
Import Java.awt.Image; 
Import Java.awt.RadialGradientPaint; 
Import java.awt.RenderingHints; 
Import Java.awt.Toolkit; 
Import java.awt.event.MouseEvent; 
Import Java.awt.event.MouseListener; 
Import Java.awt.event.MouseMotionListener; 
 
Import Java.awt.geom.Ellipse2D; 
Import javax.swing.*; /** * Gobang--Checkerboard class/public class Chessboard extends JPanel implements MouseListener {public static final int Margi  n=30;//margin public static final int grid_span=35;//grid spacing public static final int rows=15;//checkerboard row number public static final int cols=15;//Checkerboard Number point[] chesslist=new point[(rows+1) * (cols+1)];//initial each array element is null Boolean isblack=true;//the default start is black first Bo 
 Olean gameover=false;//whether the game ends int chesscount;//The number of current board pieces int xindex,yindex;//The index of the current chess piece img; 
 Image Shadows; 
 Color colortemp; 
  
 Public chessboard () { SetBackground (Color.Blue)//Set background color to orange img=toolkit.getdefaulttoolkit (). GetImage ("board.jpg"); 
  Shadows=toolkit.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; 
    Turn the coordinate position of mouse clicks into grid index int y1= (e.gety ()-margin+grid_span/2)/grid_span; The game has ended can not under//fall on the chessboard can not be under the//x,y position already have pieces exist, can not be under if (x1<0| | x1>rows| | y1<0| | y1>cols| | gameover| | 
    Findchess (x1,y1)) SetCursor (new Cursor (cursor.default_cursor)); 
    
   Set to default state else SetCursor (new Cursor (cursor.hand_cursor)); 
 } 
  }); //Draw public void paintcomponent (Graphics g) {super.paintcomponent (g);//Draw checkerboard int imgwidth= Img.getwi 
  DTH (this); 
  int Imgheight=img.getheight (this);//Get picture width and height int fwidth=getwidth (); int fheight=getheight ()//Get the width and height of the window 
  int x= (fwidth-imgwidth)/2; 
  int y= (fheight-imgheight)/2; 
  
   
  G.drawimage (IMG, x, y, null); 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 vertical bar g.drawline (Margin+i*grid_span, MARGIN, Margin+i*grid_span, Margin+rows*grid_spa 
    
  N); 
   ///Draw pieces for (int i=0;i<chesscount;i++) {//grid intersection x,y coordinate int xpos=chesslist[i].getx () *grid_span+margin; 
   int ypos=chesslist[i].gety () *grid_span+margin; G.setcolor (Chesslist[i].getcolor ())//Set color//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, New float[]{0f, 1f}, new Color[]{color.white, color.black}); 
    ((GRAPHICS2D) g). Setpaint (paint); 
    ((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, New float[]{0f, 1f}, New Color[]{color.white, color.black}); 
    ((GRAPHICS2D) g). Setpaint (paint); 
    ((GRAPHICS2D) g). Setrenderinghint (renderinghints.key_antialiasing, renderinghints.value_antialias_on); ((GRAPHICS2D) g). Setrenderinghint (Renderinghints.key_alpha_interpolation, Renderinghints.value_alpha_ 
 
   Interpolation_default); 
   } ellipse2d e = new Ellipse2d.float (XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, 34, 35); 
   ((GRAPHICS2D) g). Fill (e); The red rectangle that marks the last piece of the box if (i==CHESSCOUNT-1) {//If the last piece G.setcolor (color.red); 
   G.drawrect (XPOS-POINT.DIAMETER/2, YPOS-POINT.DIAMETER/2, 34, 35); 
   
  }} The public void mousepressed (MouseEvent e) {//mouse is not able to return under if (Gameover) when the call//game ends when pressed on the component; String colorname=isblack? " 
   
  Black chess ": White chess"; 
  Convert the coordinate position of the mouse click to Grid index xindex= (e.getx ()-margin+grid_span/2)/grid_span; 
   
  Yindex= (E.gety ()-margin+grid_span/2)/grid_span; Falling on the chessboard can not be under if (xindex<0| | xindex>rows| | yindex<0| | 
   
  Yindex>cols) return; 
   
  If the x,y position already has a piece exists, cannot under if (Findchess (Xindex,yindex)) return; Can be handled by point Ch=new Point (Xindex,yindex,isblack?). 
  Color.black:Color.white); 
  Chesslist[chesscount++]=ch; Repaint ()//Notification system redraw//If the winner is given a message, cannot continue to play chess if (Iswin ()) {String Msg=string.format ("Congratulations,%s won!") 
   ", colorname); 
   Joptionpane.showmessagedialog (this, msg); 
  Gameover=true; 
  } Isblack=!isblack; ///overwrite MouseListener method public void mouseclicked (MouseEvent e) {//Mouse pressCall} public void mouseentered (MouseEvent e) {//mouse entered on component when clicked} public void mouseexited (MouseEvent e) { 
    Boolean findchess (int x,int y) {for (point c:chesslist) {if (C!=null&&c.getx () ==x&&c.gety () ==y) 
  return true; 
 return false; 
   A private Boolean Iswin () {int continuecount=1;//the number of contiguous pieces//horizontal westward for (int x=xindex-1;x>=0;x--) { Color C=isblack? 
   Color.black:Color.white; 
   if (getchess (x,yindex,c)!=null) {continuecount++; 
  }else break; Find for (int x=xindex+1;x<=cols;x++) {Color c=isblack)//horizontally eastward? 
   Color.black:Color.white; 
   if (getchess (x,yindex,c)!=null) {continuecount++; 
  }else break; 
  } if (continuecount>=5) {return true; 
   
  }else continuecount=1; Continue with another search portrait//Up search for (int y=yindex-1;y>=0;y--) {Color c=isblack? Color.bLack:Color.white; 
   if (getchess (xindex,y,c)!=null) {continuecount++; 
  }else break; ///Portrait down for (int y=yindex+1;y<=rows;y++) {Color c=isblack? 
   Color.black:Color.white; 
   if (getchess (xindex,y,c)!=null) continuecount++; 
   
  else break; 
  } if (continuecount>=5) return true; 
   
   
  else continuecount=1; To continue the search for another situation: oblique//Northeast look for for (int x=xindex+1,y=yindex-1;y>=0&&x<=cols;x++,y--) {Color c=isblack? 
   Color.black:Color.white; 
   if (getchess (x,y,c)!=null) {continuecount++; 
  else break; //Southwest looking for (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) return true; 
   
   
  else continuecount=1; To continue the search for another situation: oblique/Northwest Looking for (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++; 
  else break; //Southeast looking for (int x=xindex+1,y=yindex+1;x<=cols&&y<=rows;x++,y++) {Color c=isblack? 
   Color.black:Color.white; 
   if (getchess (x,y,c)!=null) continuecount++; 
  else break; 
  } if (continuecount>=5) return true; 
   
  else continuecount=1; 
  return false; Private point getchess (int xindex,int yindex,color Color) {to (point p:chesslist) {if p!=null&&p. 
  GetX () ==xindex&&p.gety () ==yindex &&p.getcolor () ==color) return p; 
 return null; 
  public void Restartgame () {//Clear pawn for (int i=0;i<chesslist.length;i++) {chesslist[i]=null; 
  //restore game-related variable value isblack=true; Gameover=false; Whether the game is over chesscount = 0; 
 The current number of board pieces repaint (); 
  }//Undo 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 (); 
  } Isblack=!isblack; 
 Repaint (); 
       }//Rectangle Dimension public Dimension getpreferredsize () {return new Dimension (margin*2+grid_span*cols,margin*2 
 +grid_span*rows);  } 
  
  
  
}

2. Pawn class

Package cn.edu.ouc.fiveChess; 
 
Import Java.awt.Color; 
/** 
 * Pawn class/Public 
class Point { 
 private int x;//Chessboard x index 
 private int y;//The y index in the chessboard 
 private Color color;//Color public 
 static final int diameter=30;//diameter public point 
 
 (int x,int y,color color) { 
  this.x=x; 
  this.y=y; 
  This.color=color; 
 } 
 
 public int GetX () {//Get the index of x in the chessboard return 
  x; 
 } 
 public int GetY () {return 
  y; 
 } 
 Public color GetColor () {//Get the color of the checker return colour 
  ; 
 } 


3. Gobang Main Frame class

Package cn.edu.ouc.fiveChess; 
Import java.awt.event.*; 
 
Import java.awt.*; 
Import javax.swing.*; 
 /* Gobang main frame, program activation/public class Startchessjframe extends JFrame {private chessboard chessboard; 
 Private JPanel toolbar; 
 
 Private JButton Startbutton,backbutton,exitbutton; 
 Private JMenuBar MenuBar; 
 Private JMenu Sysmenu; 
 Private JMenuItem Startmenuitem,exitmenuitem,backmenuitem; 
  
  
  Restart, exit, and Undo menu item Public startchessjframe () {Settitle ("stand-alone version Gobang");/Set title Chessboard=new chessboard (); 
  Container Contentpane=getcontentpane (); 
  Contentpane.add (chessboard); 
  
  
  Chessboard.setopaque (TRUE); Create and Add menus MenuBar =new jmenubar ()//Initialize menu bar sysmenu=new jmenu ("system");//Initialize menu//Initialize menu item Startmenuitem=new jmenuite 
  M ("Re-start"); 
  Exitmenuitem =new JMenuItem ("exit"); 
  Backmenuitem =new JMenuItem ("undo"); 
  Add three menu items to the menus Sysmenu.add (startmenuitem); 
  Sysmenu.add (Exitmenuitem); 
  Sysmenu.add (Backmenuitem); Initialize button event listener inner class Myitemlistener lis=new MyitEmlistener (); 
  Register three menus on the event listener This.startMenuItem.addActionListener (LIS); 
  Backmenuitem.addactionlistener (LIS); 
  Exitmenuitem.addactionlistener (LIS); Menubar.add (Sysmenu);//Add System menu to Setjmenubar (MenuBar) on the menu bar;//Set MenuBar to menu bar toolbar=new JPanel ();//tool panel instantiation//Three Press 
  button to initialize startbutton=new JButton ("restart"); 
  Exitbutton=new JButton ("exit"); 
  Backbutton=new JButton ("undo"); 
  The tool panel button is FlowLayout layout toolbar.setlayout (new FlowLayout (Flowlayout.left)); 
  Add three buttons to the tool panel Toolbar.add (Startbutton); 
  Toolbar.add (Exitbutton); 
  Toolbar.add (Backbutton); 
  Register three buttons to monitor the event Startbutton.addactionlistener (LIS); 
  Exitbutton.addactionlistener (LIS); 
  Backbutton.addactionlistener (LIS); 
  Layout The tool panel to the interface "South" is also below add (Toolbar,borderlayout.south); 
  Add (chessboard);//sets the Panel object to the form/set interface Shutdown Event setdefaultcloseoperation (jframe.exit_on_close); 
  SetSize (800,800); Pack ();//Adaptive size} Private class Myitemlistener implements actionlistener{public void ActionperfOrmed (ActionEvent e) {Object obj=e.getsource ();//Get Event Source if (obj==startchessjframe.this.startmenuitem| | 
    Obj==startbutton) {//re-start//jfiveframe.this internal class reference external class System.out.println ("restart"); 
   Chessboard.restartgame (); else if (obj==exitmenuitem| | 
   Obj==exitbutton) system.exit (0); else if (obj==backmenuitem| | 
    Obj==backbutton) {System.out.println ("undo ..."); 
   Chessboard.goback (); }} public static void Main (string[] args) {startchessjframe f=new startchessjframe ();//create main frame F.SETVI 
 Sible (TRUE);//Show Main Frame}}

Third, summary
1. Design and implementation of the menu?
2. After the mouse click on the chessboard, how to draw pieces? How do I draw a red box for just the next piece?
3. How is games a data structure?

The above is the entire content of this article, I hope to learn Java program to help you.

Related Article

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.