⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 tanknewmsg.java

📁 基于尚学堂坦克大战的基础上开发,支持多人对战,在线聊天,坦克大战网络版.
💻 JAVA
字号:
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;

/**
 * 在服务器有启动下,客户端启动发生的事件,生成一辆坦克
 * @author Nightelf暗夜精灵
 *
 */
public class TankNewMsg implements Msg {
	int msgType = Msg.TANK_NEW_MSG;

	Tank tank;

	TankClient tc;

	public TankNewMsg(Tank tank) {
		this.tank = tank;
	}

	public TankNewMsg(TankClient tc) {
		this.tc = tc;
	}

	public void send(DatagramSocket ds, String IP, int udpPort) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			dos.writeInt(msgType);
			dos.writeInt(tank.getTankId());
			dos.writeUTF(tank.getUser());
			dos.writeBoolean(tank.isReady());
			dos.writeInt(tank.x);
			dos.writeInt(tank.y);
			dos.writeInt(tank.dir.ordinal());
			dos.writeBoolean(tank.good);
			dos.writeBoolean(tank.isAuto());
		} catch (IOException e) {
			e.printStackTrace();
		}
		byte[] buf = baos.toByteArray();
		try {
			DatagramPacket dp = new DatagramPacket(buf, buf.length,
					new InetSocketAddress(IP, udpPort));
			ds.send(dp);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void parse(DataInputStream dis) {
		System.out.println("客户端接收一份服务端发来TanNew的数据!");
		try {
			int id = dis.readInt();
			System.out.println(id);
			if (tc.tank.getTankId() == id) {
				return;
			}
			String user = dis.readUTF();
			boolean ready = dis.readBoolean();
			int x = dis.readInt();
			int y = dis.readInt();
			Direction dir = Direction.values()[dis.readInt()];
			boolean good = dis.readBoolean();
			boolean auto = dis.readBoolean();
	//		System.out.println("id:" + id + "-x:" + x + "-y:" + y + "-dir:"
	//				+ dir + "-good:" + good);

			boolean exists = false;
			for (int i = 0; i < tc.playerTanks.size(); i++) {

				Tank tank = (Tank) tc.playerTanks.get(i);
				if (tank.getTankId() == id) {
					exists = true;
				}
			}
			
			
			if (!exists) {
				Msg msg = new TankNewMsg(tc.tank);
				tc.client.send(msg);
				Tank newtank = new Tank(x, y, id,good,false, dir, tc);
				newtank.setUser(user);
				newtank.setReady(ready);
				if(ready){
					int count = tc.getReadyer();
					count++;
					tc.setReadyer(count);
				}
				System.out.println(id);
				tc.playerTanks.add(newtank);
				Msg repaintMsg = new JoinRepaintMsg(tc);
				tc.client.send(repaintMsg);
				System.out.println("当前坏坦克数量:"+tc.badTanks.size());
				
			}
			

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -