Android Gobang Game Program Complete Example Analysis _android

Source: Internet
Author: User

Recently studied the Gobang course, the feeling is very good. Then I wrote an android program about Gobang that I could learn a lot from. Now we begin the process of writing the Gobang program today. The source code of the program please see links:

OK, now we're going to build the project Step-by-step, starting with the following project chart:

Run the effect diagram:

Some pre-preparation code

1, the main activity class mainactivity, added in the menu to come again the function:

public class Mainactivity extends Appcompatactivity {
 private chessboardview chessboardview;

 @Override
 protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  Setcontentview (r.layout.activity_main);
  Chessboardview = (Chessboardview) Findviewbyid (R.id.boardview);
 }

 @Override Public
 Boolean onoptionsitemselected (MenuItem item) {
  int id = item.getitemid ();
  One more innings.
  if (id = = r.id.action_setting) {
   chessboardview.start ();
   return true;
  }
  return super.onoptionsitemselected (item);
 }

 @Override Public
 Boolean oncreateoptionsmenu (Menu menu) {
  getmenuinflater (). Inflate (R.menu.menu_main, menu);
  return true;
 }


2, constant class easy maintenance Management: Constants

public class Constants {
 //five child alignments public
 final static int max_count_in_line = 5;
 The number of rows of the chessboard
 final static int max_line =;

 The direction of the check
 final static int horizontal = 0;
 Final static int VERTICAL = 1;
 Final static int left_diagonal = 2;
 Final static int right_diagonal = 4;
}

3, Activity_main.xml added a custom Board view:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"http://schemas.android.com/apk" /res/android "
 xmlns:tools=" Http://schemas.android.com/tools "
 android:layout_width=" Match_parent
 " android:layout_height= "Match_parent"
 android:background= "@mipmap/bg"
 tools:context= " Com.example.linux.mygobang.MainActivity ">

 <com.example.linux.mygobang.chessboardview
  android:id= "@+id/boardview"
  android:layout_centerinparent= "true"
  android:layout_width= "Match_parent"
  android:layout_height= "Match_parent"/>
</RelativeLayout>

4, Menu_main.xml in the definition of another menu:

<?xml version= "1.0" encoding= "Utf-8"?> <menu xmlns:tools=
"Http://schemas.android.com/tools"
 Xmlns:android= "Http://schemas.android.com/apk/res/android" >

 <item android:id= "@+id/action_setting"
  android:title= "One more innings"
  android:orderincategory= "android:showasaction=" Never "
  tools:ignore=" "Appcompatresource"/>
</menu>


Customizing the view of a chessboard

The Chessboardview class is the core part of the whole program.

1, the initialization of the work, the program used in the variables are also placed in the following code:

//chessboard width, also length private int mviewwidth;//Checkerboard length of each grid private float maxlineheight; private Pa
int paint = new paint ();
Define black and white pieces of Bitmap private Bitmap mwhitepiece, mblackpiece;

Private float ratiopieceoflineheight = 3 * 1.0F/4;
Determine if the currently falling piece is white private boolean miswhite = true;
Record the list of black and white pieces position private arraylist<point> Mwhitearray = new arraylist<> ();

Private arraylist<point> Mblackarray = new arraylist<> ();
Whether the game is over private Boolean misgameover;

