Gobang Game Source

Source: Internet
Author: User
Tags gety


This is Gobang's final, the chess board and the chess piece are the program drawing. The source code of the dedicated person below.

Gobanggui.java This source file is mainly the implementation of the interface

Package Game.gobang;import Java.awt.borderlayout;import Java.awt.color;import java.awt.gridlayout;import Java.awt.event.actionevent;import Java.awt.event.actionlistener;import Java.awt.event.mouseadapter;import Java.awt.event.mouseevent;import Java.awt.event.mouselistener;import Javax.swing.box;import Javax.swing.ImageIcon ; Import Javax.swing.jbutton;import javax.swing.jframe;import javax.swing.jlabel;import Javax.swing.JOptionPane; Import Javax.swing.jpanel;public class Gobanggui extends jframe{private JPanel mainframe;private gobangboard Board; Private JPanel control;private GridLayout grid;private borderlayout border;private JButton start;private JButton end; Private JLabel label;private int row;private int column;private Gobang gobang;private mouseadapter mouselistener;private Boolean flag;private boolean ok;private actionlistener actionlistener;public Gobanggui () {This ("Gobang Game", 10, 10);} Public Gobanggui (String title, int row, int column) {super (title);//this.setundecorated (true); tHis.row = Row;this.column = Column;this.flag = False;this.ok = False;initial (); setSize (+); This.setresizable ( FALSE); This.setdefaultcloseoperation (jframe.exit_on_close); Setlocationbyplatform (true); This.setvisible (true); This.requestfocus ();} private void Initial () {createcomponent (); LayOut (); Listener ();} private void Createcomponent () {mainframe = new JPanel (); control = new JPanel (); border = new BorderLayout (); Grid = new Gri Dlayout (); start = new JButton ("Start"), label = new JLabel (); Gobang = new Gobang (row, column); board = new Gobangboard (Goban g, row, column), end = new JButton ("Exit"),//gobang.getdata () [0][0] = gobangcolor.white;} private void LayOut () {This.getcontentpane (). Add (mainframe);//setbackpicture ();//mainframe.setbackground ( Color.yellow); mainframe.setlayout (border); Mainframe.add (board, Borderlayout.center);//board.setbounds (0, 0, 500, Mainframe.add (control, borderlayout.east); Box ve = Box.createverticalbox (); Ve.add (start); Ve.add (Box.createverticalstrut); End.setsize (Start.getwidth (), Start.getheight ()); Ve.add (end); Control.add (ve);} private void Setbackpicture () {ImageIcon a = new ImageIcon ("/home/qcq/1.jpg"); JLabel p = new JLabel (a);p. SetBounds (0, 0, a.geticonwidth (), A.geticonheight ()), This.getlayeredpane (). Add (P, Integer.min_value);} /* * Determine the position index (x, y) of the mouse falling into the board pane as the current mouse coordinates. */private Place Judgeplace (int Indexx, int. indexy, int x, int y, int squre) {for (int i = 0; i < row; i++) {for (int j = 0; J < column; J + +) {if (x >= Indexx + J * Squre && x <= Indexx + (j + 1) * Squre&&y >= indexy + i * squre && Amp Y <= indexy + (i + 1) * squre) {return new place (I, j);}} return null;} private void Listener () {MouseListener = new Mouseadapter () {@Overridepublic void mousepressed (MouseEvent e) {int x = e.ge TX (); int y = e.gety ();/* * (+) is a special coordinate. The board draw begins here, * If the board added to the this JFrame the "Begin Change" to * (+), however, I do n OT know why. Just keep it; * */IF (OK) {Place temp = Judgeplace (+, x, Y, Board.getsqure ()); System.out.println (temp), if (flag) {if (!gobang.check (Temp.getx (), Temp.gety ())) {Joptionpane.showmessagedialog ( Mainframe, "Change Another Place");} else {gobang.setchess (Temp.getx (), Temp.gety (), gobangcolor.white); repaint (); if (Gobang.issuccess (new place (0, 0), New Place (Row-1, column-1), Gobangcolor.white)) {//joptionpane.showmessagedialog (mainframe, "The white player is win"); int choice = Joptionpane.showconfirmdialog (mainframe, "The white player is win", "does you want try again", Joptionpane.yes_ No_option); if (choice = = joptionpane.yes_option) {gobang.initial (); ok = False;repaint ();}} Flag = FALSE;}} else {if (!gobang.check (Temp.getx (), Temp.gety ())) {Joptionpane.showmessagedialog (mainframe, "change Another Place");} else {gobang.setchess (Temp.getx (), Temp.gety (), gobangcolor.black); repaint (); if (Gobang.issuccess (new place (0, 0), New Place (Row-1, column-1), Gobangcolor.black) {//joptionpane.showmessagedialog (mainframe, "the BLACK Player is win "), int choice = Joptionpane.showconfirmdialog (mainframe," The black player is win "," does you want try again ", Joptionpane.yes_no_option); if (choice = = joptionpane.yes_option) {gobang.initial (); ok = False;repaint ();}} Flag = True;}}} else {Joptionpane.showmessagedialog (mainframe, "Please start the game");}}; ActionListener = new ActionListener () {@Overridepublic void actionperformed (ActionEvent e) {if ((JButton) (E.getsource ( )). GetText (). Equals ("Start")) {OK = true;} else if ((JButton) (E.getsource ())). GetText (). Equals ("Exit")) { System.exit (0);}}; Board.addmouselistener (MouseListener); Start.addactionlistener (ActionListener); End.addactionlistener ( ActionListener);} public static void Main (string[] args) {Gobanggui game = new Gobanggui (NULL, 20, 20);}}

Gobangboard.java This document is a drawing of the chessboard

Package Game.gobang;import Java.awt.basicstroke;import Java.awt.color;import java.awt.graphics;import Java.awt.graphics2d;import Java.awt.layoutmanager;import Javax.swing.jpanel;public class GoBangBoard extends JPanel { Private Gobang gobang;private int row;private int column;private int squre;public gobangboard () {//this.setbounds (x, Y, WI DTH, height);} Public Gobangboard (Gobang gobang, int row, int column) {This.gobang = Gobang;this.column = Column;this.row = row;} public int getsqure () {return squre;} public void Paint (Graphics g) {graphics2d GG = (graphics2d) g;squre = (This.getwidth ()-()/Math.max (row, column);/** * F Rom the point (+) draw the game ' s background. * *//* * Below draw the background gird. * */int x = 25;int y = 10;gg.setstroke (new Basicstroke (0.5f, Basicstroke.cap_round, Basicstroke.join_round, 1.0f,new float  []{5f, 5f},0f)]; Gg.setcolor (Color.Blue); for (int i = 0; i < row; i++) {for (int j = 0; j < column; J + +) {Gg.drawrect (x + J * Squre, y + i * squre, squre, squre);}} for (int i = 0; i < gobang.getdata (). length, i++) {for (int j = 0; J < Gobang.getdata () [I].length; j + +) {if (Gobangcol Or.  White = = Gobang.getdata () [i][j]) {gg.setcolor (Color.Blue); Gg.filloval (x + j * squre, y + i * squre, squre, squre);} else if (Gobangcolor.black = = Gobang.getdata () [i][j]) {Gg.setcolor (Color.Black); Gg.filloval (x + j * squre, y + i * squre, squre, squre);}}} Gg.setstroke (New Basicstroke (5f)); Gg.setcolor (Color.Blue); Gg.drawrect (X-1, y-1, squre * column + 2, squre * row + 2); g G.dispose ();}}
Gobangcolor.java This file is an enumeration definition of the color of a pawn.

Package Game.gobang;public enum Gobangcolor {black,white,null}

Placejava This document is a definition of the position of a pawn.

Package game.gobang;/** * Here lays the snake ' s body coordinate information. * */public class Place {private int x;private int Y;public Place () {This (0, 0);} public place (int x, int y) {this.x = X;this.y = y;} public int GetX () {return x;} public void SetX (int x) {this.x = x;} public int GetY () {return y;} @Overridepublic String toString () {return "place [x=" + x + ", y=" + y + "]";} public void sety (int y) {this.y = y;} @Overridepublic int hashcode () {final int prime = 31;int result = 1;result = Prime * result + X;result = Prime * result + Y;return result;} @Overridepublic boolean equals (Object obj) {if (this = = obj) return true;if (obj = = null) return False;if (GetClass ()! = obj . GetClass ()) return false; Place other = (place) obj;if (x! = other.x) return false;if (Y! = other.y) return False;return true;}}

Gobang.java This file is the core logic code implemented by Gobang

Package Game.gobang;import java.util.scanner;/** * Question 19, using two-dimensional array to achieve Gobang chess function * */public class Gobang {private Gobangcol or[][] data;private int row = 10;private int column = 10;public Gobang () {/* * The default checkerboard is ten boxes; * */this (Ten); Initial ();} /* * Initial the Game * */public void Initial () {for (int i = 0; i < row, i++) {for (int j = 0; j < column; J + +) {data[ I][J] = Gobangcolor.null;}}} /* * The piece move * */public void setchess (int row, int column,gobangcolor color) {Data[row][column] = color;} public Gobang (int row, int column) {/* * Set the Chess squre to row * Line * */this.row = Row;this.column = Column;data = n EW gobangcolor[row][];for (int i = 0; i < row; i++) {Data[i] = new Gobangcolor[column];} Initial ();} Public gobangcolor[][] GetData () {return data;} public void SetData (gobangcolor[][] data) {this.data = data;} public int GetRow () {return row;} public void Setrow (int row) {this.row = row;} public int GetColumn () {return column;} public void Setcolumn (int column) {this.column = column;} /* Print out the current checkerboard * */public void Printcheckerboard () {/* * print out the chessboard layout * */FOR ( Gobangcolor[] i:data) {for (Gobangcolor j:i) {System.out.print (j.tostring () + "");} System.out.println ();}}  /* * Verify the input data to insure the piece are in the range * and not put this piece in the history place * Verify the pieces in the right position  * */public boolean check (int x, int y) {if (x < 0 | | x >= Row | | Y < 0 | | y >= column) {System.out.println ("the Input is Error "); SYSTEM.OUT.PRINTLN ("The input should from (0, 0) to (" + (x-1) + "," + (y-1) + ")"); return false;} if (gobangcolor.null! = Data[x][y]) {System.out.println ("This place already have one piece!"); return false;} return true;} /* * Judge if successed, the parameter x and Y * are the range which need to be scanning. * The scanning range can zoom in a range which are a circle (a square) * Center in current move, RADIUS is 5. * Scan the board to see if there is a pawn to win, you can optimize the scanning scheme, the scope of the scan to a lazi center * 5 for the radius of the board (Issucess overloaded methods to implement this idea). */public Boolean issuccess (place x, place y, Gobangcolor color) {Boolean flag = False;int counter = 0;label:for (int i = (i NT) X.getx (); I <= (int) y.getx (); i++) {for (int j = (int) x.gety (); J <= (int) y.gety (); j + +) {/* * scanning the [x, Y] range in 4 directions. * *///Check T He horizontalcounter = 0;if (j + 4 <= (int) y.gety ()) {for (int index = j; Index <= j + 4; index++) {if (color = = data[ I][index]) {counter++;}}} if (5 = = counter) {flag = True;break label;} Check the Verticalcounter = 0;if (i + 4 <= (int) y.getx ()) {for (int index = i; index <= i + 4; index++) {if (color = = Data[index][j]) {counter++;}}} if (5 = = counter) {flag = True;break label;} Check the dig Linecounter = 0;if ((i + 4 <= (int) y.getx ()) && (j + 4 <= (int) y.gety ())) {for (int indexx = I, indexy = j; Indexx <= i + 4; indexx++, indexy++) {if (color = = Data[indexx][indexy]) {counter++;}}} if (5 = = counter) {flag = True;break label;} Check the reverse dig Linecounter = 0;if ((i + 4 <= (int) y.getx ()) && (j-4 >= (int) x.gety ())) {for (int indexx = i, indexy = j; Indexx <= i + 4;indexx++, indexy--) {if (color = = Data[indexx][indexy]) {counter++;}}} if (5 = = counter) {flag = True;break label;}}} return flag; }/* * This is an overloaded method, unlike the previous method, which does not use a scan to implement the decision * but is based on the Lazi place, to be counted in four directions.  * */public Boolean issuccess (place x, Gobangcolor color) {Boolean flag = false;/* * Horizontal direction * */int counter = 0;for (int i = x.gety (); I >= math.min (X.gety ()-4, row); i--) {if (color = = Data[x.getx ()][i]) {counter++;} Else{break;}} for (int i = x.gety () + 1; I <= math.min (x.gety () + 4, column-1); i++) {if (color = = Data[x.getx ()][i]) {counter++;} Else{break;}} if (5 = = counter) {flag = true;} /* * Vertical direction * */counter = 0;for (int i = X.getx (); I >= math.min (X.getx ()-4, row); i--) {if (color = = Data I [X.gety ()]) {counter++;} Else{break;}} for (int i = x.gety () + 1; I <= math.min (x.gety () + 4, column-1); i++) {if (color = = Data[i][x.gety ()]) {counter++;} Else{break;}} if (5 = = counter) {flag = true;}  /* * Diagonal direction * */counter = 0;for (int i = X.getx (), j = x.gety (); I >= math.min (X.getx ()-4, Row) && J >= Math.min (X.gety ()-4, row); I--, j--) {if (color = = Data[i][j]) {counter++;} Else{break;}} for (int i = X.GETX () + 1, j = x.gety () + 1; I <= math.min (x.getx () + 4, column-1) && J <= Math.min (X.gety ( ) + 4, column-1); i++, J + +) {if (color = = Data[i][j]) {counter++;} Else{break;}} if (5 = = counter) {flag = true;}  /* * Reverse Diagonal direction * */counter = 0;for (int i = X.getx (), j = x.gety (); I <= math.min (x.getx () + 4, column -1) && J >= Math.min (X.gety ()-4, row); i++, j--) {if (color = = Data[i][j]) {counter++;} Else{break;}} for (int i = X.GETX () + 1, j = x.gety () + 1; I >= math.min (X.getx ()-4, Row) && J <= Math.min (X.gety () + 4, COLUMN-1); I--, J + +) {if (color = = Data[i][j]) {counter++;} Else{break;}} if (5 = = counter) {flag = true;} return flag;} /* * The actual game start here, where Black first, white second, * we can optimize the game which does not call * The method issuccess in the first Segme NT. such as 8 moves. * And we can narrow the scanning the range to a square just talk above. * */public void Playchess () {Scanner in = new Scanner (system.in); Place x = new Place (0, 0);  Place y = new Place (row-1, column-1); Label:while (true) {//the input should like 1,2while (In.hasnext ()) {string[] str = In.next (). Split (","); int indexx = integer.valueof (str[0]); int indexy = integer.valueof (str[1]); if (!check (Indexx), indexy) {System.out.println ("Please input again"); continue;} Else{setchess (Indexx, Indexy, Gobangcolor.black);p Rintcheckerboard ();//if (issuccess (x, Y, Gobangcolor.black)) {if ( Issuccess (New Place (Indexx, indexy), Gobangcolor.black)) {System.out.println ("The BLACK was win"); break label;} Break;}} while (In.hasnext ()) {string[] str = In.next (). Split (","); int indexx = integer.valueof (str[0]); int indexy = Integer.valueof (str[1]); if (!check (Indexx, indexy)) {System.OUT.PRINTLN ("Please input again"); continue;} Else{setchess (Indexx, Indexy, Gobangcolor.white);p Rintcheckerboard ();//if (issuccess (x, Y, Gobangcolor.white)) {if ( Issuccess (New Place (Indexx, indexy), Gobangcolor.white)) {System.out.println ("The ' Is Win '); break label;} Break;}}} In.close ();} public static void Main (string[] args) {Gobang chess = new Gobang (); chess.playchess ();}}


Gobang Game Source

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.