Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 藍牙對戰五子棋項目實戰(含人機對戰功能)

編輯:關於 Android 程式設計

這是上周花了一週時間完成的課程設計項目,主要實現了以下功能:

基本功能

(1)該 App 能透過藍牙自動搜索周圍其他安裝了本應用的手機,用戶可選擇其中某一台發起對戰邀請,被邀請方可以同意或拒絕;
(2)雙方可進行五子棋藍牙對戰;
(3)具備悔棋等功能;
(4)實現人機對戰,並提供難度選擇;
(5)提供用戶戰績排名系統。

項目已上傳至 GitHub:https://github.com/jiangzhengnan/PumpkinGoBang.git

下面結合界面截圖與原理程式碼,逐一剖析實現思路。整體實現可分為三大部分:簡單人機算法、普通人機算法,以及藍牙模組的客戶端/服務端實現。

一、運行截圖

主界面:

人人對戰界面:

藍牙搜索功能:

藍牙對戰界面:

簡單人機功能:

普通人機功能:

二、實現原理

1、簡單難度電腦算法

由於時間緊迫,人機算法這塊實現得比較樸素,沒有採用專業的五子棋演算法(比如五元組分值比較法或正規的博弈演算法)。簡單難度的思路很直白:在玩家落子點的周圍隨機生成一個點。

 /** * 簡單模式自動下棋的電腦 */ private void naocanautomatic(int x, int y, int Color) { int[][] temp = {{x - 1, y - 1}, {x, y - 1}, {x + 1, y - 1}, {x - 1, y}, {x + 1, y}, {x - 1, y + 1}, {x, y + 1}, {x + 1, y + 1}}; ArrayList<int[]> templist = new ArrayList<>(); for (int i = 0; i < temp.length; i++) { if (temp[i][0] >= 0 && temp[i][0] < 13 && temp[i][1] >= 0 && temp[i][1] < 13) { templist.add(temp[i]); } } panduanshifouyijingxiaguo(templist); int num = (int) (Math.random() * templist.size()); int a = templist.get(num)[0]; int b = templist.get(num)[1]; putChess(a, b, Color); }

這裡要保存已經下過的點位,並判斷是否重複。真正的難點在於:如果落子位置在角落(或周圍已無可自動生成的位置),就需要遞歸判斷並隨機生成一個新位置,直到全盤再無空位為止:

 /** * 遞歸判斷是否已經下過 */ private void panduanshifouyijingxiaguo(ArrayList templist) { for (int i = 0; i < storageHadChess.size(); i++) { for (int j = 0; j < templist.size(); j++) { if (storageHadChess.get(i)[0] == templist.get(j)[0] && storageHadChess.get(i)[1] == templist.get(j)[1]) { templist.remove(j); if (templist.size() == 0) { templist.add(new int[]{(int) (Math.random() * (GRID_SIZE - 2)), (int) (Math.random() * (GRID_SIZE - 2))}); panduanshifouyijingxiaguo(templist); } } } } }

2、普通難度算法

普通難度的實現略顯糾結。它在簡單人機(可稱之為「隨機落子算法」)的基礎上,加入了三點判斷:一旦黑白任何一方有三點連成一線,就自動往這三點的兩端隨機堵上一子,並繼續遞歸判斷是否重複。這段循環寫得偏長,因為沒有把重複程式碼抽離出來。

 /** * 普通模式自動下棋的電腦 */ private void normalautomatic(int x, int y, int Color) { int duishouColor = 0; if (Color == 1) { duishouColor = 2; } else { duishouColor = 1; } for (int i = 0; i < GRID_SIZE - 1; i++) for (int j = 0; j < GRID_SIZE - 1; j++) { //檢測橫軸三個相連 if ((((i + 3) < (GRID_SIZE - 1)) && (mGridArray[i][j] == Color) && (mGridArray[i + 1][j] == Color) && (mGridArray[i + 2][j] == Color)) || (((i + 3) < (GRID_SIZE - 1)) && (mGridArray[i][j] == duishouColor) && (mGridArray[i + 1][j] == duishouColor) && (mGridArray[i + 2][j] == duishouColor))) { boolean aa = false; for (int p = 0; p < cunchusandianArraylist.size(); p++) { String sandiantemp = cunchusandianArraylist.get(p); String[] sandiantemps = sandiantemp.split(":"); if ((Integer.parseInt(sandiantemps[0]) == i) && (Integer.parseInt(sandiantemps[1]) == j) && (Integer.parseInt(sandiantemps[2]) == (i + 1)) && (Integer.parseInt(sandiantemps[3]) == j) && (Integer.parseInt(sandiantemps[4]) == (i + 2)) && (Integer.parseInt(sandiantemps[5]) == j)) { aa = true; } } if (aa == false) { ifsangedianxianglian(i - 1, j, i + 3, j, Color); cunchusandianArraylist.add(i + ":" + j + ":" + (i + 1) + ":" + j + ":" + (i + 2) + ":" + j); return; } } //縱軸、兩條對角線的判斷同理,此處省略…… } int[][] temp = {{x - 1, y - 1}, {x, y - 1}, {x + 1, y - 1}, {x - 1, y}, {x + 1, y}, {x - 1, y + 1}, {x, y + 1}, {x + 1, y + 1}}; ArrayList templist = new ArrayList<>(); for (int k = 0; k < temp.length; k++) { if (temp[k][0] >= 0 && temp[k][0] < 13 && temp[k][1] >= 0 && temp[k][1] < 13) { templist.add(temp[k]); } panduanshifouyijingxiaguo(templist); int num = (int) (Math.random() * templist.size()); int a = templist.get(num)[0]; int b = templist.get(num)[1]; putChess(a, b, Color); return; } }

3、藍牙連接實現

整個項目是客戶端與服務端一體化的,藍牙部分大致可分為三個模組:掃描模組、服務端等待連接模組,以及客戶端主動連接模組。

掃描模組:先打開一個廣播,掃描周圍設備。

 //接收廣播 private class BluetoothReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (!devices.contains(bluetoothDevice)) { deviceNameAndDresss.add(new Device(bluetoothDevice.getName(), bluetoothDevice.getAddress(),bluetoothDevice.getBondState())); devices.add(bluetoothDevice); deviceshowAdapter.notifyDataSetChanged(); } } } }

也可以呼叫 BluetoothAdapter 的 startDiscovery() 方法主動掃描:

 private class SaoMiaoButtonListener implements View.OnClickListener { @Override public void onClick(View v) { ObjectAnimator animator = ObjectAnimator.ofFloat(v,"rotation",0,359); animator.setRepeatCount(12); animator.setDuration(1000); animator.start(); isQuering = true; Toast.makeText(BlueToothFindOthersAty.this, "開始掃描", Toast.LENGTH_SHORT).show(); deviceNameAndDresss.clear(); Set pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { if (!devices.contains(device)) { deviceNameAndDresss.add(new Device(device.getName(), device.getAddress(),device.getBondState())); devices.add(device); } } } deviceshowAdapter.setDevices(deviceNameAndDresss); deviceshowAdapter.notifyDataSetChanged(); bluetoothAdapter.startDiscovery(); } }

服務端等待連接模組:服務端相對簡單,透過 accept 方法監聽連接即可。

 new Thread(new Runnable() { @Override public void run() { try { while (true) { bluetoothServerSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(benjiname, Config.UUID); fuwuSocket = bluetoothServerSocket.accept(); if (fuwuSocket.isConnected()) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BlueToothFindOthersAty.this, "接收挑戰請求,建立連接成功!", Toast.LENGTH_SHORT); BlueToothGameAty blueToothGameAty = new BlueToothGameAty(); blueToothGameAty.blueToothGameAty.manageConnectedSocket(fuwuSocket, false); } }); Intent i = new Intent(BlueToothFindOthersAty.this,BlueToothGameAty.class); startActivity(i); } } } catch (IOException e) { e.printStackTrace(); Log.d("whalea", "沒讀到的原因!:" + e.getMessage()); } } }).start();

客戶端主動連接模組:客戶端 socket 使用 connect() 方法主動連接。

 private void buildConnect(int position, boolean isfaqiren) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceNameAndDresss.get(position).getDeviceAddress()); Boolean result = false; try { if (device.getBondState() == BluetoothDevice.BOND_NONE) { Method createBondMethod = BluetoothDevice.class .getMethod("createBond"); result = (Boolean) createBondMethod.invoke(device); } else if (device.getBondState() == BluetoothDevice.BOND_BONDED) { kehuduanSocket = device.createRfcommSocketToServiceRecord(Config.UUID); final AlertDialog aDialog = new AlertDialog.Builder(BlueToothFindOthersAty.this) .setTitle("發起對戰").setMessage("確認挑戰玩家:" + deviceNameAndDresss.get(position).getDeviceName() + "嗎?") .setNegativeButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new Thread(new Runnable() { @Override public void run() { bluetoothAdapter.cancelDiscovery(); try { kehuduanSocket.connect(); if (kehuduanSocket.isConnected()) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BlueToothFindOthersAty.this, "連接成功!!", Toast.LENGTH_SHORT).show(); BlueToothGameAty blueToothGameAty = new BlueToothGameAty(); blueToothGameAty.blueToothGameAty.manageConnectedSocket(kehuduanSocket, true); } }); Intent i = new Intent(BlueToothFindOthersAty.this,BlueToothGameAty.class); startActivity(i); } } catch (final IOException e) { runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(BlueToothFindOthersAty.this, "連接失敗!!" + e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } } }).start(); } }) .setPositiveButton("取消", null).show(); } } catch (Exception e) { e.printStackTrace(); } }

其餘初始化程式碼都在項目裡,這裡不再贅述,感興趣的讀者可以下載源碼細細研讀。

說來也巧,本可供選擇的課程設計項目不少,我最終還是挑了这个頗具挑戰性的。此前一直沒接觸過藍牙開發,網上的 demo 又往往晦澀難懂(大概是沒能科學上網的緣故),最終還是靠著官方 API 文檔,才一點點寫出了最初的連接 demo,再逐步測試資料傳輸。所以說啊,還是要多讀 API!

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved