Libgdx: android单机斗地主支持局域网wifi联网的网络模块核心代码

这个作品是我最近写的,结合我的毕业设计的通信模块和之前的单机版斗地主。我已经上架到豌豆荚了,贴了点广告,看看能不能赚点茶钱。可是一点也不乐观。因此我想分享给大家源码。只要不用于商业。 下面先贴网络模块的核心代码,第一次写这种逻辑用的udp, 经验不够,没有写的那么好看。

这里是我上架的apk,大家下载来试试也无妨: 地址 http://www.wandoujia.com/apps/com.hj.joker

package com.hj.net;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Random;
import java.util.Vector;

import org.apache.http.conn.util.InetAddressUtils;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.hj.screen.NetGameScreen;
import com.hj.screen.RommScreen;
import com.hj.tool.Card;
import com.hj.tool.Comm;

import android.os.Message;
import android.util.Log;

public class NetManager {

	// 初始化
	public RommScreen rommScreen = null;
	public NetGameScreen netGameScreen = null;
	public static int Max = 3;
	public User me = null, u = null, computer = null;
	public List<User> users = null;
	public Room currentRoom = null;
	public List<Room> roomList = null;// 本主机的所有用户
	public boolean isStop = true;
	public boolean LeaveRoom = false;
	public CardData cards[] = new CardData[56];
	public List<CardData> cardDataList = new ArrayList<CardData>();
	// 协议命令
	public static final int CMD_HOST_REQUEST_ROOM = 10;
	public static final int CMD_REPLY_ROOM = 11;
	public static final int CMD_CREATE_ROOM = 12;
	public static final int MES_UPDATE_ROOM = 13;
	public static final int MES_UPDATE_User = 14;
	public static final int CMD_HOST_JOIN_ROOM = 15;
	public static final int CMD_BROAD_USERLIST = 16;
	public static final int CMD_UPDATE_ROOM = 17;
	public static final int CMD_HOST_LEAVE_ROOM = 18;
	public static final int CMD_LEAVE_ROOM = 19;
	public static final int CMD_DEL_ROOM = 20;
	public static final int CMD_HOST_READY_ROOM = 21;
	public static final int CMD_BEGIN_CARDS = 22;
	public static final int MES_UPDATE_BEGINCARD = 23;
	public static final int MES_UPDATE_LANDLORD = 24;
	public static final int CMD_HOST_FINISH_LANDLORD = 25;
	public static final int CMD_BROAD_NEXT_LANDLORD = 26;
	public static final int CMD_BEGIN_LANDLORD_CARDS = 27;
	public static final int CMD_HOST_START_CARDS = 28;
	public static final int CMD_START_CARDS = 29;
	public static final int MES_SHOW_CARDBUTTON = 30;
	public static final int MES_UPDATE_LANDLORDHEAD = 31;
	public static final int CMD_HOST_SEND_CARDS = 32;
	public static final int CMD_SEND_CARDS = 33;
	public static final int MES_SEND_CARDS = 34;
	public static final int CMD_SEND_CURRENTID_CARDS = 35;
	public static final int MES_FLUSH_CARDS = 36;
	public static final int CMD_HOST_SEND_CARDS_COMPUTER = 37;
	public static final int PORT_SEND = 2429;// 发送端口
	public static final int PORT_RECEIVE = 2425;// 接收端口

	public NetManager() {
		roomList = new ArrayList<Room>();
		users = new ArrayList<User>();
	}

	public void init() {
		users.clear();
		cardDataList.clear();
		for (int i = 0; i < 3; i++) {
			netGameScreen.gInfo.playerList[i].clear();
			netGameScreen.gInfo.playerOutList[i].clear();
		}
		netGameScreen.gInfo.playerList[3].clear();
		// users
	}

