All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.codingame.gameengine.module.entities.ContainerBasedEntity Maven / Gradle / Ivy

package com.codingame.gameengine.module.entities;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 
 *
 * @param 
 *            a subclass inheriting Entity, used in order to return this as a T instead of a ContainerBasedEntity.
 */
public abstract class ContainerBasedEntity> extends Entity {

    private Set> entities;

    ContainerBasedEntity() {
        super();

        entities = new HashSet<>();
    }

    /**
     * Separates the given entity from this ContainerBasedEntity.
     * 
     * @param entity
     *            the Entity to be removed from this ContainerBasedEntity, if it is part of it.
     */
    public void remove(Entity entity) {
        if (entity.parent == this) {
            entity.parent = null;
            entities.remove(entity);
            set("children", asString(entities), null);
        }
    }

    /**
     * Adds the given Entity instances to this ContainerBasedEntity.
     * 

* The entities will be displayed within a container controlled by this ContainerBasedEntity. * * @param entities * the Entity instances to be added to this ContainerBasedEntity. * @exception IllegalArgumentException * if at least one given Entity is already in a ContainerBasedEntity. */ public void add(Entity... entities) { Stream.of(entities).forEach(entity -> { if (entity.getParent().isPresent()) { throw new IllegalArgumentException( String.format( "Cannot add entity %d to container %d: it is already in container %d", entity.getId(), getId(), entity.getParent().get().getId() ) ); } this.entities.add(entity); entity.parent = this; }); set("children", asString(this.entities), null); } private String asString(Set> entities) { return entities.stream() .map(e -> String.valueOf(e.getId())) .collect(Collectors.joining(",")); } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy