Jump to content

custom block that prevents spawning of mobs in a certain perimeter


Thaliviel

Recommended Posts

  • Replies 61
  • Created
  • Last Reply

Top Posters In This Topic

Mmmmh...

 

I think when the world is loading, right?

If a player is changing dimensions, the new dimension will be loaded as world. And when a player logs into the game, the world will be loaded without triggering PlayerEvent.PlayerChangedDimensionEvent.

 

So do I put WorldEvent.Load in my main mod file and use override?

If the game automatically calls readFromNBT, how do I access the BlockList that was loaded?

Link to comment
Share on other sites

Write a get method for it like that

public static MyData get(World world) {
MyData handler = (MyData )world.loadItemData(MyData .class, IDENTIFIER);
if(handler==null) {
	handler = new MyData ();
	world.setItemData(IDENTIFIER, handler);
}
return handler;
}

 

And here is how to use forge events

 

http://www.minecraftforum.net/forums/mapping-and-modding/mapping-and-modding-tutorials/1571567-forge-1-6-4-1-8-eventhandler-and

Link to comment
Share on other sites

Wouldn't it be easiest to just manually scan for the block in range when the mob tries to spawn?

 

I can't see it being that resource intensive to do some iteration.

 

That depends on the range.

If I set a range of 50 Blocks (in a cube-ish range around the block, not a sphere), each spawn will check 100*100*100 Blocks, which is 1 million blocks. And that is a bit too much... Storing the data to a small list and saving/loading the list is much more elegant, I think.

Link to comment
Share on other sites

Write a get method for it like that

public static MyData get(World world) {
MyData handler = (MyData )world.loadItemData(MyData .class, IDENTIFIER);
if(handler==null) {
	handler = new MyData ();
	world.setItemData(IDENTIFIER, handler);
}
return handler;
}

 

Okay, I'm finally getting close - thanks to your help!

 

The identifier - is that the DATA_NAME of my extended WorldSavedData?

public class MBBlockList extends WorldSavedData {

private static final String DATA_NAME = MonsterBlocker.MODID + "_BlockList";
public List<Position> mbBlockList = new ArrayList();

public MBBlockList() {
    super(DATA_NAME);
}

 

The DATA_NAME is "MonsterBlocker_BlockList", so I added this method to my main mod file:

    public static MBBlockList get(World world) {
    	MBBlockList handler = (MBBlockList) world.loadItemData(List.class, "MonsterBlocker_BlockList");
	if(handler==null) {
		handler = new MBBlockList();
		world.setItemData("MonsterBlocker_BlockList", handler);
	}
	return handler;
}

 

And I have a stub EventHandler:

public class MBEventHandler {

@ForgeSubscribe //1.6.4
public void onWorldEventLoad(WorldEvent.Load event)
{
	MBBlockList test = MonsterBlocker.get(event.world);
}

}

 

Is that okay so far? So I have to tell the EventHandler the world and it will return some... uh, Data of the type MBBlockList? Sorry, I'm having problems understanding these different concepts and I'm still learning. But I try my best!

Link to comment
Share on other sites

Wouldn't it be easiest to just manually scan for the block in range when the mob tries to spawn?

 

I can't see it being that resource intensive to do some iteration.

 

Depends on the case. But imagine, a range of 10 is already 1000 blocks to check..

 

Yes IDENTIFIER is the DATANAME. But you shouldnt say world.setItemData("MonsterBlock_BlockList",handler). Use the String variable you defined world.setItemData(DATANAME, handler)

 

You call the method and get your handler back, where you can getter methods that return u the list of blocks

Link to comment
Share on other sites

Depends on the case. But imagine, a range of 10 is already 1000 blocks to check..

 

Scanning a whole chunk (65536 blocks) takes 0.4ms

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Depends on your computer :b

 

My 32 bit hardware dates back to 2009.  So yeah, it doesn't take long to look at every block in the chunk.  It's not a good idea unless you have a good reason (I did, and benchmarked it for that reason, had to use

Time.getNano()

because it was so fast).

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

I'm almost done.

 

I have my EventHandler class, where I can set the range of the Monster Blocker, and which contains two methods for loading the data and one for checking whether the spawn should be denied or not. This class contains the mbBlockList which is used while playing.

package com.monsterBlocker;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.world.World;
import net.minecraftforge.event.Event.Result;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingSpawnEvent;
import net.minecraftforge.event.world.WorldEvent;

public class MBEventHandler {

public List<Position> mbBlockList = new ArrayList();
public static final String DATA_NAME = MonsterBlocker.MODID + "_BlockList";
private static final int RANGE_SIDE = 50;
private static final int RANGE_UP = 50;
private static final int RANGE_DOWN = 10;

public static MBSave get(World world) {
    	MBSave handler = (MBSave) world.loadItemData(MBSave.class, DATA_NAME);
	if(handler==null) {
		handler = new MBSave();
		world.setItemData(DATA_NAME, handler);
	}
	return handler;
}

@ForgeSubscribe //1.6.4
public void onWorldEventLoad(WorldEvent.Load event)
{
	MBBlockList mbdata = get(event.world);
	mbBlockList = mbdata.getList();
}

@ForgeSubscribe
public void LSECheckSpawn(LivingSpawnEvent.CheckSpawn event)
{
	for (int i=0; i < mbBlockList.size(); ++i)
	{
		Position posBlock = mbBlockList.get(i);
		if ( (posBlock.x - RANGE_SIDE < event.x) && (event.x < posBlock.x + RANGE_SIDE) &&
			 (posBlock.y - RANGE_SIDE < event.y) && (event.y < posBlock.y + RANGE_SIDE) &&
			 (posBlock.z - RANGE_DOWN < event.z) && (event.z < posBlock.z + RANGE_UP) )
		{
			event.setResult(Result.DENY);
			System.out.println("Spawn Denied");
			return;
		}
	}
}

}

 

So the next thing to do is when a player adds a MB-Block, the mbBlockList should be updated (in the MBEventHandler) and the new mbBlockList should be sent to MBSave (extends WorldSavedData) and marked dirty.

 

However, when I write this:

public class MBBlock extends Block
{
        @Override
        public void onBlockAdded(World world, int x, int y, int z)
        {
        	Position pos = new Position(x, y, z);
        	MBEventHandler.mbBlockList.add(pos);
        	MBSave.onMBBlockChange(MBEventHandler.mbBlockList);
        }

an error occurs: "Cannot make a static reference to the non-static field MBEventHandler.mbBlockList"

How can I solve this? I'm not sure what happens when I make that static...

Link to comment
Share on other sites

You can't assume that there's only one

World

loaded at any time and maintain a single list from

WorldEvent.Load

/

Save

. Each time a block is added or removed, you need to fetch the

WorldSavedData

for that

World

and add or remove the position from that instance's list.

 

@ForgeSubscribe

doesn't exist any more, use

@SubscribeEvent

. I suspect you misread the event handler tutorial you followed.

 

You can use a for-each/enhanced for loop to iterate through a collection such as an array or list.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

You can't assume that there's only one

World

loaded at any time

 

Ah, that was my error in reasoning. So instead fetching the BlockList when a player joins a world, I have to fetch it every time I add/remove a MB-Block and every time the spawn is checked, because that depends on the world where the block is changed or the mob is spawning. And if I play in multiplayer, that may happen simultaneously in several dimensions.

 

Okay, I will fix that issue.

 

Thanks for the tip with the enhanced for loop.

 

And I'm actually still using 1.6.4, that's my old setup when I stopped playing/modding in 2014. I'll update that when I'm ready for that.

Link to comment
Share on other sites

Ah, that was my error in reasoning. So instead fetching the BlockList when a player joins a world, I have to fetch it every time I add/remove a MB-Block and every time the spawn is checked, because that depends on the world where the block is changed or the mob is spawning. And if I play in multiplayer, that may happen simultaneously in several dimensions.

 

Yes. Even in a LAN game, the players may be in separate dimensions to each other.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

Even SSP there are still multiple dimensions loaded (the game automagically generates and holds a portion of the Nether active if you have a Nether portal).

Apparently I'm a complete and utter jerk and come to this forum just like to make fun of people, be confrontational, and make your personal life miserable.  If you think this is the case, JUST REPORT ME.  Otherwise you're just going to get reported when you reply to my posts and point it out, because odds are, I was trying to be nice.

 

Exception: If you do not understand Java, I WILL NOT HELP YOU and your thread will get locked.

 

DO NOT PM ME WITH PROBLEMS. No help will be given.

Link to comment
Share on other sites

Even SSP there are still multiple dimensions loaded (the game automagically generates and holds a portion of the Nether active if you have a Nether portal).

Interesting, so that's why a zombie pigman managed to come into my overworld two days ago :D

 

Anyway, I'm almost done. The mod is running and System.out.println("Spawn Denied"); is printing, so theoretically it should work.

However, there are still monsters that spawn next to these blocks, and I tried to debug it for several hours without success...

 

EventHandler

package com.monsterBlocker;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.world.World;
import net.minecraftforge.event.Event.Result;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingSpawnEvent;
import net.minecraftforge.event.world.WorldEvent;

public class MBEventHandler {

//public List<Position> mbBlockList = new ArrayList();
public static final String DATA_NAME = MonsterBlocker.MODID + "_BlockList";
private static final int RANGE_SIDE = 50;
private static final int RANGE_UP = 50;
private static final int RANGE_DOWN = 10;

public static MBSave get(World world) {
    	MBSave handler = (MBSave) world.loadItemData(MBSave.class, DATA_NAME);
	if(handler==null) {
		handler = new MBSave();
		world.setItemData(DATA_NAME, handler);
	}
	return handler;
}

@ForgeSubscribe //1.6.4
public void LSECheckSpawn(LivingSpawnEvent.CheckSpawn event)
{
	List<Position> mbBlockList = new ArrayList();
	MBSave mbdata = get(event.world);
	mbBlockList = mbdata.getList();
	for (int i=0; i < mbBlockList.size(); ++i)
	{
		Position posBlock = mbBlockList.get(i);
		//Position posMonster = new Position((int) event.x, (int) event.y, (int) event.z);
		if ( (posBlock.x - RANGE_SIDE < event.x) && (event.x < posBlock.x + RANGE_SIDE) &&
			 (posBlock.y - RANGE_SIDE < event.y) && (event.y < posBlock.y + RANGE_SIDE) &&
			 (posBlock.z - RANGE_DOWN < event.z) && (event.z < posBlock.z + RANGE_UP) )
		{
			event.setResult(Result.DENY);
			System.out.println("Spawn Denied");
			return;
		}
	}
}
}

 

SavedData

package com.monsterBlocker;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraft.world.WorldSavedData;

public class MBSave extends WorldSavedData {

private static final String DATA_NAME = MonsterBlocker.MODID + "_BlockList";
public List<Position> mbBlockList = new ArrayList();

public MBSave() {
    super(DATA_NAME);
}

public MBSave(String s) {
	super(s);
}
    
    public List<Position> getList() {
    	return mbBlockList;
    }

/*public static List<Position> get(World world) {
	List<Position> handler = (List<Position>) world.loadItemData(List.class, "MonsterBlocker_BlockList");
	if(handler==null) {
		handler = new ArrayList();
		world.setItemData("MonsterBlocker_BlockList", handler);
	}
	return handler;
}*/
    
    public void onMBBlockChange(List<Position> newMBBlockList) {
    	mbBlockList = newMBBlockList;
    	markDirty();
    }
    
    public void addBlock(Position pos)
    {
    	mbBlockList.add(pos);
    }

    @Override
    public void readFromNBT(NBTTagCompound nbt) {
    	mbBlockList.clear();
    	
    	NBTTagList nbttaglist = nbt.getTagList("mbBlockList");
    	for (int i = 0; i < nbttaglist.tagCount(); ++i) {
    		NBTTagCompound posCompound = (NBTTagCompound) nbttaglist.tagAt(i);
    		Position pos = new Position(posCompound.getInteger("x"), posCompound.getInteger("y"), posCompound.getInteger("z"));
    		mbBlockList.add(pos);
    	}
    }

    @Override
    public void writeToNBT(NBTTagCompound nbt) {
    	
    	NBTTagList nbttaglist = new NBTTagList();
    	nbt.setTag("mbBlockList", nbttaglist);
    	for(int i = 0; i < mbBlockList.size(); i++) {
    		NBTTagCompound compound = new NBTTagCompound();
    		Position pos = mbBlockList.get(i);
       	    compound.setInteger("x", pos.x);
       	    compound.setInteger("y", pos.y);
       	    compound.setInteger("z", pos.z);
       	    nbttaglist.appendTag(compound);
    	}    	 
    }
}

 

Block

package com.monsterBlocker;

import java.util.ArrayList;
import java.util.List;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;

public class MBBlock extends Block
{

        public MBBlock (int id)
        {
                super(id, Material.iron);
                this.setUnlocalizedName(MonsterBlocker.mbBlock_unlocalizedName);
                this.setCreativeTab(CreativeTabs.tabBlock);
                
                this.setHardness(5F);
                this.setResistance(15F);
                this.setStepSound(Block.soundMetalFootstep);
                this.setLightValue(2F);
        }
        
        @Override
        @SideOnly(Side.CLIENT)
        public void registerIcons(IconRegister icon) {
        blockIcon = icon.registerIcon(MonsterBlocker.AID + ":" + "monsterBlocker");
        }

        @Override
        public void onBlockAdded(World world, int x, int y, int z)
        {
        	Position pos = new Position(x, y, z);
        	List<Position> mbBlockList = new ArrayList();
    		MBSave mbdata = MBEventHandler.get(world);
    		
    		mbBlockList = mbdata.getList();
    		mbBlockList.add(pos);
    		mbdata.onMBBlockChange(mbBlockList);

        	//System.out.println("I Added");      	
        }
        
        @Override
        public void breakBlock(World world, int x, int y, int z, int oldBlockID, int oldMetadata)
        {
        	Position pos = new Position(x, y, z);
        	List<Position> mbBlockList = new ArrayList();
    		MBSave mbdata = MBEventHandler.get(world);
    		
    		mbBlockList = mbdata.getList();
    		mbBlockList.remove(pos);
    		mbdata.onMBBlockChange(mbBlockList);
        }
}

 

And main file

package com.monsterBlocker;

import java.util.ArrayList;
import java.util.List;

import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.Mod.EventHandler;
import cpw.mods.fml.common.Mod.Instance;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.LanguageRegistry;

@Mod(modid = MonsterBlocker.MODID, name = MonsterBlocker.NAME, version = MonsterBlocker.VERSION)
@NetworkMod( channels = {"MB"}, clientSideRequired = true, serverSideRequired = true )

public class MonsterBlocker 
{
    public static final String MODID = "MonsterBlocker";
    public final static String AID = MODID.toLowerCase();
    public final static String NAME = "Monster Blocker";
    public static final String VERSION = "0.1";
    public static final String DATA_NAME = MonsterBlocker.MODID + "_BlockList";
    
    public static final String mbBlock_unlocalizedName = "monsterBlocker";
    public static final String mbBlock_name = "Monster Blocker";
    
    @SidedProxy( clientSide = "com.monsterBlocker.ClientProxy", serverSide = "com.monsterBlocker.CommonProxy" )
    public static CommonProxy proxy;
    
    public static Block monsterBlocker;

    // The instance of your mod that Forge uses.
    @Instance(value = MonsterBlocker.MODID)
    public static MonsterBlocker instance;
    
    @EventHandler
    public static void preInit(FMLPreInitializationEvent event) {
    	proxy.initRenderers();
    	proxy.initSounds();
    	
    	monsterBlocker = new MBBlock(3009);
    	GameRegistry.registerBlock(monsterBlocker, MonsterBlocker.mbBlock_name);
    	LanguageRegistry.addName(monsterBlocker, MonsterBlocker.mbBlock_name);
    	
    	GameRegistry.addRecipe(new ItemStack(MonsterBlocker.monsterBlocker, 1),
    			new Object[] {
    			"BIB",
    			"IGI",
    			"BIB",
    			'G', Block.glowStone, 'I', Item.ingotGold, 'B', Item.blazePowder
    			});
    	}
    
    @EventHandler
    public static void init ( FMLInitializationEvent event ) {
    	MinecraftForge.EVENT_BUS.register(new MBEventHandler());
    }
}

 

So if you could please help me one last time and get this mod running how it is supposed to, I'll be really grateful!

Link to comment
Share on other sites

Try denying the spawn unconditionally. Does this prevent all mobs from spawning?

 

I don't feel like setting up Java 7 to run 1.6.4, but I tried this in 1.8.9 and it did appear to prevent all mobs from spawning.

Please don't PM me to ask for help. Asking your question in a public thread preserves it for people who are having the same problem in the future.

Link to comment
Share on other sites

Well, that works. No big surprise. When I deny every spawn, then no mobs are spawning at all.

 

Furthermore, when I load a world where I placed my MB-Block, the system print "Spawn Denied" works. So I guess saving/loading is working correctly, too.

 

Could there be a problem when I compare Int and Float?

posBlock.x - RANGE_SIDE < event.x

Int - Int < Float

 

Or could there be a problem when getting the BlockList, so that sometimes it won't fetch the list correctly? I'll try to figure that out by using system messages.

 

Right now I detected the first problem: When I remove a MB-Block, it isn't removed from the list.

Link to comment
Share on other sites

If I set a range of 50 Blocks (in a cube-ish range around the block, not a sphere), each spawn will check 100*100*100 Blocks, which is 1 million blocks. And that is a bit too much... Storing the data to a small list and saving/loading the list is much more elegant, I think.

I too had been wondering about that, so I am glad to see your explanation. With such a long range, I can also see a potential difference in behavior with regards to unloaded chunks: A spawn-supressor remembered by the world will have its effect even if its chunk is "over the horizon". However, a ticking TE (or a block-seeking event handler) would only work while its chunk is loaded.

 

If these blocks ever became common enough to make an absolute world-list tedious, then you might opt for a synthesis of strategies (having the world aware of what suppressor blocks are currently loaded, but otherwise leaving them in their chunks).

The debugger is a powerful and necessary tool in any IDE, so learn how to use it. You'll be able to tell us more and get better help here if you investigate your runtime problems in the debugger before posting.

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.




×
×
  • Create New...

Important Information

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