	// 发送消息
	public void sendCMD(Msg msg) {
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
		}
		(new UdpSend(msg)).start();
	}

	class UdpSend extends Thread {
		Msg msg = null;

		UdpSend(Msg msg) {
			this.msg = msg;
		}

		public void run() {
			try {
				byte[] data = toByteArray(msg);
				DatagramSocket ds = new DatagramSocket(PORT_SEND + Max);
				DatagramPacket packet = new DatagramPacket(data, data.length,
						InetAddress.getByName(msg.getReceiveUserIp()),
						PORT_RECEIVE + Max);
				packet.setData(data);
				ds.send(packet);
				ds.close();
			} catch (Exception e) {
			}

		}
	}

	// 接收消息
	public void openReceiveMsgThread() {
		(new UdpReceive()).start();
	}

	public class UdpReceive extends Thread {
		Msg msg = null;

		UdpReceive() {
		}

		public void run() {
			// 消息循环
			while (!isStop) {
				try {
					DatagramSocket ds = new DatagramSocket(PORT_RECEIVE + Max);
					byte[] data = new byte[1024 * 32];
					DatagramPacket dp = new DatagramPacket(data, data.length);
					dp.setData(data);
					ds.receive(dp);
					byte[] data2 = new byte[dp.getLength()];
					System.arraycopy(data, 0, data2, 0, data2.length);// 得到接收的数据
					Msg msg = (Msg) toObject(data2);
					ds.close();

					// 解析消息
					parse(msg);
				} catch (Exception e) {
				}
			}

		}
	}

	// 解析接收的
	public void parse(Msg msg) {
		Room r = null;
		switch (msg.getMsgType()) {
		case CMD_HOST_REQUEST_ROOM:// 搜索桌子
			u = (User) msg.getBody();
			if (me.getIp().equals(currentRoom.getIp())) {
				// out("有人进房间:"+u.getIp());
				replyRoom(u);
			}
			break;
		case CMD_REPLY_ROOM: // 收到反馈桌子
			r = (Room) msg.getBody();
			if (!isContainsRoom(r)) {
				roomList.add(r);
				updateRoomList();
			}
			break;
		case CMD_CREATE_ROOM: // 收到创建的桌子
			r = (Room) msg.getBody();
			if (!isContainsRoom(r)) {
				roomList.add(r);
				updateRoomList();
			}
			break;
		case CMD_HOST_JOIN_ROOM: // 收到请求加入桌子
			u = (User) msg.getBody();
			// out("收到请求");
			if (!isContainsUser(u)) {
				users.add(u);
				currentRoom.userCount++;
				orderComputer();
				broadUser();
				// 反馈桌子人数更新
				updateRoom();
			}
			break;
		case CMD_UPDATE_ROOM: // 收到桌子列表更新
			r = (Room) msg.getBody();
			if (isContainsRoom(r)) {
				for (Room t : roomList) {
					if (t.getIp().equals(r.getIp()))
						t.setUserCount(r.getUserCount());
				}
			} else
				roomList.add(r);
			updateRoomList();
			break;
		case CMD_BROAD_USERLIST:// 收到用户列表更新
			// out("收到广播");
			users = (ArrayList) msg.getBody();
			updateUserList();
			break;
		case CMD_HOST_LEAVE_ROOM: // 主机离开房间
			u = (User) msg.getBody();
			leaveRoom2(u);
			break;
		case CMD_DEL_ROOM: // 收到删除房间
			r = (Room) msg.getBody();
			if (isContainsRoom(r)) {
				removeRoom(r);
			}
			updateRoomList();
			break;
		case CMD_LEAVE_ROOM:
			u = (User) msg.getBody();
			if (!u.getIp().equals(me.getIp())) {
				LeaveRoom = true;
				init();
				users.clear();
				currentRoom = null;
				updateRoomList();
			}
			break;
		case CMD_HOST_READY_ROOM: // 准备
			u = (User) msg.getBody();
			for (User user : users) {
				if (user.getIp().equals(u.getIp()))
					user.setReady(true);
			}
			// broadUser();
			// 开始游戏
			beginGame();
			break;
		case CMD_BEGIN_CARDS:// 收到发的牌0
			cardDataList.clear();
			cardDataList = (ArrayList<CardData>) msg.getBody();
			updateBeginCard();
			startLandlord();
			break;

		case CMD_BROAD_NEXT_LANDLORD: // 被通知显示抢分按钮
			updateLandlord(1);
			break;
		case CMD_HOST_FINISH_LANDLORD: // 按下了抢分按钮
			u = (User) msg.getBody();
			// out("fenfen");
			// out("分:"+u.getLandlordScore());
			// out("id:"+u.getDeskId());
			// 判断抢分完成没有
			if (!judgeFinishLandlord())
				nextLandlord(u.getDeskId());
			break;
		case CMD_BEGIN_LANDLORD_CARDS: // 收到地主牌
			cardDataList.clear();
			cardDataList = (ArrayList<CardData>) msg.getBody();
			netGameScreen.gInfo.setLandlordId(cardDataList.get(0).deskId);
			updateBeginCard();
			updateLandLordHead();
			break;
		case CMD_HOST_START_CARDS: // 谁是地主
			sendCMD(new Msg(me.getName(), me.getIp(), null,
					(String) msg.getBody(), CMD_START_CARDS, null));
			break;
		case CMD_START_CARDS: // 地主开始出牌
			showCardButton();
			break;
		case CMD_HOST_SEND_CARDS: // 有人出牌了

			int desk = -1;
			for (User s : users) {
				if (s.getIp().equals(msg.getSendUserIp()))
					desk = s.getDeskId();
			}
			out(desk + ":出牌");
			// sendID
			for (User user : users) {
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp()))
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_SEND_CURRENTID_CARDS,
								(desk + 1) % 3));
				}
			}
			netGameScreen.gInfo.setCurrentPlayerId((desk + 1) % 3);
			cardDataList.clear();
			cardDataList = (ArrayList<CardData>) msg.getBody();
			for (CardData cd : cardDataList)
				out("出了:" + cd.imageId);
			// 将牌分给组内人
			for (User user : users) {
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp())) {
						sleepT(300);
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_SEND_CARDS, new ArrayList(
										cardDataList)));
						// out("给:"+user.getDeskId()+":size:"+cardDataList.size());
					}
				}
			}
			updateCards(desk);
			// 下一个人
			if (!(Max == 2 && desk == 1)) {
				// out("下一个人");
				sendCMD(new Msg(me.getName(), me.getIp(), null,
						currentRoom.getIp(), CMD_HOST_START_CARDS, users.get(
								(desk + 1) % 3).getIp()));
			}
			// Computer出牌
			if (Max == 2 && netGameScreen.gInfo.getCurrentPlayerId() == 2) {
				// 电脑出牌
				out("电脑出牌");
				sleepT(1000);
				cardDataList.clear();
				netGameScreen.gInfo.playerOutList[2] = Comm.getBestAI(
						netGameScreen.gInfo.playerList[2],
						netGameScreen.gInfo.getOppo());
				if (netGameScreen.gInfo.playerOutList[2] == null)
					out("电脑没牌出");
				else {
					out("电脑出的牌:" + netGameScreen.gInfo.playerOutList[2].size());
					String s = "";
					for (Card cd : netGameScreen.gInfo.playerOutList[2]) {
						s += cd.value + ",";
						cardDataList.add(new CardData(cd.imageId, 2));
					}
					out("电脑牌:" + s);
				}
				sendCMD(new Msg(me.getName(), me.getIp(), null,
						currentRoom.getIp(), CMD_HOST_SEND_CARDS_COMPUTER,
						cardDataList));
			}
			break;
		case CMD_HOST_SEND_CARDS_COMPUTER: // 电脑接收
			out("电脑出牌来接收");
			// sendID
			for (User user : users) {
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp()))
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_SEND_CURRENTID_CARDS,
								(2 + 1) % 3));
				}
			}
			netGameScreen.gInfo.setCurrentPlayerId((2 + 1) % 3);
			cardDataList.clear();
			cardDataList = (ArrayList<CardData>) msg.getBody();
			// out("cc");
			// 将牌分给组内人
			for (User user : users) {
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp())) {
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_SEND_CARDS, cardDataList));
						// out("向发送了牌:"+user.getDeskId());
					}
				}
			}
			// out("bb");
			updateCards(2);
			// out("电脑出了牌");
			// 下一个人
			sendCMD(new Msg(me.getName(), me.getIp(), null,
					currentRoom.getIp(), CMD_HOST_START_CARDS, users.get(
							(2 + 1) % 3).getIp()));

			break;
		case CMD_SEND_CARDS: // 收到广播来的牌
			int desk1 = -1;
			while (desk1 < 0) {
				desk1 = (netGameScreen.gInfo.getCurrentPlayerId() + 2) % 3;
			}
			// out("出牌的人"+desk1);
			cardDataList.clear();
			cardDataList = (ArrayList<CardData>) msg.getBody();
			out("xx:" + cardDataList.size());
			updateCards(desk1);
			break;
		case CMD_SEND_CURRENTID_CARDS: // 收到当前ID
			netGameScreen.gInfo.setCurrentPlayerId((Integer) msg.getBody());
			break;
		}
	}

	// ***********************************************游戏逻辑**************************************************
	// AI
	public void orderComputer() {
		if (Max == 2) {
			User t1 = users.get(1), t2 = users.get(2);
			;
			users.remove(t1);
			users.remove(t2);
			users.add(t2);
			users.add(t1);
		}

	}

	public void addComputer() {
		if (Max == 2) {
			// out("addCPU");
			computer = new User("computer", "null");
			computer.setDeskId(2);
			computer.setReady(true);
			users.add(computer);
		}
	}

	// NET
	public void requestRoom() {
		// out("port:"+Max);
		roomList.clear();
		sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
				CMD_HOST_REQUEST_ROOM, me));
	}

	public void replyRoom(User user) {
		// out("sendCMD:CMD_REPLY_ROOM");
		sendCMD(new Msg(me.getName(), me.getIp(), null, user.getIp(),
				CMD_REPLY_ROOM, currentRoom));

	}

	public void createRoom() {
		// 加入自己当user
		me.setDeskId(users.size());
		users.add(me);
		addComputer();
		// out("currentSize:"+users.size());
		currentRoom = new Room(me.getIp(), 1);
		roomList.add(currentRoom);
		sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
				CMD_CREATE_ROOM, currentRoom));
		updateUserList();

	}

	public void joinRoom(Room r) {
		// out("申请加入:"+r.getIp()+",人数已有:"+r.getUserCount() );
		currentRoom = r;
		me.setDeskId(r.userCount);
		sendCMD(new Msg(me.getName(), me.getIp(), null, r.getIp(),
				CMD_HOST_JOIN_ROOM, me));
	}

	public void updateRoom() {
		// out("sendCMD:CMD_UPDATE_ROOM");
		sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
				CMD_UPDATE_ROOM, currentRoom));
	}

	public void broadUser() {
		// /out("sendCMD:CMD_BROAD_USERLIST");
		for (User user : users) {
			// out("广播:"+user.getIp());
			if (Max == 3 || (!user.getIp().equals("null")))
				sendCMD(new Msg(me.getName(), me.getIp(), null, user.getIp(),
						CMD_BROAD_USERLIST, users));
		}
		updateUserList();
	}

	public void leaveRoom1() {
		// out("leaveIp:"+me.getIp()+",HostIP:"+currentRoom.getIp());
		sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
				CMD_HOST_LEAVE_ROOM, me));
	}

	public void leaveRoom2(User u) {
		// out("2leaveIp:"+u.getIp()+",HostIP:"+currentRoom.getIp());
		if (currentRoom.getIp().equals(u.getIp())
				|| netGameScreen.gInfo.playerList[0].size() > 0) {
			// 解散桌子
			for (User user : users) {
				if (Max == 3 || (!user.getIp().equals("null")))
					sendCMD(new Msg(me.getName(), me.getIp(), null,
							user.getIp(), CMD_LEAVE_ROOM, me));
			}
			init();
			delRoom(currentRoom);
			removeRoom(currentRoom);
			LeaveRoom = true;
			users.clear();
			currentRoom = null;
			updateRoomList();
		} else {
			removeUser(u);
			currentRoom.userCount--;
			updateRoom();
			broadUser();
			sendCMD(new Msg(me.getName(), me.getIp(), null, u.getIp(),
					CMD_LEAVE_ROOM, null));
		}
	}

	public void delRoom(Room r) {
		sendCMD(new Msg(me.getName(), me.getIp(), null, getBroadCastIP(),
				CMD_DEL_ROOM, r));
	}

	public void getReady() {
		me.setReady(true);
		sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
				CMD_HOST_READY_ROOM, me));
	}

	public void beginGame() {
		int count = 0;
		for (User user : users) {
			if (user.isReady()) {
				count++;
			}
		}
		if (count == 3) {
			// out("准备完毕:开始发牌");
			// 取消准备图标
			for (User user : users) {
				user.setReady(false);
			}
			broadUser();
			cardDataList.clear();
			int len = 54;
			for (int i = 1; i <= len; i++)
				cards[i] = new CardData(i, -1);
			// out("洗牌");
			// 洗牌
			for (int i = 0; i < 100; i++) {
				Random random = new Random();
				int a = random.nextInt(54) + 1;
				int b = random.nextInt(54) + 1;
				CardData k = cards[a];
				cards[a] = cards[b];
				cards[b] = k;
			}
			// out("发牌");
			// 发牌
			for (int i = 1; i <= 51; i++) {
				cardDataList.add(cards[i]);
				cards[i].setDeskId(i % 3);
			}
			// out("地主牌");
			// 地主牌
			for (int i = 52; i <= 54; i++) {
				cardDataList.add(cards[i]);
				cards[i].setDeskId(3);
			}
			// 将牌分给组内人
			for (User user : users) {
				// out("ip:"+user.getIp());
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp()))
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_BEGIN_CARDS, cardDataList));
				}
			}
			// out(cardDataList.size()+":ab");
			updateBeginCard();
			startLandlord();
		} else
			broadUser();
	}

	public void startLandlord() {
		if (me.getIp().equals(currentRoom.getIp())) {// 房主确定谁是地主
			netGameScreen.gInfo.FirstLandLordId = 0;// 房主先抢地主
			netGameScreen.gInfo
					.setCurrentPlayerId(netGameScreen.gInfo.FirstLandLordId);
			updateLandlord(1);
		}
	}

	public void finishLandlord() {
		sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
				CMD_HOST_FINISH_LANDLORD, me));
	}

	public void nextLandlord(int deskId) {
		// out("通知下一个抢地主:"+users.get((deskId+1)%3).getIp());
		sendCMD(new Msg(me.getName(), me.getIp(), null, users.get(
				(deskId + 1) % 3).getIp(), CMD_BROAD_NEXT_LANDLORD, null));
	}

	public boolean judgeFinishLandlord() {
		int count = 0;
		User maxUser;
		for (User user : users) {
			if (user.getLandlordScore() > -1)
				count++;
		}
		if (count == 3) {
			// out("完成抢分");
			int landlordId = Comm.getLandOwnerId(new int[] {
					users.get(0).getLandlordScore(),
					users.get(1).getLandlordScore(),
					users.get(2).getLandlordScore() }, 0);
			// out("地主ID:"+landlordId);
			netGameScreen.gInfo.LandlordId = landlordId;
			for (User user : users) {
				user.setLandlordScore(-1);
				// out("设置:"+user.getIp()+":取消分数显示");
			}
			broadUser();
			// 将地主牌送入地主
			cardDataList.clear();
			for (Card c : netGameScreen.gInfo.playerList[3]) {
				cardDataList.add(new CardData(c.imageId, landlordId));
			}
			// 将牌分给组内人
			for (User user : users) {
				// out("发牌给:"+user.getIp());
				if (Max == 3 || (!user.getIp().equals("null"))) {
					if (!user.getIp().equals(currentRoom.getIp()))
						sendCMD(new Msg(me.getName(), me.getIp(), null,
								user.getIp(), CMD_BEGIN_LANDLORD_CARDS,
								cardDataList));
				}
			}
			// 因为自己不需要再发一遍给自己
			updateBeginCard();
			updateLandLordHead();
			broadUser();
			// 通知地主出牌
			startHostCard();
			return true;
		}
		return false;
	}

	public void startHostCard() {
		// out("地主ID:"+users.get(netGameScreen.gInfo.LandlordId).getIp());
		sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
				CMD_HOST_START_CARDS, users.get(netGameScreen.gInfo.LandlordId)
						.getIp()));
	}

	public void sendHostCards() {
		// out("通知Host出牌了");
		cardDataList.clear();
		for (Card cd : netGameScreen.gInfo.playerOutList[me.getDeskId()]) {
			// out("取2:"+cd.imageId);
			cardDataList.add(new CardData(cd.imageId, me.getDeskId()));
		}

		sendCMD(new Msg(me.getName(), me.getIp(), null, currentRoom.getIp(),
				CMD_HOST_SEND_CARDS, cardDataList));
	}

	// UI
	void flush(List<Card> list) {
		sendMes2(MES_FLUSH_CARDS, list);
	}

	void updateCards(int desk) {

		flush(netGameScreen.gInfo.playerOutList[(desk + 1) % 3]);
		if (netGameScreen.gInfo.playerOutList[desk] != null)
			netGameScreen.gInfo.playerOutList[desk].clear();
		for (Card c1 : netGameScreen.gInfo.playerList[desk]) {
			for (CardData card : cardDataList) {
				if (card.imageId == c1.imageId) {
					netGameScreen.gInfo.playerOutList[desk].add(c1);
				}
			}
		}
		if (netGameScreen.gInfo.playerOutList[desk] != null)
			netGameScreen.gInfo.playerList[desk]
					.removeAll(netGameScreen.gInfo.playerOutList[desk]);
		// 发牌
		sendMes2(MES_SEND_CARDS, desk);
	}

	void updateLandLordHead() {
		sendMes2(MES_UPDATE_LANDLORDHEAD, null);
	}

	void showCardButton() {
		// out("显示出牌按钮");
		sendMes2(MES_SHOW_CARDBUTTON, null);
	}

	void updateLandlord(int visible) {
		sendMes2(MES_UPDATE_LANDLORD, visible);
	}

	void updateBeginCard() {
		// out(cardDataList.size()+":a");
		for (CardData card : cardDataList) {
			Card cards = new Card(card.getImageId(), netGameScreen.atlsa);
			netGameScreen.gInfo.playerList[card.getDeskId()].add(cards);
			// netGameScreen.net.out(card.getDeskId()+":"+me.getDeskId());
			if (card.getDeskId() == me.getDeskId()) {
				cards.addListener(new ClickListener() {
					@Override
					public boolean touchDown(InputEvent event, float x,
							float y, int pointer, int button) {
						Card c = (Card) event.getListenerActor();
						if(netGameScreen.gInfo.getGameState()==2)
							c.move();
						c.touched=1;
						Log.v("test", "touch" + c.imageId);
						return super.touchDown(event, x, y, pointer, button);
					}

				});
			}
		}
		// 发牌
		sendMes2(MES_UPDATE_BEGINCARD, null);
	}

	void updateRoomList() {
		sendMes1(MES_UPDATE_ROOM, null);
	}

	void updateUserList() {
		sendMes2(MES_UPDATE_User, null);
	}

	// ***********************************************功能函数*************************************************
	public boolean isContainsRoom(Room r) {
		for (int i = 0; i < roomList.size(); i++) {
			if (roomList.get(i).getIp().equals(r.getIp()))
				return true;
		}
		return false;
	}

	public boolean isContainsUser(User u) {
		for (int i = 0; i < users.size(); i++) {
			// out(users.get(i).getIp()+":"+u.getIp());
			if (users.get(i).getIp().equals(u.getIp())) {
				return true;
			}
			// out("lala");
		}
		// out("false");
		return false;
	}

	public void removeRoom(Room room) {

		Room t = null;
		for (Room r : roomList) {
			if (r.getIp().equals(room.getIp()))
				t = r;
		}
		roomList.remove(t);
	}

	public void removeUser(User user) {
		User t = null;
		for (User r : users) {
			if (r.getIp().equals(user.getIp()))
				t = r;
		}
		users.remove(t);
	}

	// 发送Handle
	public void sendMes1(int cmd, Object o) {
		Message m = new Message();
		m.what = cmd;
		m.obj = o;
		if (rommScreen != null)
			rommScreen.handler.sendMessage(m);

	}

	public void sendMes2(int cmd, Object o) {
		Message m = new Message();
		m.what = cmd;
		m.obj = o;
		if (netGameScreen != null)
			netGameScreen.handler.sendMessage(m);
	}

	// 获取当前时间
	public static long getTimel() {
		return System.currentTimeMillis();
	}

	// 得到广播ip, 192.168.0.255之类的格式
	public String getBroadCastIP() {
		String ip = getLocalHostIp().substring(0,
				getLocalHostIp().lastIndexOf(".") + 1)
				+ "255";
		return ip;
	}

	// 获取本机IP
	public String getLocalHostIp() {
		String ipaddress = "";
		try {
			Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces();
			// 遍历所用的网络接口
			while (en.hasMoreElements()) {
				NetworkInterface nif = en.nextElement();// 得到每一个网络接口绑定的所有ip
				Enumeration<InetAddress> inet = nif.getInetAddresses();
				// 遍历每一个接口绑定的所有ip
				while (inet.hasMoreElements()) {
					InetAddress ip = inet.nextElement();
					if (!ip.isLoopbackAddress()
							&& InetAddressUtils.isIPv4Address(ip
									.getHostAddress())) {
						return ipaddress = ip.getHostAddress();
					}
				}

			}
		} catch (SocketException e) {
			System.out.print("获取IP失败");
			e.printStackTrace();
		}
		return ipaddress;

	}

	// 对象封装成消息
	public byte[] toByteArray(Object obj) {
		byte[] bytes = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(obj);
			oos.flush();
			bytes = bos.toByteArray();
			oos.close();
			bos.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return bytes;
	}

	// 消息解析成对象
	public Object toObject(byte[] bytes) {
		Object obj = null;
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
			ObjectInputStream ois = new ObjectInputStream(bis);
			obj = ois.readObject();
			ois.close();
			bis.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}
		return obj;
	}

	public static void out(String s) {
		Log.v("test", s);
	}

	public void sleepT(long time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

如果想要全部源码的,可以 email 我 [email protected] 但是只能研究所用

PS:由于博客中毒我把所有文章都删了才解封。。

Libgdx: android单机斗地主支持局域网wifi联网的网络模块核心代码,布布扣,bubuko.com

时间: 2024-10-01 03:06:26

Libgdx: android单机斗地主支持局域网wifi联网的网络模块核心代码的相关文章

BasicNetworkingSample Android判断网络连接是wifi联网还是其他联网

    /**      * Check whether the device is connected, and if so, whether the connection      * is wifi or mobile (it could be something else).      */     private void checkNetworkConnection() {       ConnectivityManager connMgr =           (Connecti

android中百度地图定位的实现方法(仅适用于真机+WIFI联网环境)

注意:此方法的环境是:真机(小米手机,系统版本为Android4.2.2)+WIFI联网(才能实现最后的运行结果):使用虚拟机调试会出现各种问题. 第一步:下载SDK和申请Key 到百度的网站http://developer.baidu.com/map/ 第二步:然后选择SDK下载.(根据需要下载需要的SDK) 第三步:申请key http://developer.baidu.com/map/index.php?title=androidsdk 然后选择创建应用 需要填写:应用名称和数字签名(S

分享一个Android版 仿QQ局域网即时通信软件(可发文件、语音、录音)

一.支持的功能有文字信息交互.语音聊天.发送文件和录音 源码会在后面附上. 二.UI展示图 三.经过我的测试,是非常成功的.只是有一点不足就是语音实时通话的时候声音会回声甚至死机. 文件传送和文字,录音都比较成功. 四.本软件是用Java编码,在安卓平台上的应用.使用了UDP协议和TCP协议. 大家可以学习这两部分的代码. 里面注释还是比较多. 五.当然我只是个学生,这个只是学生版本,仅供大家学习借鉴之用.绝对不能用于商业拿去直接卖,或者改改就上架某市场. 六.宣传下本人的小制作: 单机斗地主-

【转并修改】VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试

转:http://www.cnblogs.com/ShaYeBlog/p/4072074.html VS2013内置了IISExpress.做asp.net MVC的web项目开发时,Ctrl+F5和F5启动项目运行(后者是调试模式)的同时都会打开IISExpress,事实上本机对该web项目走的就是这个内置的server.默认情况下,该server运行的web项目不支持局域网内其他机器的访问.为了做到这一点: 1.关闭防火墙. 2.修改C:\Users\Administrator\Docume

VS2013 MVC Web项目使用内置的IISExpress支持局域网内部机器(手机、PC)访问、调试

VS2013内置了IISExpress.做asp.net MVC的web项目开发时,Ctrl+F5和F5启动项目运行(后者是调试模式)的同时都会打开IISExpress,事实上本机对该web项目走的就是这个内置的server.默认情况下,该server运行的web项目不支持局域网内其他机器的访问.为了做到这一点: 1.关闭防火墙. 2.修改C:\Users\Administrator\Documents\IISExpress\config目录下的applicationhost.config的文件

检查android设备是否支持某些功能

我们在开发APP的时候,应用程序可能需要设备支持某些功能才能保证应用程序的运行.例如需要支持电话,NFC.陀螺仪等等. 我们可以使用PackageManager对象的hasSystemFeature方法来检查当前设备是否支持某些功能. 第一种方法: 使用代码检查设备是否支持某些功能.这种方法比较好.因为不论app来自哪里.都能准确的判断设备是否支持应用所需的功能. 代码: PackageManager pm = getPackageManager(); // 获取是否支持电话 boolean t

Getting started with &#39;User Accounts&#39; on Android 5.0 Lollipop (android的多用户支持)

With Android 5.0 Lollipop, Google is adding true multi-user support for tablets and smartphones alike. When Google released Android 4.2 it included multiple user accounts for tablets; however, smartphone users were left in the cold. (In Google's defe

cocos2dx《单机斗地主》源码解剖之八 电脑玩家出牌与跟牌(结束)

上一篇文章对玩家手中的牌进行分析归类,下面就该实现电脑玩家出牌与跟牌的策略了.首先我们来看看出牌的策略,代码如下: void GameScene::update(float delta){ switch (m_iState) { case 0: SendPk(); break; case 1: schedule(schedule_selector(GameScene::Call),1); break; case 2: scheduleOnce(schedule_selector(GameScen

JAVA面向对象编程课程设计——网络版单机斗地主

一.团队介绍 成员姓名 任务分配 成员课程设计博客链接 兰泽祥(组长) 数据库,斗地主规则的实现,人机自动出牌的算法,实体类的设计 吴修恩 JSP界面的设计,前后端数据的交互,servlet设计,动态更新界面 二.项目GIT地址 fight_against_landlords 三.项目git提交记录截图 四.项目功能架构图.主要功能流程图 五.面向对象设计类图 1.CardGames类图 2.CardGame类图 3.Card类图 4.UserUserInformation类图 5.User类图