The game is over, whether the White side victory private Boolean miswhitewinner;
 Public Chessboardview (context, AttributeSet attrs) {Super (context, attrs);
Init ();
 private void Init () {paint.setcolor (0x88000000);
 Paint.setantialias (TRUE);
 Paint.setdither (TRUE);

 Paint.setstyle (Paint.Style.STROKE);
 Mwhitepiece = Bitmapfactory.decoderesource (Getresources (), R.MIPMAP.STONE_W2);
Mblackpiece = Bitmapfactory.decoderesource (Getresources (), R.MIPMAP.STONE_B1); }

2, Onmeasure method, the size of the view, so that the view of the long and wide consistent.

@Override
protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
 int widthsize = Measurespec.getsize (WIDTHMEASURESPEC);
 int Widthmodel = Measurespec.getmode (widthmeasurespec);

 int heightsize = measurespec.getsize (heightmeasurespec);
 int Heightmodel = Measurespec.getmode (heightmeasurespec);

 int width = math.min (widthsize, heightsize);
 if (Widthmodel = = measurespec.unspecified) {
  width = heightsize;
 } else if (Heightmodel = = Measurespec.unspecifie D) {
  width = widthsize;
 }
 Setmeasureddimension (width, width);
 

2, the Onsizechanged method in the layout stage, if the view size changes, this method is called.

@Override
protected void onsizechanged (int w, int h, int oldw, int oldh) {
 super.onsizechanged (W, H, OLDW, OLDH); C3/>mviewwidth = W;
 Maxlineheight = Mviewwidth * 1.0f/constants.max_line;

 int piecewidth = (int) (maxlineheight * ratiopieceoflineheight);
 Mwhitepiece = Bitmap.createscaledbitmap (mwhitepiece, Piecewidth, Piecewidth, false);
 Mblackpiece = Bitmap.createscaledbitmap (mblackpiece, Piecewidth, Piecewidth, false);
 

4, Ontouchevent method to handle the position of our next pieces:

@Override Public
Boolean ontouchevent (Motionevent event) {
 if (misgameover) {return
  false;
 }
 int action = Event.getaction ();
 if (action = = motionevent.action_up) {
  int x = (int) event.getx ();
  int y = (int) event.gety ();

  Point point = Getvalidpoint (x, y);
  if (mwhitearray.contains) | | mblackarray.contains (point) {return
   false;
  }
  if (miswhite) {
   mwhitearray.add (point);
  } else {
   mblackarray.add (point);
  }
  Invalidate ();
  Miswhite =!miswhite;
 }
 return true;
} 

5, in the OnDraw method to do the board drawing work:

@Override
protected void OnDraw (Canvas Canvas) {
 super.ondraw (Canvas);
 Grid
 Drawboard (canvas) for drawing the chessboard;
 Draw a chessboard of black and white pieces
 drawpieces (canvas);
 Check to see if the game is over
 checkgameover ();
}

6, Next, we press the above process, a detailed explanation:

To draw a checkerboard grid:

The network cable that draws the chessboard is
private void Drawboard (Canvas Canvas) {
 int w = mviewwidth;
 float lineheight = maxlineheight;

 for (int i = 0; i < constants.max_line i++) {
  int startx = (int) (LINEHEIGHT/2);
  int endx = (int) (W-LINEHEIGHT/2);

  int y = (int) ((0.5 + i) * lineheight);
  Canvas.drawline (StartX, y, EndX, y, paint);
  Canvas.drawline (y, StartX, y, endx, paint);
 }


To draw the black and white pieces of a chessboard:

To draw a piece from an array of black-and-white pieces
private void drawpieces (Canvas Canvas) {
 for (int i = 0, n = mwhitearray.size (); i < n; i++) { Point
  Whitepoint = Mwhitearray.get (i);
  float left = (whitepoint.x + (1-ratiopieceoflineheight)/2) * maxlineheight;
  float top = (Whitepoint.y + (1-ratiopieceoflineheight)/2) * maxlineheight;

  Canvas.drawbitmap (Mwhitepiece, left, top, null);

 for (int i = 0, n = mblackarray.size (); i < n; i++) {point
  Blackpoint = Mblackarray.get (i);
  float left = (blackpoint.x + (1-ratiopieceoflineheight)/2) * maxlineheight;
  float top = (Blackpoint.y + (1-ratiopieceoflineheight)/2) * maxlineheight;

  Canvas.drawbitmap (Mblackpiece, left, top, null);
 }


Check to see if the game is over:

Check to see if the game is over
private void Checkgameover () {
 Checkwinner checkwinner = new Checkwinner ();
 Boolean Whitewin = Checkwinner.checkfiveinlinewinner (Mwhitearray);
 Boolean Blackwin = Checkwinner.checkfiveinlinewinner (Mblackarray);

 if (Whitewin | | blackwin) {
  misgameover = true;
  Miswhitewinner = Whitewin;
  String Text = Miswhitewinner? "White victory": "Black Chess victory";
  Toast.maketext (GetContext (), text, Toast.length_short). Show ();
 }


Save the mess and restore the chess

1, save the pieces, such as the switch horizontal screen:

private static final String INSTANCE = "INSTANCE";
private static final String Instance_game_over = "Instance_game_over";
private static final String Instance_white_array = "Instance_white_array";
private static final String Instance_black_array = "Instance_black_array";

@Override
protected parcelable onsaveinstancestate () {
 Bundle Bundle = new Bundle ();
 Bundle.putparcelable (INSTANCE, Super.onsaveinstancestate ());
 Bundle.putboolean (Instance_game_over, misgameover);

 Bundle.putparcelablearraylist (Instance_black_array, mblackarray);
 Bundle.putparcelablearraylist (Instance_white_array, mwhitearray);
 return bundle;
}

2, from the bundle to restore the chess:

@Override
protected void onrestoreinstancestate (parcelable state) {
 if (state instanceof Bundle) {
  Bundle Bundle = (bundle) state;
  Misgameover = Bundle.getboolean (instance_game_over);
  Mwhitearray = Bundle.getparcelablearraylist (Instance_white_array);
  Mblackarray = Bundle.getparcelablearraylist (Instance_black_array);
  Super.onrestoreinstancestate (Bundle.getparcelable (INSTANCE));
  return;
 }
 Super.onrestoreinstancestate (state);

3, to increase the logic of another game:

One more. Public
void Start () {
 mwhitearray.clear ();
 Mblackarray.clear ();
 Misgameover = false;
 Miswhitewinner = false;
 Invalidate ();
}

Algorithm to determine whether the game is over

In the Checkwinner, to the chess board in the "Rice" font check whether five children alignment:

1, check method, for different directions, make judgments:

Private Boolean check (int x, int y, list<point> points, int checkori) {int count = 1; for (int i = 1; i < Constants.max_count_in_line i++) {switch (Checkori) {case Constants.HORIZONTAL:point1
    = new Point (X-i, y);
   Break
    Case Constants.VERTICAL:point1 = new Point (x, y-i);
   Break
    Case Constants.LEFT_DIAGONAL:point1 = new Point (x-i, y + i);
   Break
    Case Constants.RIGHT_DIAGONAL:point1 = new Point (x + i, y + i);
  Break
  } if (Points.contains (point1)) {count++;
  } else {break; (int i = 1; i < Constants.max_count_in_line i++) {switch (Checkori) {case Constants.horizontal:p
    Oint2 = new Point (x + i, y);
   Break
    Case Constants.VERTICAL:point2 = new Point (x, y + i);
   Break
    Case Constants.LEFT_DIAGONAL:point2 = new Point (x + I, y-i);
   Break
    Case Constants.RIGHT_DIAGONAL:point2 = new Point (X-i, y-i);
  Break
 } if (Points.contains (Point2)) {  count++;
  } else {break;
 } if (count = = Constants.max_count_in_line) {return true;
return false;

 }

2, do four directions check:

Horizontal Judgment
Private Boolean checkhorizontal (int x, int y, list<point> points) {
 Checkmodel = Constants.horizont AL;
 return check (x, Y, points, Checkmodel);

Vertical Judgment
Private Boolean checkvertical (int x, int y, list<point> points) {
 Checkmodel = constants.vertical;< C8/>return check (x, Y, points, Checkmodel);

Left skew judgment
private Boolean checkleftdiagonal (int x, int y, list<point> points) {
 Checkmodel = Constants.left _diagonal;
 return check (x, Y, points, Checkmodel);

Right skew judgment
private Boolean checkrighttdiagonal (int x, int y, list<point> points) {
 Checkmodel = Constants.ri ght_diagonal;
 return check (x, Y, points, checkmodel);
 

3, make specific judgments, whether the game is over:

Private point point1, Point2;
private int checkmodel =-1;

public boolean Checkfiveinlinewinner (list<point> points) {for
 (point point:points) {
  int x = point.x;
   
    int y = point.y;

  if (Checkhorizontal (x, y, points)) {return
   true;
  } else if (checkvertical (x, y, points)) {return
   true;
  else if (checkleftdiagonal (x, y, points)) {return
   true;
  } else if (checkrighttdiagonal (x, y, points)) {
   return true;
  }
 return false;
}


   

SOURCE Download: Android Gobang Game program

This is the entire content of this article, I hope to learn more about Android software programming help.

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.