How to realize the Local area Network version of Gobang Game by Android
This article mainly introduces "Android how to achieve Gobang game LAN version". In daily operation, I believe many people have doubts about how to achieve Gobang game LAN version in Android. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "Android how to achieve Gobang game LAN version"! Next, please follow the editor to study!
Implementation environment: android studio 3.2.1, mobile phone resolution: 1920 * 1080
The local area network uses Socket connection.
Divided into main activity class, host class, client class
The code is as follows
Permissions to be added to the manifest file:
Main activity:
Package fivechess;import android.os.Bundle;import android.preference.PreferenceManager;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.EditText;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import java.net.InetAddress;import java.net.NetworkInterface;import java.net.SocketException;import java.util.Enumeration;public class MainActivity extends AppCompatActivity {private TextView txtMain; private Button serverBtn; private TextView txtClient Private EditText ipText; private Button clientBtn; private int ip = 10000; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); initView ();} private void initView () {txtMain = (TextView) findViewById (R.id.txtMain); serverBtn = (Button) findViewById (R.id.serverBtn) TxtClient = (TextView) findViewById (R.id.txtClient); ipText = (EditText) findViewById (R.id.ipText); clientBtn = (Button) findViewById (R.id.clientBtn); ipText.setText (getPreference ("myIp")); / / display the local ip address setIp () / / judge whether it is a host or a client according to the button final ViewGroup.LayoutParams params = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); serverBtn.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {ServerView serverView = new ServerView (MainActivity.this, ip, MainActivity.this) AddContentView (serverView, params); serverView.startConn (); / / hide the current control viewGone ();}}) ClientBtn.setOnClickListener (new View.OnClickListener () {@ Override public void onClick (View v) {if (ipText.getText (). ToString (). IsEmpty ()) {Toast.makeText (MainActivity.this, "IP cannot be empty!" , Toast.LENGTH_SHORT) .show (); return;} ClientView clientView = new ClientView (MainActivity.this, ipText.getText (). ToString (), ip, MainActivity.this); addContentView (clientView, params); clientView.startJoin (); / / hide the current control viewGone () }});} / stores the currently entered ip public void setMyIp () {setPreference ("myIp", ipText.getText (). ToString ());} / / is used to obtain the native ip address public void setIp () {String s; try {for (Enumeration en = NetworkInterface.getNetworkInterfaces (); en.hasMoreElements ()) ) {NetworkInterface face = en.nextElement (); for (Enumeration enAddr = face.getInetAddresses (); enAddr.hasMoreElements ();) {InetAddress addr = enAddr.nextElement (); if (! addr.isLoopbackAddress ()) {s = addr.getHostAddress () / / only get the local area network address if ("192" .equals (s.substring (0,3)) {txtMain.setText (txtMain.getText (). ToString () + "host ip:" + s) } catch (SocketException e) {e.printStackTrace ();}} / / hide the auxiliary space of the main activity public void viewGone () {txtMain.setVisibility (View.GONE); serverBtn.setVisibility (View.GONE) TxtClient.setVisibility (View.GONE); ipText.setVisibility (View.GONE); clientBtn.setVisibility (View.GONE);} / / used to get the last ip input address public String getPreference (String key) {return PreferenceManager.getDefaultSharedPreferences (this) .getString (key, "192.168.") } / / used to store data to local public void setPreference (String key, String value) {PreferenceManager.getDefaultSharedPreferences (this). Edit (). PutString (key, value). Apply ();}}
Layout:
Effect picture
Code:
Host class:
Package fivechess;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket Import java.util.ArrayList;import java.util.List;import java.util.Timer;import java.util.TimerTask;public class ServerView extends View {/ / Top margin public static final int TOP = 200; / / left of the chessboard, top margin public static final int MARGINLEFT = 50, MARGINTOP = 100 + TOP; / / width of the piece, public static final int CHESSW = 62 as the case may be / / the width of the grid, as the case may be, public static final int W = 70; / / 14 squares, 15 row and row coordinates public static final int L = 15; public static final int BLOCKL = 14; / / the color tag of the chess public static final int BLACK = 2, WHITE = 1 BLOCKL / public static final int NULL =-1 strike / width of the chessboard private int width = W * stroke / / height of the chessboard private int height = W * BLOCKL; / / Mark the color of our chess / / store the information of all the passing chess, mainly the coordinates private List allList = new ArrayList (); / / store the information of the chess we have passed private List myList = new ArrayList (); / / store the information of the other side's passing chess private List enemyList = new ArrayList () / / whether it is possible to move private boolean canPlay; / / whether there is a sliding event private boolean isMove; / / to start the server. All network requests are executed in the thread private ServerSocket serverSocket; / / to interact with the client / / the other port private int port; / / to send the message private PrintWriter pw / / main activity private MainActivity mainActivity; / / prompt text box private TextView tvTip; / / restart private Button btnRestart; public ServerView (Context context, int port, MainActivity mainActivity) {super (context); this.port = port; this.mainActivity = mainActivity; / / initialize chessboard initMap () / / add prompt text box controls and restart buttons ViewGroup.LayoutParams params = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); tvTip = new TextView (context); tvTip.setText ("waiting for connection..."); tvTip.setX (500); tvTip.setY (20); mainActivity.addContentView (tvTip, params); btnRestart = new Button (context) BtnRestart.setText (restart); btnRestart.setX (MARGINLEFT); btnRestart.setY (20); mainActivity.addContentView (btnRestart, params); btnRestart.setEnabled (false); btnRestart.setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {/ / restart the game restartGame () / / send a message to client sendMes ("restart");}}) SetOnTouchListener (new OnTouchListener () {@ Override public boolean onTouch (View v, MotionEvent event) {switch (event.getAction ()) {case MotionEvent.ACTION_DOWN: isMove = false; break / / determine whether it is a sliding event case MotionEvent.ACTION_MOVE: isMove = true; break; case MotionEvent.ACTION_UP: if (! canPlay) {break } / / can only handle the click event if (! isMove) {/ / get the x, y coordinates of the current click location int x = (int) event.getX ()-MARGINLEFT Int y = (int) event.getY ()-MARGINTOP; / / whether if (x) is outside the chessboard
< -W / 2 || x >Width + W / 2 | | y
< -W / 2 || y > < L; i++) { int hx = MARGINLEFT; int hy = MARGINTOP + i * W; int vx = MARGINLEFT + i * W; int vy = MARGINTOP; // 画竖线 canvas.drawLine(hx, hy, MARGINLEFT + width, hy, paint); // 画横线 canvas.drawLine(vx, vy, vx, MARGINTOP + height, paint); } // 画初始的九个星位 RectF rectF = new RectF(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int w = 20; int x = MARGINLEFT + W * 3 + j * W * 4 - w / 2; int y = MARGINTOP + W * 3 + i * W * 4 - w / 2; rectF.set(x, y, x + 20, y + 20); // 画椭圆 canvas.drawOval(rectF, paint); } } // 画棋子 String[] t; int r, c; for (int i = 0; i < allList.size(); i++) { // 黑棋先,所以黑棋索引为双数,白棋为单数 if (i % 2 == 0) { paint.setColor(Color.BLACK); } else { paint.setColor(Color.WHITE); } t = allList.get(i).split("\\|"); // 行坐标 r = Integer.valueOf(t[0]); // 列坐标 c = Integer.valueOf(t[1]); // 使棋子的中心点对其坐标顶点 c = MARGINLEFT + c * W - CHESSW / 2; r = MARGINTOP + r * W - CHESSW / 2; rectF.set(c, r, c + CHESSW, r + CHESSW); // 画椭圆 canvas.drawOval(rectF, paint); } } // 重新开始游戏 public void restartGame() { allList.clear(); myList.clear(); enemyList.clear(); canPlay = true; setTip("我下"); post(new Runnable() { @Override public void run() { invalidate(); } }); }} 客户端类: 与主机有区别的地方就是 建立连接和接受消息的线程,其它的地方大体相同 代码如下: package fivechess;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.RectF;import android.view.MotionEvent;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.Toast;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;import java.util.ArrayList;import java.util.List;import java.util.Timer;import java.util.TimerTask;public class ClientView extends View { public static final int TOP = 200; public static final int MARGINLEFT = 50, MARGINTOP = 100 + TOP; public static final int W = 70; public static final int CHESSW = 62; // 14个格子,15根线 public static final int L = 15; public static final int BLOCKL = 14; public static final int BLACK = 2, WHITE = 1; private int width = W * BLOCKL; private int height = W * BLOCKL; private int player; private List allList = new ArrayList(); private List myList = new ArrayList(); private List enemyList = new ArrayList(); private boolean canPlay; private boolean isMove; private Socket socket; private int port; private String ip; private MainActivity mainActivity; private PrintWriter pw; private TextView tvTip; private Button btnRestart; public ClientView(Context context, String ip, int port, MainActivity mainActivity) { super(context); this.port = port; this.ip = ip; this.mainActivity = mainActivity; initMap(); ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); tvTip = new TextView(context); tvTip.setText("连接中"); tvTip.setX(500); tvTip.setY(20); mainActivity.addContentView(tvTip, params); btnRestart = new Button(context); btnRestart.setText("重新开始"); btnRestart.setX(MARGINLEFT); btnRestart.setY(20); btnRestart.setEnabled(false); mainActivity.addContentView(btnRestart, params); btnRestart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { restartGame(); sendMes("restart"); } }); setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: isMove = false; break; case MotionEvent.ACTION_MOVE: isMove = true; break; case MotionEvent.ACTION_UP: if (!canPlay) { break; } if (!isMove) { int x = (int) event.getX() - MARGINLEFT; int y = (int) event.getY() - MARGINTOP; if (x < -W / 2 || x >Width + W / 2 | | y
< -W / 2 || y >