Jump to content

Get Block from String?


Focamacho

Recommended Posts

How can I get a block from a String?

 

Example:

String config = "minecraft:water;minecraft:grass;biomesoplenty:gem_block:7;ore:logWood";

 

I tried:

	public static List<ItemStack> getBlockConfig(String config) {
		System.out.println(config);
		List<ItemStack> allBlocks = new ArrayList<Integer>();
		String[] blockList = config.split(";");
		if(!(blockList.length <= 0)) {
			for(String block : blockList) {
				if(block.startsWith("ore:")) {
					String[] split = block.split(":");
					allBlocks.addAll(getBlockListFromOredict(split[1]));
				} else {
					String[] split = block.split(":");
					if(split.length > 2) {
						ItemStack blockItem = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]), 1, Integer.parseInt(split[2]));
						allBlocks.add(blockItem);
					} else if(split.length == 2){
						ItemStack blockItem = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]));
						allBlocks.add(blockItem);
					}
				}
			}
		}
		return allBlocks;
	}	

 

But for blocks like water & flowers, it returns Air.

Tried using blockstate, but it don't work with oredict, because crashs in logWood using .getStateFromMeta.

 

Crash:

Quote

Caused by: java.lang.IllegalArgumentException: Cannot set property PropertyEnum{name=variant, clazz=class net.minecraft.block.BlockPlanks$EnumType, values=[acacia, dark_oak]} to oak on block minecraft:log2, it is not an allowed value
    at net.minecraft.block.state.BlockStateContainer$StateImplementation.withProperty(BlockStateContainer.java:233)
    at net.minecraft.block.BlockNewLog.getStateFromMeta(BlockNewLog.java:74)
    at com.focamacho.mysticaladaptations.util.BlockCheck.getStateListFromOredict(BlockCheck.java:190)
    at com.focamacho.mysticaladaptations.util.BlockCheck.getBlockConfig(BlockCheck.java:168)
    at com.focamacho.mysticaladaptations.util.BlockCheck.<clinit>(BlockCheck.java:22)
    ... 48 more


I need a list of blocks defined in the configuration file, for comparison with a Right-Clicked block.

Link to comment
Share on other sites

Well, there are two logs: "minecraft:log" and "minecraft:log2"

One of them is oak, spruce, jungle, and birch, the other is acacia and dark oak. You're trying to set log2 to oak, which is not an allowed variant.

  • Like 1

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

How should I do it?

	public static List<IBlockState> getBlockListFromOredict(String ore) {
		List<IBlockState> oreBlocks = new ArrayList<IBlockState>();
		List<ItemStack> oreItems = OreDictionary.getOres(ore);
		for(ItemStack item : oreItems) {
			oreBlocks.add(Block.getBlockFromItem(item.getItem()).getStateFromMeta(item.getMetadata());
		}
		return oreBlocks;
	}

 

Link to comment
Share on other sites

About Me

Spoiler

My Discord - Cadiboo#8887

My WebsiteCadiboo.github.io

My ModsCadiboo.github.io/projects

My TutorialsCadiboo.github.io/tutorials

Versions below 1.14.4 are no longer supported on this forum. Use the latest version to receive support.

When asking support remember to include all relevant log files (logs are found in .minecraft/logs/), code if applicable and screenshots if possible.

Only download mods from trusted sites like CurseForge (minecraft.curseforge.com). A list of bad sites can be found here, with more information available at stopmodreposts.org

Edit your own signature at www.minecraftforge.net/forum/settings/signature/ (Make sure to check its compatibility with the Dark Theme)

Link to comment
Share on other sites

This code only crashs with ore:logWood 

	public static List<IBlockState> getBlockListFromOredict(String ore) {
		List<IBlockState> oreBlocks = new ArrayList<IBlockState>();
		List<ItemStack> oreItems = OreDictionary.getOres(ore);
		for(ItemStack item : oreItems) {
			oreBlocks.add(Block.getBlockFromItem(item.getItem()).getStateFromMeta(item.getMetadata());
		}
		return oreBlocks;
	}
Link to comment
Share on other sites

I'm trying to get a list of blocks from a configuration file, using a String:

water_seeds = config.get(category, "water_seeds", "minecraft:water").getString();
wood_seeds = config.get(category, "wood_seeds", "ore:logWood").getString();

 

BlockCheck.java

public static final List<ItemStack> Water = getBlockConfig(ModConfig.water_seeds);
public static final List<ItemStack> Wood = getBlockConfig(ModConfig.wood_seeds);
  
public static List<ItemStack> getBlockConfig(String config) {
		List<ItemStack> allBlocks = new ArrayList<ItemStack>();
		String[] blockList = config.split(";");
		if(!(blockList.length <= 0)) {
			for(String block : blockList) {
				if(block.startsWith("ore:")) {
					String[] split = block.split(":");
					allBlocks.addAll(getBlockListFromOredict(split[1]));
				} else {
					String[] split = block.split(":");
					if(split.length > 2) {
						ItemStack blockA = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]), 1, Integer.parseInt(split[2]));
						allBlocks.add(blockA);
					} else if(split.length == 2){
						ItemStack blockA = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]));
						allBlocks.add(blockA);
					}
				}
			}
		}
		return allBlocks;
	}
	
	public static List<ItemStack> getBlockListFromOredict(String ore) {
		List<ItemStack> oreItems = OreDictionary.getOres(ore);
		return oreItems;
	}

 

But, when I create a ItemStack from things like "minecraft:water" or "minecraft:lava" it returns a tile.air:

Quote

[12:25:10] [main/INFO] [STDOUT]: [com.focamacho.mysticaladaptations.util.BlockCheck:getBlockConfig:186]: minecraft:water itemstack: 1xtile.air@0

[12:25:10] [main/INFO] [STDOUT]: [com.focamacho.mysticaladaptations.util.BlockCheck:getBlockConfig:186]: minecraft:lava itemstack: 1xtile.air@0:

 

And I need use the List<ItemStack> to compare a right-clicked block with the blocks in the list.

SeedExtractor.java

	       	........
			ItemStack blockItem = iblockstate.getBlock().getPickBlock(iblockstate, raytraceresult, worldIn, pos, player);
	       	if(player.canPlayerEdit(pos, raytraceresult.sideHit, itemstack)) {
				if(checkBlockAndTier(itemstack, blockItem, BlockCheck.Wood, Type.WOOD)) seed = returnSeedItem(Type.WOOD);
				else if(checkBlockAndTier(itemstack, blockItem, BlockCheck.Water, Type.WATER)) seed = returnSeedItem(Type.WATER);
				else if(checkBlockAndTier(itemstack, blockItem, BlockCheck.Fire, Type.FIRE)) seed = returnSeedItem(Type.FIRE);
			........


	public boolean checkBlockAndTier(ItemStack extractor, ItemStack block, List<ItemStack> blockList, CropType.Type seed) {
		if(checkBlock(block, blockList) && verifyTier(seed, extractor) && seed.isEnabled()) return true;
		else return false;
	}
      
	public boolean checkBlock(ItemStack block, List<ItemStack> blockList) {
		if(blockList == null || blockList.isEmpty()) return false;
		else {
			for(ItemStack b : blockList) {
				if(OreDictionary.itemMatches(b, block, true)) {
					return true;
				}
			}
		}
		return false;
	}

 

to result in this:

cF8Cjbz.gif

 

 

Edited by Focamacho
Link to comment
Share on other sites

I'm using 1.12.2. I found a way to fix my problem, I don't know if it's the best way, but it works.

I create a new List<Block> for each seed, and get his values using:

	public static List<Block> getBlockConfig2(String config) {
		List<Block> allBlocks = new ArrayList<Block>();
		String[] blockList = config.split(";");
		if(!(blockList.length <= 0)) {
			for(String block : blockList) {
				if(block.startsWith("ore:")) {
					//nothing
				} else {
					String[] split = block.split(":");
					if(split.length > 2) {
						ItemStack blockA = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]), 1, Integer.parseInt(split[2]));
						if(blockA.getItem() == Items.AIR) {
							Block blockB = Block.getBlockFromName(split[0] + ":" + split[1]);
							if(blockB != null) {
								allBlocks.add(blockB);
							}
						}
					} else if(split.length == 2){
						ItemStack blockA = new ItemStack(Item.getByNameOrId(split[0] + ":" + split[1]));
						if(blockA.getItem() == Items.AIR) {
							Block blockB = Block.getBlockFromName(split[0] + ":" + split[1]);
							if(blockB != null) {
								allBlocks.add(blockB);
							}
						}
					}
				}
			}
		}
		return allBlocks;
	}

 

https://github.com/Focamacho/MysticalAdaptations/commit/f4f233d76ce057ba79b10379c571cc62cfe18522

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

    • They were already updated, and just to double check I even did a cleanup and fresh update from that same page. I'm quite sure drivers are not the problem here. 
    • i tried downloading the drivers but it says no AMD graphics hardware has been detected    
    • Update your AMD/ATI drivers - get the drivers from their website - do not update via system  
    • As the title says i keep on crashing on forge 1.20.1 even without any mods downloaded, i have the latest drivers (nvidia) and vanilla minecraft works perfectly fine for me logs: https://pastebin.com/5UR01yG9
    • Hello everyone, I'm making this post to seek help for my modded block, It's a special block called FrozenBlock supposed to take the place of an old block, then after a set amount of ticks, it's supposed to revert its Block State, Entity, data... to the old block like this :  The problem I have is that the system breaks when handling multi blocks (I tried some fix but none of them worked) :  The bug I have identified is that the function "setOldBlockFields" in the item's "setFrozenBlock" function gets called once for the 1st block of multiblock getting frozen (as it should), but gets called a second time BEFORE creating the first FrozenBlock with the data of the 1st block, hence giving the same data to the two FrozenBlock :   Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=head] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@73681674 BlockEntityData : id:"minecraft:bed",x:3,y:-60,z:-6} Old Block Fields set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=3, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} Frozen Block Entity set BlockState : Block{minecraft:black_bed}[facing=east,occupied=false,part=foot] BlockPos{x=2, y=-60, z=-6} BlockEntity : net.minecraft.world.level.block.entity.BedBlockEntity@6d1aa3da BlockEntityData : {id:"minecraft:bed",x:2,y:-60,z:-6} here is the code inside my custom "freeze" item :    @Override     public @NotNull InteractionResult useOn(@NotNull UseOnContext pContext) {         if (!pContext.getLevel().isClientSide() && pContext.getHand() == InteractionHand.MAIN_HAND) {             BlockPos blockPos = pContext.getClickedPos();             BlockPos secondBlockPos = getMultiblockPos(blockPos, pContext.getLevel().getBlockState(blockPos));             if (secondBlockPos != null) {                 createFrozenBlock(pContext, secondBlockPos);             }             createFrozenBlock(pContext, blockPos);             return InteractionResult.SUCCESS;         }         return super.useOn(pContext);     }     public static void createFrozenBlock(UseOnContext pContext, BlockPos blockPos) {         BlockState oldState = pContext.getLevel().getBlockState(blockPos);         BlockEntity oldBlockEntity = oldState.hasBlockEntity() ? pContext.getLevel().getBlockEntity(blockPos) : null;         CompoundTag oldBlockEntityData = oldState.hasBlockEntity() ? oldBlockEntity.serializeNBT() : null;         if (oldBlockEntity != null) {             pContext.getLevel().removeBlockEntity(blockPos);         }         BlockState FrozenBlock = setFrozenBlock(oldState, oldBlockEntity, oldBlockEntityData);         pContext.getLevel().setBlockAndUpdate(blockPos, FrozenBlock);     }     public static BlockState setFrozenBlock(BlockState blockState, @Nullable BlockEntity blockEntity, @Nullable CompoundTag blockEntityData) {         BlockState FrozenBlock = BlockRegister.FROZEN_BLOCK.get().defaultBlockState();         ((FrozenBlock) FrozenBlock.getBlock()).setOldBlockFields(blockState, blockEntity, blockEntityData);         return FrozenBlock;     }  
  • Topics

×
×
  • Create New...

Important Information

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