Ir para conteúdo
  • 0

[Duvida] Como pego os blocos e salvo ?


Solitario

Pergunta

Ola galera, gostaria de saber como fazer tipo esse sistema:

Marco 2 locais e pego os blocos dentro dessas localizações e coloco para depois poder reconstruir os blocos salvos

Queria que ele salvasse tudo em um arraylist/hashmap para poder depois usar um for para pegar e colocar todos os blocos nos locais é que nem um regenblock ... alguém poderia me ajudar?

 

@Edit

fiz uma parte porem não esta funcionando corretamente

(ao clickar ele é cancelado porém ele não seta nem manda mensagem)

	@EventHandler
    public void onPlayerInteractEvent(PlayerInteractEvent event){
        Player player = event.getPlayer();
        if(event.getAction()==Action.LEFT_CLICK_BLOCK && selectmode.contains(player)){
            try{
            	pos1.put(player, event.getClickedBlock().getLocation());
                player.sendMessage("§bPos 1: " + event.getClickedBlock().getLocation());
                event.setCancelled(true);
            }catch(Exception e){
            	player.sendMessage(Main.Prefix + " §cOcorreu algum erro ao marcar o local!");
            }
        }
        if(event.getAction() == Action.RIGHT_CLICK_BLOCK && selectmode.contains(player)){
            try{
                pos2.put(player, event.getClickedBlock().getLocation());
                player.sendMessage("§bPos 2: " + event.getClickedBlock().getLocation());
                event.setCancelled(true);
            }catch(Exception e){
            	player.sendMessage(Main.Prefix + " §cOcorreu algum erro ao marcar o local!");
            }
        }
    }
Editado por Solitario
Link para o comentário
Compartilhar em outros sites

26 respostass a esta questão

Posts Recomendados

Cuboid.class (Acha no google aí)

 

new Cuboid(hashmap.get(player), hashmap2.get(player));

Tenho já +/- uma class porém no edit como diz parece estar bugado ao escolher os locais

 

Aqui o que eu tou usando para salvar:

    public void SalvarArea(Player player, Location l1, Location l2){
        int mix, max, miy, may, miz, maz;
        int blockCounter = 0;
        if(l1.getBlockX() < l2.getBlockX()){
            mix = l1.getBlockX();
            max = l2.getBlockX();
        }else{
            mix = l2.getBlockX();
            max = l1.getBlockX();
        }
        if(l1.getBlockY() < l2.getBlockY()){
            miy = l1.getBlockY();
            may = l2.getBlockY();
        }else{
            miy = l2.getBlockY();
            may = l1.getBlockY();
        }
        if(l1.getBlockZ() < l2.getBlockZ()){
            miz = l1.getBlockZ();
            maz = l2.getBlockZ();
        }else{
            miz = l2.getBlockZ();
            maz = l1.getBlockZ();
        }
        for(int x = mix; x<=max;x++){
            for(int y = miy; y<=may;y++){
                for(int z = miz; z<=maz;z++){
                    Location location = new Location(player.getWorld(), x,y,z);
                    base.put(location, location.getBlock().getType());
                    blockCounter++;
		            }
		           
		        }
		       
		}
        if(pos1.get(player) != null && pos2.get(player) != null){
	        pos1.remove(player);
	        pos2.remove(player);
        }
        player.sendMessage(Main.Prefix + blockCounter + " Blocos salvos!");
    }
Editado por Solitario
Link para o comentário
Compartilhar em outros sites

crie essa classe no seu plugin

   public void SalvarArea(Player player, Location l1, Location l2){

        if(!l1.getWorld().equals(l2.getWorld())){ // evitar que o cuboid lance essa excepção IllegalArgumentException
            player.sendMessage("Locations must be on the same world");
            return;
        }

        Cuboid cuboId = new Cuboid(l1, l2);

        List<Block> list = cuboId.getBlocks();

        for(Block block : list){
            base.put(block.getLocation(), block.getType());
        }

        int blockCounter = list.size()

        if(pos1.get(player) != null && pos2.get(player) != null){
	        pos1.remove(player);
	        pos2.remove(player);
        }

        player.sendMessage(Main.Prefix + blockCounter + " Blocos salvos!");

    }
Editado por zAth
Link para o comentário
Compartilhar em outros sites

 

crie essa classe no seu plugin

   public void SalvarArea(Player player, Location l1, Location l2){

        if(!l1.getWorld().equals(l2.getWorld())){ // evitar que o cuboid lance essa excepção IllegalArgumentException
            player.sendMessage("Locations must be on the same world");
            return;
        }

        Cuboid cuboId = new Cuboid(l1, l2);

        List<Block> list = cuboId.getBlocks();

        for(Block block : list){
            base.put(block.getLocation(), block.getType());
        }

        int blockCounter = list.size()

        if(pos1.get(player) != null && pos2.get(player) != null){
	        pos1.remove(player);
	        pos2.remove(player);
        }

        player.sendMessage(Main.Prefix + blockCounter + " Blocos salvos!");

    }

Não adianta eu ter esse code ;-; o select mode não esta funcional ;-;

Link para o comentário
Compartilhar em outros sites

Código :

	public static List<Location> getLoc(Location loc1, Location loc2) {
		
		double xMin = Math.min(loc1.getX(), loc2.getX());
		double zMin = Math.min(loc1.getZ(), loc2.getZ());
		double yMin = Math.min(loc1.getY(), loc2.getY());
		
		double xMax = Math.max(loc1.getX(), loc2.getX());
		double zMax = Math.max(loc1.getZ(), loc2.getZ());
		double yMax = Math.max(loc1.getY(), loc2.getY());
		
		List<Location> locs = new ArrayList<>();

		for(int x = (int) xMin; x <= xMax; x ++){
			for(int y = (int) yMin; y <= yMax; y ++){
				for(int z = (int) zMin; z <= zMax; z ++){
					locs.add(new Location(loc1.getWorld(), x, y, z));
				}
			}
		}
		return locs;
	}

Modo de uso :

				for(Location loc : getLoc(loc1_Minerador, loc2_Minerador)){
					loc.getBlock().setType(Material.STONE);
			
				}

Se quiser otimizar o código,fica a vontade;

Link para o comentário
Compartilhar em outros sites

que select mode rapaiz

para setar do local x até local y '-'

 

que nem o worldedit seta

 

 

 

@Edit

fiz uma parte porem não esta funcionando corretamente

(ao clickar ele é cancelado porém ele não seta nem manda mensagem)

	@EventHandler
    public void onPlayerInteractEvent(PlayerInteractEvent event){
        Player player = event.getPlayer();
        if(event.getAction()==Action.LEFT_CLICK_BLOCK && selectmode.contains(player)){
            try{
            	pos1.put(player, event.getClickedBlock().getLocation());
                player.sendMessage("§bPos 1: " + event.getClickedBlock().getLocation());
                event.setCancelled(true);
            }catch(Exception e){
            	player.sendMessage(Main.Prefix + " §cOcorreu algum erro ao marcar o local!");
            }
        }
        if(event.getAction() == Action.RIGHT_CLICK_BLOCK && selectmode.contains(player)){
            try{
                pos2.put(player, event.getClickedBlock().getLocation());
                player.sendMessage("§bPos 2: " + event.getClickedBlock().getLocation());
                event.setCancelled(true);
            }catch(Exception e){
            	player.sendMessage(Main.Prefix + " §cOcorreu algum erro ao marcar o local!");
            }
        }
    }

Esse é o select mode '-' ele não deixa quebrar porém não seta ;-;

 

 

Código :

	public static List<Location> getLoc(Location loc1, Location loc2) {
		
		double xMin = Math.min(loc1.getX(), loc2.getX());
		double zMin = Math.min(loc1.getZ(), loc2.getZ());
		double yMin = Math.min(loc1.getY(), loc2.getY());
		
		double xMax = Math.max(loc1.getX(), loc2.getX());
		double zMax = Math.max(loc1.getZ(), loc2.getZ());
		double yMax = Math.max(loc1.getY(), loc2.getY());
		
		List<Location> locs = new ArrayList<>();

		for(int x = (int) xMin; x <= xMax; x ++){
			for(int y = (int) yMin; y <= yMax; y ++){
				for(int z = (int) zMin; z <= zMax; z ++){
					locs.add(new Location(loc1.getWorld(), x, y, z));
				}
			}
		}
		return locs;
	}

Modo de uso :

				for(Location loc : getLoc(loc1_Minerador, loc2_Minerador)){
					loc.getBlock().setType(Material.STONE);
			
				}

Se quiser otimizar o código,fica a vontade;

Interessante ... mais estou com problemas no select mode (codigo acima)

Link para o comentário
Compartilhar em outros sites

para setar do local x até local y '-'

 

que nem o worldedit seta

 

 

Esse é o select mode '-' ele não deixa quebrar porém não seta ;-;

 

 

Interessante ... mais estou com problemas no select mode (codigo acima)

HashMap<String,Location> locs = new Hashmap<>();
 
if (e.getAction() == Action.LEFT_CLICK_BLOCK && p.getItemInHand().getType() == Material.GOLD_NUGGET) {
p.sendMessage("§aVocê setou a primeira posição.");
e.setCancelled(true);
locs.put("loc1",e.getclickedblock.getlocation);
}
 
if (e.getAction() == Action.RIGHT_CLICK_BLOCK && p.getItemInHand().getType() == Material.GOLD_NUGGET) {
p.sendMessage("§aVocê setou a primeira posição.");
e.setCancelled(true);
locs.put("loc1",e.getclickedblock.getlocation);
}
 
Ai você pode usar um o jeito que quiser.{Runnable,Delay,sei lá eu}
 
@Eventhandler
public void j(PlayerJoinEvent e){
 for(Location loc : getLoc(locs.get("loc1"), locs.get("loc2")){
loc.getBlock().setType(Material.STONE);
 
}
}
Editado por Darwin
Link para o comentário
Compartilhar em outros sites

 

HashMap<String,Location> locs = new Hashmap<>();
 
if (e.getAction() == Action.LEFT_CLICK_BLOCK && p.getItemInHand().getType() == Material.GOLD_NUGGET) {
p.sendMessage("§aVocê setou a primeira posição.");
e.setCancelled(true);
locs.put("loc1",e.getclickedblock.getlocation);
}
 
if (e.getAction() == Action.RIGHT_CLICK_BLOCK && p.getItemInHand().getType() == Material.GOLD_NUGGET) {
p.sendMessage("§aVocê setou a primeira posição.");
e.setCancelled(true);
locs.put("loc1",e.getclickedblock.getlocation);
}
 
Ai você pode usar um o jeito que quiser.{Runnable,Delay,sei lá eu}
 
@Eventhandler
public void j(PlayerJoinEvent e){
 for(Location loc : getLoc(locs.get("loc1"), locs.get("loc2")){
loc.getBlock().setType(Material.STONE);
 
}
}

 

    HashMap<Player, Location> pos1 = new HashMap<Player, Location>();
    HashMap<Player, Location> pos2 = new HashMap<Player, Location>();
	@EventHandler
    public void onPlayerInteractEvent(PlayerInteractEvent event){
        Player player = event.getPlayer();
        if(event.getAction()==Action.LEFT_CLICK_BLOCK && selectmode.contains(player) && player.getItemInHand().getType() == Material.GOLD_NUGGET){
           pos1.put(player, event.getClickedBlock().getLocation());
           player.sendMessage(Main.Prefix + "§bPos 1: " + event.getClickedBlock().getLocation());
           event.setCancelled(true);
        if(event.getAction() == Action.RIGHT_CLICK_BLOCK && selectmode.contains(player) && player.getItemInHand().getType() == Material.GOLD_NUGGET){
            pos2.put(player, event.getClickedBlock().getLocation());
            player.sendMessage(Main.Prefix + "§bPos 2: " + event.getClickedBlock().getLocation());
            event.setCancelled(true);
        }
       }
	}

Não quer funcionar

Editado por Solitario
Link para o comentário
Compartilhar em outros sites

HashMap<Player, Location> pos1 = new HashMap<Player, Location>();    HashMap<Player, Location> pos2 = new HashMap<Player, Location>();	@EventHandler    public void onPlayerInteractEvent(PlayerInteractEvent event){        Player player = event.getPlayer();        if(event.getAction()==Action.LEFT_CLICK_BLOCK && selectmode.contains(player) && player.getItemInHand().getType() == Material.GOLD_NUGGET){           pos1.put(player, event.getClickedBlock().getLocation());           player.sendMessage(Main.Prefix + "§bPos 1: " + event.getClickedBlock().getLocation());           event.setCancelled(true);        if(event.getAction() == Action.RIGHT_CLICK_BLOCK && selectmode.contains(player) && player.getItemInHand().getType() == Material.GOLD_NUGGET){            pos2.put(player, event.getClickedBlock().getLocation());            player.sendMessage(Main.Prefix + "§bPos 2: " + event.getClickedBlock().getLocation());            event.setCancelled(true);        }       }	}
Não quer funcionar

HashMap<Player, Location> pos1 = new HashMap<Player, Location>(); HashMap<Player, Location> pos2 = new HashMap<Player, Location>();
em vez de Player salva o nome dele(Isso não vai resolve só to falando porque acho melhor)

 

uma coisa verifica se ele ta mesmo clicando em um bloco 3 verifica se ele esta mesmo no selectmode 3 verifica se o item que ele ta segurando esta certo.

pois se ele não passa dessa parte pode ser alguma coisa assim

Editado por TzMarcio
Link para o comentário
Compartilhar em outros sites

HashMap<Player, Location> pos1 = new HashMap<Player, Location>(); HashMap<Player, Location> pos2 = new HashMap<Player, Location>();
em vez de Player salva o nome dele(Isso não vai resolve só to falando porque acho melhor)

 

uma coisa verifica se ele ta mesmo clicando em um bloco 3 verifica se ele esta mesmo no selectmode 3 verifica se o item que ele ta segurando esta certo.

pois se ele não passa dessa parte pode ser alguma coisa assim

 

O problema que tou vendo só ta no verificar se ele ta no selectmode

(Mudei para salvar o nome)

if(event.getAction() == Action.LEFT_CLICK_BLOCK  && selectmode.contains(player.getName())){
}
Link para o comentário
Compartilhar em outros sites

 

crie essa classe no seu plugin

   public void SalvarArea(Player player, Location l1, Location l2){

        if(!l1.getWorld().equals(l2.getWorld())){ // evitar que o cuboid lance essa excepção IllegalArgumentException
            player.sendMessage("Locations must be on the same world");
            return;
        }

        Cuboid cuboId = new Cuboid(l1, l2);

        List<Block> list = cuboId.getBlocks();

        for(Block block : list){
            base.put(block.getLocation(), block.getType());
        }

        int blockCounter = list.size()

        if(pos1.get(player) != null && pos2.get(player) != null){
	        pos1.remove(player);
	        pos2.remove(player);
        }

        player.sendMessage(Main.Prefix + blockCounter + " Blocos salvos!");

    }

se a pessoa quisesse colocar 1 bloco então daria erro ?

 

OBS: O code que eu coloquei:

    public void SalvarArea(Player player, Location l1, Location l2){
        int mix, max, miy, may, miz, maz;
        int blockCounter = 0;
        if(l1.getBlockX() < l2.getBlockX()){
            mix = l1.getBlockX();
            max = l2.getBlockX();
        }else{
            mix = l2.getBlockX();
            max = l1.getBlockX();
        }
        if(l1.getBlockY() < l2.getBlockY()){
            miy = l1.getBlockY();
            may = l2.getBlockY();
        }else{
            miy = l2.getBlockY();
            may = l1.getBlockY();
        }
        if(l1.getBlockZ() < l2.getBlockZ()){
            miz = l1.getBlockZ();
            maz = l2.getBlockZ();
        }else{
            miz = l2.getBlockZ();
            maz = l1.getBlockZ();
        }
        for(int x = mix; x<=max;x++){
            for(int y = miy; y<=may;y++){
                for(int z = miz; z<=maz;z++){
                    Location location = new Location(player.getWorld(), x,y,z);
                    base.put(location, location.getBlock().getType());
                    blockCounter++;
		            }
		           
		        }
		       
		}
        if(pos1.get(player) != null && pos2.get(player) != null){
	        pos1.remove(player);
	        pos2.remove(player);
        }
        player.sendMessage(Main.Prefix + blockCounter + " Blocos salvos!");
    }

esta com um problema de salvar o bloco tipo slab (Ele salva outro tipo)

ou na lã e acho que no vidro também

Link para o comentário
Compartilhar em outros sites

Você tem que colocar o data/durability do bloco, para os normais coloque 0.

Tou usando uma ArrayList simples de apenas <Material, Location> como iria ficar (É minha primeira vez fzd coisas desse tipo e.e (salvando blocos ...))

Link para o comentário
Compartilhar em outros sites

Tou usando uma ArrayList simples de apenas <Material, Location> como iria ficar (É minha primeira vez fzd coisas desse tipo e.e (salvando blocos ...))

porque voce nao usa a map assim: <Location, Block>

Editado por jeta
Link para o comentário
Compartilhar em outros sites

Tou usando uma ArrayList simples de apenas <Material, Location> como iria ficar (É minha primeira vez fzd coisas desse tipo e.e (salvando blocos ...))

o simples é usar <Block, Location> logo como o @jeta falou, depois verifica o material com Block.getType() e a data com Block.getData().getData().

Você deve estar apenas verificando o material, já que é a única coisa que você guarda, mas as lãs, vidros, etc variam dependendo da data, que alteram a cor do bloco, então você tem que verificar o id/material e a data (eu pessoalmente prefiro verificar o id, o material em alguns blocos tem o nome diferente no bukkit do nome do mine).

 

um bloco tem um monte de atributos, mesmo assim guardar muitos blocos em uma map acho que não lagaria.. senão você teria que fazer alguma gambiarra e mudar o <Block, Location> para <String, Location> onde o string seria "id:data", assim não precisa guardar os atributos que você não quer do bloco na map. Mas acho que <Block, Location> não laga mesmo.. o certo seria <Block, Location>.

 

Esse testamento enorme merece laike nao?

Editado por zAth
Link para o comentário
Compartilhar em outros sites

 

Tou usando uma ArrayList simples de apenas <Material, Location> como iria ficar (É minha primeira vez fzd coisas desse tipo e.e (salvando blocos ...))

 

No lugar do material, use itemstack. O itemstack tu pode alterar a data

Link para o comentário
Compartilhar em outros sites

o simples é usar <Block, Location> logo como o @jeta falou, depois verifica o material com Block.getType() e a data com Block.getData().getData().

Você deve estar apenas verificando o material, já que é a única coisa que você guarda, mas as lãs, vidros, etc variam dependendo da data, que alteram a cor do bloco, então você tem que verificar o id/material e a data (eu pessoalmente prefiro verificar o id, o material em alguns blocos tem o nome diferente no bukkit do nome do mine).

 

um bloco tem um monte de atributos, mesmo assim guardar muitos blocos em uma map acho que não lagaria.. senão você teria que fazer alguma gambiarra e mudar o <Block, Location> para <String, Location> onde o string seria "id:data", assim não precisa guardar os atributos que você não quer do bloco na map. Mas acho que <Block, Location> não laga mesmo.. o certo seria <Block, Location>.

 

Esse testamento enorme merece laike nao?

ok ... mais para colocar o bloco seria como para especificar (Citei que uso arraylist só que errei é hashmap)

for(Location bloco : base.keySet()){
    Main.instance.getServer().getWorld(bloco.getWorld().getName()).getBlockAt(bloco).setTypeId(base.get(bloco).getType().getId());
}

não ta funcionando e.e ... como ficaria para colocar o bloco ? (To salvando via <location, block>)

No lugar do material, use itemstack. O itemstack tu pode alterar a data

itemstack não é apenas para item ? (e.e tentei não apareceu nada sobre itemstack)

Link para o comentário
Compartilhar em outros sites

ok ... mais para colocar o bloco seria como para especificar (Citei que uso arraylist só que errei é hashmap)

for(Location bloco : base.keySet()){
    Main.instance.getServer().getWorld(bloco.getWorld().getName()).getBlockAt(bloco).setTypeId(base.get(bloco).getType().getId());
}

não ta funcionando e.e ... como ficaria para colocar o bloco ? (To salvando via <location, block>)

itemstack não é apenas para item ? (e.e tentei não apareceu nada sobre itemstack)

Você pode pegar o material e criar o ItemStack, e depois pode pegar o material pelo ItemStack, ou pode usar o Block.

Link para o comentário
Compartilhar em outros sites

Você pode pegar o material e criar o ItemStack, e depois pode pegar o material pelo ItemStack, ou pode usar o Block.

n tou conseguindo colocar os blocos '-' via Block

achei um pouco na internet sobre o bloco em ItemStack porém não encontrei como pego o (short)

Link para o comentário
Compartilhar em outros sites

Visitante
Este tópico está impedido de receber novos posts.
×
×
  • Criar Novo...