# Android Gobang learning

Posted by feldon23 on Fri, 11 Feb 2022 01:05:53 +0100

# Gobang

Android course homework, Gobang production.
The school curriculum is too complicated and there are many skill points. I learn everything, but I don't learn very well.
Because JAVA only knows a little, Android development also learned a little fur. This code is written step by step by turning over the textbook by Android Xiaobai, which has no reference for big guys.
The code quality is not high and the encapsulation is not very good. Don't learn from me (I'm not the main subject, so I don't want to continue to change the later code encapsulation), but it can be used for the introduction of Xiaobai idea.
The function and interface are simple and ugly, but they are easy to use.

# Effect display:

## In the game: show whether the current round is white or black (red as white)

Click restart: the page is cleared

## game over:

Click another game: the page is empty

# The first step is to draw a grid

activity_ main. In XML

TextView.java

# Step 2: draw chess pieces

By drawing a black circle and a red circle to represent a chess piece, you can judge whether to draw a white chess piece or a black chess piece through a boolean putwChess constantly taking Negation: (Point is a class with chess piece coordinates x and y)

Draw red and black dots according to the released position of the mouse
Note: use ACTION_UP instead of ACTION_DOWN, or the mouse will directly drop the pieces as soon as it touches the chessboard.
Since the position where the mouse is released is not necessarily at the intersection of the chessboard, it is necessary to process the obtained coordinates: because my chessboard has 10 grids, and the length and width are 1000, the width and length of a small grid are 100. In addition, the chessboard moves 40 to the left, so X1 = 40+X1/100*100.

(if I fall on the position of (160170), it will be on (140140) after processing, that is

Put the processed X1 and Y1 into the Point object.

Judge whether the Point object of the current coordinate already exists. If it exists, return false. Otherwise, put the Point object into the List.
Note: since the Point object is compared, the equal method needs to be refactored when using the contains method (see the above figure for the code)

In testview Java, draw black and white chess according to the List of black and white chess.
Refresh the interface.

# Step 3: judge the winning situation

According to the chessboard, a binary array is established to indicate the situation of chessmen at each intersection. The subscript indicates the position of the intersection, and the value indicates the presence of chess pieces. If there is no piece, it is 0, white is 1 and black is 2
While adding the chess coordinates, the binary array is also updated. The array subscript is obtained from the values of X1 and Y1. (for example, (140140), the final subscript is (1, 1))

After each chess piece, it will judge whether to win or continue through the two-dimensional array.
10. Y is the coordinate of the current chess piece. Color indicates whether it is black or white. If it is black, color is 2. When judging, it is to judge whether the value in the binary array is 2.
If 5 pieces in a row of the current chess pieces are black (that is, the value of the binary array is 2), the black chess wins.
If there are five pieces in a vertical row of the current chess pieces, you will win.

Similarly, judge an oblique piece

# Step 4: respond and have another game

If it is judged that someone wins, a pop-up window will be created for prompt, and no more pieces can be placed because gameRunning becomes false. Get who wins according to the color of the current chess piece (because it is displayed in the pop-up window after the falling chess is refreshed, when putwChess is white, it indicates that the last falling chess won is black chess).

If you click another game, the List of black and white chess will be cleared, and the round prompt will be initialized to black chess round
, the two-dimensional array traversal is 0, and gamerunning is changed to true again.

# code snippet

## MainActivity.java

```package com.example.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
TextView textView;
TestView testView;
Button button;
boolean gameRunning = true;
int x1,y1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Chessboard and pieces
testView = (TestView)findViewById(R.id.testView1);
testView.setOnTouchListener(new mOnThuch());
//Press the button again
button = (Button)findViewById((R.id.button1));
button.setOnClickListener(new mClick());
//Round prompt text
textView = (TextView)findViewById(R.id.textView2);
textView.setText("Current round: black chess"); //Initialization prompt, black chess first
}
class btnclock implements OnClickListener{
@Override
public void onClick(View arg0){
testView.invalidate();
}
}
private void chessInit(){
gameRunning = true; //The game goes on again;
textView.setText("Current round: black chess");//Initialization prompt, black chess first
testView.cleanChess();
testView.invalidate();
}
//Click the restart button in the game to initialize the data, which has the same function as another time.
class mClick implements  OnClickListener{
public void onClick(View v){
chessInit();
}
}
private class mOnThuch implements View.OnTouchListener {
public boolean onTouch(View v, MotionEvent event) {
//If the game is in progress, draw the pieces; otherwise, do not draw or add coordinates
if (gameRunning){
if (event.getAction() == MotionEvent.ACTION_UP) {
//Get the position where the current mouse is raised, that is, the chess piece is put down
x1 = (int) event.getX();
y1 = (int) event.getY();
//Standardize the coordinates and let the chess pieces fall at the intersection
x1 = 40 + x1 / 100 * 100;
y1 = 40 + y1 / 100 * 100;
Point point = new Point(x1, y1);
//Returns false if the coordinates of the current value already exist
if (testView.wChess.contains(point) || testView.bChess.contains(point)) {
return false;
}
//If it is judged that white chess is drawn, the coordinates are put into white chess and judge whether it is successful
if (testView.putwChess) {
testView.mkWChess(point);
testView.putWChess((x1-40)/100,(y1-40)/100);
gameRunning = testView.gameRun((x1-40)/100,(y1-40)/100,1);
}
//If it is judged that the drawing is a black chess, the coordinates will be put into the black chess and judge whether it is successful or not
if(!testView.putwChess){
testView.mkBChess(point);
testView.putBChess((x1-40)/100,(y1-40)/100);
gameRunning = testView.gameRun((x1-40)/100,(y1-40)/100,2);
}
testView.invalidate();
//Change prompt
if(testView.putwChess)
textView.setText("Current round: black chess");
else
textView.setText("Current round: white chess");

if(gameRunning == false){
dialog.setTitle("game over");
if(!testView.putwChess)
dialog.setMessage("Black chess wins");
else
dialog.setMessage("White chess wins");
dialog.setPositiveButton("Another game",new okClick());
dialog.create();
dialog.show();
}

}

}
return true;
}
}
@Override
dialog.cancel();//Close pop-up window
chessInit();//initialization
}
}
}

```

## Point.java

```package com.example.myapplication;

public class Point {
private int x,y;
Point(int x,int y){
this.x = x;
this.y = y;
}
int getX(){
return x;
}
int getY(){
return y;
}
@Override
//In order to compare objects, function refactoring is required
public boolean equals(Object obj){
if (obj instanceof Point) {
Point p = (Point) obj;
return this.x == p.x && this.y == p.y;
}
return super.equals(obj);
}
}

```

## TestView.java

```package com.example.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;

public class TestView extends View{
boolean putwChess = true;
//Used to draw a chessboard
ArrayList<Point> bChess = new ArrayList<Point>();
ArrayList<Point> wChess = new ArrayList<Point>();
//Used to store chessboard
int chesses[][] = new int[11][11];
//Clear content
void cleanChess(){
bChess.clear();
wChess.clear();;
for(int i = 0;i < 11;i++){
for(int j = 0;j < 11;j++){
chesses[i][j] = 0;
}
}
putwChess = true;
}
//Update black and white LIST
void mkBChess(Point chess){
}
void mkWChess(Point chess){
}
//Update 2D array
void putBChess(int x, int y){
chesses[x][y] = 2;
}
void putWChess(int x, int y){
chesses[x][y] = 1;
}
public TestView(Context context, AttributeSet attr){
super(context,attr);
}

@Override
//Draw graphics
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
gird(canvas);
}
public void gird(Canvas canvas){
int line = 10; /*Number of grids*/
int girdWith = 100;//Width of grid
int girdHeight = 100;//Grid height
int startx = 40;//Grid start position
int starty = 40;//Grid start position
canvas.drawColor(Color.WHITE);
Paint paint = new Paint();
paint.setStrokeWidth(4);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
//Draw a horizontal line
for(int i = 0;i < line+1;i++){
canvas.drawLine(startx,starty,startx+girdWith*line,starty,paint);
starty = starty+100;
}
starty = 40;
//Draw a vertical line
for(int i = 0;i < line+1;i++){
canvas.drawLine(startx,starty,startx,starty+girdHeight*line,paint);
startx = startx+100;
}
//Draw black chess
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
for(int i = 0;i < bChess.size();i++){
Point point = bChess.get(i);
canvas.drawCircle(point.getX(),point.getY(), 30, paint);
}
//Draw white chess
paint.setStyle(Paint.Style.FILL);
paint.setAntiAlias(true);
paint.setColor(Color.RED);
for(int i = 0;i < wChess.size();i++){
Point point = wChess.get(i);
canvas.drawCircle(point.getX(),point.getY(), 30, paint);
}

putwChess = !putwChess; //Take the reverse to reach the situation of black and white chess in turn.
}
//Determine whether the game is over
public boolean gameRun(int x, int y,int color) {
//Five across
int countChess = 1;
int px = 0;
int py = 0;
for (px = x - 1; px >= 0; px--) {
if (chesses[px][y] == color ) {
countChess++;
if (countChess >= 5)
return false;
} else
break;
}
for (px = px + 1; px < 11; px++) {
if (chesses[px][y] == color) {
countChess++;
if (countChess >= 5)
return false;
} else
break;
}
//There are five upright
countChess = 1;
for (py = y - 1; py >= 0; py--) {
if (chesses[x][py] == color) {
countChess++;
if (countChess >= 5)
return false;
} else
break;
}
for (py = y + 1; py < 11; py++) {
if (chesses[x][py] == color) {
countChess++;
if (countChess >= 5)
return false;
} else
break;
}
//Left oblique five
countChess = 1;
for(px = x-1,py = y-1;px >= 0 && py >= 0;px--,py--){
if(chesses[px][py] == color){
countChess++;
if (countChess >= 5)
return false;
}else
break;
}
for(px = x+1,py = y+1;px <11&& py <11;px++,py++){
if(chesses[px][py] == color){
countChess++;
if (countChess >= 5)
return false;
}else
break;
}
//Right oblique five
countChess = 1;
for(px = x-1,py = y+1;px >= 0 && py < 11;px--,py++){
if(chesses[px][py] == color){
countChess++;
if (countChess >= 5)
return false;
}else
break;
}
for(px = x+1,py = y-1;px <11&& py >= 0;px++,py--){
if(chesses[px][py] == color){
countChess++;
if (countChess >= 5)
return false;
}else
break;
}
return true;
}

}
```

## activity_main

```<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30dp"
android:text="Five Chess Game " />

<com.example.myapplication.TestView
android:id="@+id/testView1"
android:layout_width="match_parent"
android:layout_height="414dp"></com.example.myapplication.TestView>

<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="40dp"
android:text="Current round: black chess"/>

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="59dp"
android:textSize="30dp"
android:text="restart" />

</LinearLayout>
```

Topics: Android