【源码】联机五子棋,基于UDP可靠传输

4 篇文章 0 订阅
2 篇文章 0 订阅

前几天在 游戏蛮牛论坛 发现一篇文章 《Socket联机版五子棋》, 东方喵的版本,逻辑判断在服务器端,基于 Unity TcpClient。

初衷

因为个人挺喜欢五子棋游戏的,而且每天中午跟同事一起吃饭时,等餐时间,没事可干,他们都是埋头“搞机”。
所以呢,我打算重写下五子棋这个游戏,在等餐的时候可以直接用手机来一局。

现在每天中午我们都要来一局,其乐无穷!!!

感谢

感谢东方喵分享的资源;
感谢天梯实时对战服务的商务小伙伴的热情帮忙及联机服务的支持。

下面呢,就给大家分享下实现过程。

关于游戏

暂定名: GobangOnline
网络协议: UDP
匹配:两玩家随机匹配(也有计划加上 房间号或者密令匹配对战 和 局域网联机对战);

先来张配图:
(带红点的棋子为最后落子标记)
这里写图片描述

涉及同步数据

  • 匹配成功玩家昵称同步
  • 玩家落子数据同步
  • 胜负同步

玩家昵称同步

和一个朋友争论了好几次,还是决定把玩家输入昵称的逻辑保留下来。
玩家启动游戏,输入昵称,既可联机对战(昵称保存到本地)。

1,输入昵称,点击“登录”,将直接进入匹配对手界面。

UIManager.cs

	public void onButtonClick(string name) {
		if(name == "")
			return;

		switch (name) {
		case "level":
			// 昵称不能为空
			GameObject mainObj = ui.transform.Find ("Main").gameObject;
			GameObject textObj = mainObj.transform.Find ("InputField/Text").gameObject;
			GameObject errorTipObj = mainObj.transform.Find ("ErrorTip").gameObject;
			string nickname = textObj.GetComponent<Text> ().text;
			if (nickname == "") {
				errorTipObj.SetActive (true);
				return;
			}

			GameManager.nickname = nickname;

			// 记录 nickname
			PlayerPrefs.SetString ("nickname", nickname);

			errorTipObj.SetActive (false);
			mainObj.SetActive (false);

			// 等级匹配
			GobangClient.connect (8);
			break;

		case "retry":
			GobangClient.disconnect ();
			break;

		}
	}

2,匹配成功后,发送握手交换名片(昵称)数据。

GobangClient.cs

	// GobangClient 主要重写 Nanolink实时对战服务已封装的 onMessage, onResync, onStatusChanged, onConnected, onDisconnected 方法。
	// 重写接受到数据的响应函数,在GameManager.recvMessage()中统一处理接收到数据
	protected override void onMessage (byte[] data, byte fromIndex) {
		// Hashtable values = GameSerialize.fromBytes (data);

		GameObject gameObj = GameObject.Find ("Game");
		if (gameObj == null)
			return;

		GameManager gameManager = gameObj.GetComponent<GameManager> ();
		if (gameManager == null)
			return;

		// 同意处理 接收到的数据
		gameManager.recvMessage(GameSerialize.fromBytes (data), fromIndex);
	}
	
	// 匹配成功时,自动调用 onResync 方法
	protected override void onResync(byte fromIndex) {
		// 同步玩家的 名字
		{
			Debug.Log(GameManager.nickname);

			// 交换名字,握手
			{
				Hashtable values = new Hashtable ();
				values.Add ("name", "handshake");
				values.Add ("v", GameManager.nickname);

				GobangClient.send (GameSerialize.toBytes (values));
			}

			// 先进入房间的玩家 持 黑子
			string chess = "";
			if (getInt ("client-index") == 0)
				chess = "黑子";
			else
				chess = "白子";

			GameObject ui = GameObject.Find ("UI");
			GameObject userInfoObj = ui.transform.Find ("UserInfo").gameObject;
			GameObject selfObj = userInfoObj.transform.Find ("Self").gameObject;
			selfObj.GetComponent<Text> ().text = "本人: " + GameManager.nickname + " (" + chess + ")";

			userInfoObj.SetActive (true);
		}
	}

3,收到对手的握手数据时,完成本地渲染。

GameManager.cs

	// 接收到消息
	public void recvMessage(Hashtable values, byte fromIndex) {
		string name = (string) values["name"];
		switch(name) {
		// 握手,交换名片
		case "handshake":
			{
				// 先进入房间的玩家 持 黑子
				string theChess = "";
				if (fromIndex == 0)
					theChess = "黑子";
				else
					theChess = "白子";

				GameObject ui = GameObject.Find ("UI");
				GameObject userInfoObj = ui.transform.Find ("UserInfo").gameObject;
				GameObject adversaryObj = userInfoObj.transform.Find ("Adversary").gameObject;
				adversaryObj.GetComponent<Text> ().text = "对手: " + values["v"] + " (" + theChess + ")";

				userInfoObj.SetActive (true);
			}
			break;

		// 落子
		case "piece":
			{
				int x = (int) values["x"];
				int y = (int) values["y"];
				string turn = (string) values["turn"];

				GameObject chessObj = GameObject.Find ("Chess");
				if (chessObj == null)
					return;

				// 渲染接收到的数据,落子
				InputManager input = chessObj.GetComponent<InputManager> ();
				input.setPiece (x, y, turn);

				// 修正 chess 布子
				chess[x, y] = turn;
			}
			break;

		// gameover
		case "lose":
			{
				// gameover
				isOver = true;

				// UI
				GameObject ui = GameObject.Find("UI");

				GameObject resultObj = ui.transform.Find ("Result").gameObject;
				GameObject gameoverObj = resultObj.transform.Find ("GameOver").gameObject;
				gameoverObj.GetComponentInChildren<Text> () .text = "不幸惨败";

				resultObj.SetActive(true);
			}
			break;

		default:
			Debug.Log ("无效的指令");
			break;
		}

	}

落子同步

玩家A落子操作后,即刻同步落子数据给玩家B,玩家B接收到数据后,渲染落子位置及对应的棋子;
切换回合;

InputManager.cs

	...
    private void Update () {
		// 确保连接后,操作才有效
		if(!GobangClient.isConnected())
			return;

		if (Input.GetMouseButtonDown(0) && (GameManager.curTurn == GameManager.userColor) && !GameManager.isOver) {
            RaycastHit2D hit= Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
			if(hit) {
                Debug.Log(hit.point);
				// 鼠标位置对应的格子按 "四舍五入"
                indexX = (int)System.Math.Round((hit.point.x - c0.transform.position.x) / cellSizeX, System.MidpointRounding.AwayFromZero);
                indexY = (int)System.Math.Round((hit.point.y - c0.transform.position.y) / cellSizeY, System.MidpointRounding.AwayFromZero);
				if (indexX >= 0 && indexX < sizeX && indexY >= 0 && indexY < sizeY) {
					if (!isSet[indexX, indexY]) {
						string trun = GameManager.curTurn;

						// 发送消息通知对手,落子位置
						{
							Hashtable values = new Hashtable ();
							values.Add ("name", "piece");
							values.Add ("x", indexX);
							values.Add ("y", indexY);
							values.Add ("turn", trun);

							GobangClient.send (GameSerialize.toBytes (values));
						}

						// 落子
						setPiece(indexX, indexY, trun);

						// 更新 GameManager chess
						updateChess (indexX, indexY, trun);
                    } else {
                        Debug.Log("此格已经下子儿了");
                    }
                }
            }
        }
	}

	// 落子
	public void setPiece(int x, int y, string turn) {
		GameObject sign = GameObject.Find ("Sign");
		if(sign != null)
			Destroy(sign);

        Vector3 v = c0.transform.position + new Vector3(x * cellSizeX, y * cellSizeY, 0);
		Instantiate(pieceHash[turn] as GameObject, v, Quaternion.identity);
        isSet[x, y] = true;

		// 标记最后一次落子,红点
		sign = Instantiate(pieceHash["Sign"] as GameObject, v, Quaternion.identity);
		sign.name = "Sign";

		// 落子后,切换回合
		if (turn == "Black")
			GameManager.curTurn = "White";

		if (turn == "White")
			GameManager.curTurn = "Black";
    }

	// 更新 chess
	private void updateChess(int x, int y, string turn) {
		GameObject gameObj = GameObject.Find ("Game");
		if (gameObj == null)
			return;

		// 渲染接收到的数据,落子
		GameManager gameManager = gameObj.GetComponent<GameManager> ();
		if (gameManager == null)
			return;

		gameManager.updateChess (x, y, turn);	
	}

接收数据处理部分可以看上文的 GameManager.cs 中 recvMessage 方法。

胜负同步

胜负逻辑判断在本地计算,落子时检查胜负结果。
如果战胜对手发送消息通知对手。

GameManager.cs

	public void updateChess(int x, int y, string turn) {
		// 修正 chess 布子
		chess[x, y] = turn;

		// 检查胜负
		if(checkChess(x, y, turn)) {
			Debug.Log ("游戏结束,获胜方:" + turn);

			// game over
			isOver = true;
			// 结果通知给对方
			{
				Hashtable values = new Hashtable ();
				values.Add ("name", "lose");
				values.Add ("v", (byte) 1);

				GobangClient.send (GameSerialize.toBytes (values));
			}

			// UI
			GameObject ui = GameObject.Find("UI");

			GameObject resultObj = ui.transform.Find ("Result").gameObject;
			GameObject gameoverObj = resultObj.transform.Find ("GameOver").gameObject;
			gameoverObj.GetComponentInChildren<Text> () .text = "大获全胜";

			resultObj.SetActive(true);
		}
	}

检查胜负方法 checkChess

	// 遍历检查棋盘是否有胜负出现
	private bool checkChess(int x, int y, string turn) {
		int counta = 0; // 横
		int countb = 0; // 竖
		int countc = 0; // 正斜
		int countd = 0; // 反斜

		// 横,正方向
		for (int i = 1; i < 5; i++) {
			if (x + i >= sizeX) {
				break;
			}

			if (chess[i + x, y] == turn) {
				counta++;
			} else {
				break;
			}
		}
		// 横,负方向
		for (int i = 1; i < 5; i++) {
			if (x - i < 0) {
				break;
			}

			if (chess[x - i, y] == turn) {
				counta++;
			} else {
				break;
			}
		}
		if (counta >= 4) {
			return true;
		}
			
		// 竖,正方向
		for (int i = 1; i < 5; i++) {
			if (y + i >= sizeY) {
				break;
			}

			if (chess[x, i + y] == turn) {
				countb++;
			} else {
				break;
			}
		}
		// 竖,负方向
		for (int i = 1; i < 5; i++) {
			if (y - i < 0) {
				break;
			}

			if (chess[x, y - i] == turn) {
				countb++;
			} else {
				break;
			}
		}
		if (countb >= 4) {
			return true;
		}

		// 正斜,正方向
		for (int i = 1; i < 5; i++) {
			if (x + i >= sizeX || y + i >= sizeY) {
				break;
			}

			if (chess[x + i, y + i] == turn) {
				countc++;
			} else {
				break;
			}
		}
		// 正斜,负方向
		for (int i = 1; i < 5; i++) {
			if (x - i  < 0 || y - i < 0) {
				break;
			}

			if (chess[x - i, y - i] == turn) {
				countc++;
			} else {
				break;
			}
		}
		if (countc >= 4) {
			return true;
		}

		// 反斜,正方向
		for (int i = 1; i < 5; i++) {
			if (x + i >= sizeX || y - i < 0) {
				break;
			}

			if (chess[x + i, y - i] == turn) {
				countd++;
			} else {
				break;
			}
		}
		// 反斜,负方向
		for (int i = 1; i < 5; i++) {
			if (x - i < 0 || y + i >= sizeY) {
				break;
			}

			if (chess[x - i, y + i] == turn) {
				countd++;
			} else {
				break;
			}
		}
		if (countd >= 4) {
			return true;
		}

		return false;
	}

有什么疑问可以留言,一起探讨。(本人QQ:836667502)。
源码下载:
链接: https://pan.baidu.com/s/1bpB4PUB 密码: nuk7

安卓.apk包下载:
链接:https://pan.baidu.com/s/1qXCPTRQ 密码:xear

  • 2
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值