Jump to content

Giving players extra data.


Briggybros

Recommended Posts

I'm trying to give every player a money variable, but I'm having some trouble. I have created a connection handler like so;

	@EventHandler
public void load(FMLInitializationEvent event) {
	proxy.init();

	NetworkRegistry.instance().registerConnectionHandler(new ConnectionHandler());
}

 

In the playerLoggedIn method I then do this:

	@Override
public void playerLoggedIn(Player player, NetHandler netHandler, INetworkManager manager) {
	EntityPlayer entityPlayer = (EntityPlayer) player;
	System.out.println("Player joined!");
	NBTTagCompound tag = entityPlayer.getEntityData();

	NBTBase modeTag = tag.getTag("credits");
	if(modeTag == null) {
		XXXX.credits.put(entityPlayer.username, 30);
		tag.setInteger("credits", 30);
	} else {
		XXXX.credits.put(entityPlayer.username, ((NBTTagInt)modeTag).data);
	}

	ByteArrayOutputStream bos = new ByteArrayOutputStream(4);
	DataOutputStream outputStream = new DataOutputStream(bos);

	int credits = 0;

	for (String key : XXXX.credits.keySet()) {
		if(key.equalsIgnoreCase(((EntityPlayer)player).username))credits = XXXX.credits.get(key);
	}

	try {
		outputStream.writeInt(credits);
	} catch (Exception ex) {
		ex.printStackTrace();
	}

	Packet250CustomPayload packet = new Packet250CustomPayload();
	packet.channel = "CreditValues";
	packet.data = bos.toByteArray();
	packet.length = bos.size();

	PacketDispatcher.sendPacketToPlayer(packet, player);
}

Where XXXX.credits is a HashMap like so:

public static HashMap<String, Integer> credits = new HashMap<String, Integer>();

 

The packet is then handled like so:

	@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {

	if (packet.channel.equals("CreditVaules")) {
		handleValues(packet);
	}

private void handleValues(Packet250CustomPayload packet) {
	Side side = FMLCommonHandler.instance().getEffectiveSide();
	if (side.isClient()) {
		DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));

		int credits = 0;

		try {
			credits = inputStream.readInt();
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		XXXX.myCredits = credits;
	}
}
}

Where myCredits is an integer to hold the individual client's credits.

 

I then print this number onto the screen, However, it is always 0. I don't know why this is the case. Can someone help?

 

NOTE: I'm drunk when writing this so if something doesn't make sense just ask.

Link to comment
Share on other sites

yes, no, hi, im also playing with money in my mod

 

<optional> my mod requires that the player can receives money even while offline, so its store in a database isntead of the nbt</optional>

 

you should use IExtendedEntityProperties instead

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

Link to comment
Share on other sites

How is this used properly for both client and server?

If you check for instanceof EntityPlayer in the EntityConstructing event a dummy of your data will also be present on the client. Use packets to sync the data between the client & server version.

 

I've basically done just that..

 

My main data class now looks like:

package mods.XXXX;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;

import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.world.World;
import net.minecraftforge.common.IExtendedEntityProperties;

public class PlayerVariables implements IExtendedEntityProperties {

public static final String IDENTIFIER = "xxxxvalues";

public static PlayerVariables fromPlayer(EntityPlayerMP player) {
	return (PlayerVariables)player.getExtendedProperties(IDENTIFIER);
}

int xxx = 0;
int yyy = 68;

EntityPlayerMP player;

@Override
public void saveNBTData(NBTTagCompound compound) {
	compound.setInteger("xxx", xxx);
	compound.setInteger("yyy", yyy);
}

@Override
public void loadNBTData(NBTTagCompound compound) {
	if (compound.hasKey("xxx")) {
		this.addXxx(compound.getInteger("xxx"));
	} else {
		this.addXxx(30);
	}

	if (compound.hasKey("yyy")) {
		this.useYyy(68 - (68 - compound.getInteger("yyy")));
	} else {
		this.useYyy(0);
	}
}

@Override
public void init(Entity entity, World world) {
	player = (EntityPlayerMP) entity;
}

public void addXxx(int value) {
	xxx += value;
	sendPacket();
}

public boolean removeXxx(int value) {
	if (xxx > value) {
		xxx -= value;
		sendPacket();
		return true;
	} else {
		return false;
	}
}

public boolean useYyy(int value) {
	if (yyy > value) {

		yyy -= value;

		sendPacket();
		return true;
	} else {
		return false;
	}
}

private void sendPacket() {
	ByteArrayOutputStream bos = new ByteArrayOutputStream(;
	DataOutputStream outputStream = new DataOutputStream(bos);
	try {
		outputStream.writeInt(yyy);
		outputStream.writeInt(xxx);
	} catch (Exception ex) {
		ex.printStackTrace();
	}

	Packet250CustomPayload packet = new Packet250CustomPayload();
	packet.channel = "XxxxValues";
	packet.data = bos.toByteArray();
	packet.length = bos.size();

	PacketDispatcher.sendPacketToPlayer(packet, (Player)player);
}
}

 

The entity constructor code is..

package mods.XXXX;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;

import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;

import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraftforge.event.EventPriority;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.EntityEvent.EntityConstructing;

public class EntityConstructListener {

@ForgeSubscribe(priority = EventPriority.NORMAL)
public void onEntityConstuct(EntityConstructing event) {
	if (event.entity instanceof EntityPlayerMP) {
		EntityPlayerMP ep = (EntityPlayerMP) event.entity;
		ep.registerExtendedProperties(PlayerVariables.IDENTIFIER, new PlayerVariables());

	}
}
}

 

My packet handler is as so:

package mods.XXXX;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import mods.XXXX.client.ClientProxy;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;

public class PacketHandler implements IPacketHandler {

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {

	Side side = FMLCommonHandler.instance().getEffectiveSide();

	if (packet.channel.equals("Some other packet") && side == Side.SERVER) {
		handleXxxx(packet, playerEntity); // method is hidden <- this one already works
	}

	if (packet.channel.equals("XxxVaules") && side == Side.CLIENT) {
		handleValues(packet);
	}
}

private void handleValues(Packet250CustomPayload packet) {
	DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));

	int yyy = 0;
	int xxx = 0;

	try {
		yyy = inputStream.readInt();
		xxx = inputStream.readInt();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	ClientProxy.xxx = xxx;
	ClientProxy.yyy = yyy;
}
}

I then use ClientProxy.xxx and ClientProxy.yyy as variables in calculations for a graphical overlay. However, the variables do not set to default when testing on singleplayer, but both are at 0. Why are they 0, they should be send from the data.

Link to comment
Share on other sites

1: can you NOT use xxx yyy as variable name, it makes the code 1000 000 times harder to read

-if your variables are actually called xxx yyy it is VERY shitty name btw

 

2: can you println in your packet handler (client side) to check if you are actually receiving the packet ?

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

Link to comment
Share on other sites

This is my packet handler, the System.out.println isn't called when on a singleplayer game

package mods.SaberMod;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;

import mods.SaberMod.client.ClientProxy;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;
import cpw.mods.fml.relauncher.Side;

public class PacketHandler implements IPacketHandler {

@Override
public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {

	Side side = FMLCommonHandler.instance().getEffectiveSide();

	if (packet.channel.equals("SaberExtend") && side == Side.SERVER) {
		handleExtend(packet, playerEntity);
	}

	if (packet.channel.equals("SaberVaules") && side == Side.CLIENT) {
		handleValues(packet);
	}
}

private void handleExtend(Packet250CustomPayload packet, Player playerEntity) {

	DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));

	int stage = 0;
	int damage = 0;

	try {
		stage = inputStream.readInt();
		damage = inputStream.readInt();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	stage = (stage == 0) ? 1 : 0;

	EntityPlayerMP player = (EntityPlayerMP) playerEntity;
	player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack((256 + SaberMod.BASE_ITEM_ID + stage), 1, damage));
	player.updateHeldItem();
}

private void handleValues(Packet250CustomPayload packet) {
	DataInputStream inputStream = new DataInputStream(new ByteArrayInputStream(packet.data));

	Minecraft mc;
	mc = Minecraft.getMinecraft();
	mc.getLogAgent().logFine("Saber Values packet recieved.");

	int force = 0;
	int credits = 0;

	try {
		force = inputStream.readInt();
		credits = inputStream.readInt();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}

	ClientProxy.credits = credits;
	ClientProxy.force = force;
}
}

Link to comment
Share on other sites

more importantly

 

@Override

public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {

System.out.println("i was called");

}

would this be called ? because if this isnt called then you are not registering your packet handlers correctly :)

 

 

 

how to debug 101:http://www.minecraftforge.net/wiki/Debug_101

-hydroflame, author of the forge revolution-

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Announcements



  • Recently Browsing

    • No registered users viewing this page.
  • Posts

    • Hi I have an issue with a server it solved deleting the ice and fire but my friends and me really want to use it does any of these mods are causing the issue due to incompatibility  Security craft Aquaculture Architectury Artifacts Astikorcarts Baubles BetterCaves yungs BetterStrongholds yungs BetterMineshafts yungs Bountiful Byg  Callablehorses Carry on Chococraft Citadel Clumps Collective Comforts Corailrecycler Craftable horse armor Comes alive Curios forge Decocraft Dungeonsarise  Open blocks elevator Expandability Farlanders Goblin traders Hwyla  Ice and fire Infernal expansion Jei Jump over fences Mantle  Macaws bridges Macaws doors Macaws fences Macaws furniture  Macaws fencesbyg Morpheus Mouse tweaks Mowzies mobs Obfuscate Paraglider Patchouli  Pick up notifier Random village names Spartan shields Small ships Sophisticated backpacks Spartan weaponry Storage drawers straw golem Structure gel Twilight forest  Tinkers construct Two players one horse  Valhesia core  Valhesia structures  Way stones  Vehicle mod  Wall jump Wings Wolves with armor Xptome  Xaeros minimap  Yungsapi  
    • { "type": "magic_overhaul:rune_inscribing", "base": { "item": "//base item" }, "template": { "item": "//template item" }, "output": { "count": 1, "item": "//output item" } } ^ Ok, where is your recipe JSON placed in your file structure? What's it called? And paste the actual JSON you're testing with, because it needs to be valid.
    • I'm trying to run Forge 1.12.2 on Minecraft  so I can use certain mods, but this error popped up. I've seen multiple errors but I just can't figure this one out. Unable to locate the Java runtime. Error details: 0x00000000 - system: The operation completed successfully. Filename on disk:  Path: . Exists: Directory
    • https://mclo.gs/b422RFc
    • Плагин и Приват
  • Topics

×
×
  • Create New...

Important Information

By using this site, you agree to our Terms of Use.