Example usage for com.badlogic.gdx.utils Array indexOf

List of usage examples for com.badlogic.gdx.utils Array indexOf

Introduction

In this page you can find the example usage for com.badlogic.gdx.utils Array indexOf.

Prototype

public int indexOf(T value, boolean identity) 

Source Link

Document

Returns an index of first occurrence of value in array or -1 if no such value exists

Usage

From source file:com.ahsgaming.valleyofbones.ai.AIPlayer.java

License:Apache License

@Override
public void update(GameController controller, float delta) {
    super.update(controller, delta);

    if (genome == null) {
        Json json = new Json();
        genome = json.fromJson(GenomicAI.class, Gdx.files.internal("ai/xjix3xuv").readString());
        Gdx.app.log(LOG, "Loaded ai: " + genome.id);
    }//from   w ww .j a  v  a2s .c  om

    if (controller.getCurrentPlayer().getPlayerId() == getPlayerId()) {
        timer -= delta;
        if (timer < 0) {
            timer = countdown;

            if (VOBGame.DEBUG_AI)
                Gdx.app.log(LOG, "start...");
            // first, create the visibility matrix
            if (visibilityMatrix == null) {
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create visibility matrix");
                visibilityMatrix = createVisibilityMatrix(controller.getMap(),
                        controller.getUnitsByPlayerId(getPlayerId()));
                return;
            }

            // next, create the value matrix and threat matrix
            if (valueMatrix == null) {
                Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>();
                for (AbstractUnit unit : controller.getUnits()) {
                    if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y
                            * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)]) {
                        visibleUnits.add(unit);
                    }
                }
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create value/threat matrices");
                valueMatrix = createUnitMatrix(controller.getMap(), visibleUnits, false);
                threatMatrix = createUnitMatrix(controller.getMap(), visibleUnits, true);
                return;
            }

            // create goalMatrix (based on knowledge of the map)
            if (goalMatrix == null) {
                if (VOBGame.DEBUG_AI)
                    Gdx.app.log(LOG, "...create goal matrix");
                goalMatrix = createGoalMatrix(controller.getMap(), controller.getUnits());

                if (VOBGame.DEBUG_AI) {
                    DecimalFormat formatter = new DecimalFormat("00.0");
                    for (int y = 0; y < controller.getMap().getHeight(); y++) {
                        if (y % 2 == 1) {
                            System.out.print("   ");
                        }
                        for (int x = 0; x < controller.getMap().getWidth(); x++) {
                            int i = y * controller.getMap().getWidth() + x;
                            float sum = (visibilityMatrix[i] ? goalMatrix[i] + valueMatrix[i] + threatMatrix[i]
                                    : 0);
                            System.out.print((sum >= 0 ? " " : "") + formatter.format(sum) + " ");
                        }
                        System.out.println("\n");
                    }
                }

                return;
            }

            // move units
            for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) {
                if (unit.getData().getMovesLeft() < 1)
                    continue;
                Vector2[] adjacent = HexMap.getAdjacent((int) unit.getView().getBoardPosition().x,
                        (int) unit.getView().getBoardPosition().y);
                Vector2 finalPos = new Vector2(unit.getView().getBoardPosition());
                float finalSum = goalMatrix[(int) finalPos.y * controller.getMap().getWidth()
                        + (int) finalPos.x]
                        + valueMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x]
                        + threatMatrix[(int) finalPos.y * controller.getMap().getWidth() + (int) finalPos.x];
                for (Vector2 v : adjacent) {
                    if (v.x < 0 || v.x >= controller.getMap().getWidth() || v.y < 0
                            || v.y >= controller.getMap().getHeight())
                        continue;
                    float curSum = goalMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x]
                            + valueMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x]
                            + threatMatrix[(int) v.y * controller.getMap().getWidth() + (int) v.x];
                    if (curSum > finalSum && controller.isBoardPosEmpty(v)) {
                        finalPos.set(v);
                        finalSum = curSum;
                    }
                }
                if (finalPos.x != unit.getView().getBoardPosition().x
                        || finalPos.y != unit.getView().getBoardPosition().y) {
                    // move!
                    Move mv = new Move();
                    mv.owner = getPlayerId();
                    mv.turn = controller.getGameTurn();
                    mv.unit = unit.getId();
                    mv.toLocation = finalPos;
                    netController.sendAICommand(mv);
                    valueMatrix = null;
                    threatMatrix = null;
                    return;
                }
            }

            // attack
            Array<AbstractUnit> visibleUnits = new Array<AbstractUnit>();
            Array<AbstractUnit> friendlyUnits = controller.getUnitsByPlayerId(this.getPlayerId());
            for (AbstractUnit unit : controller.getUnits()) {
                if (unit.getOwner() == this || unit.getOwner() == null)
                    continue;
                if (visibilityMatrix[(int) (unit.getView().getBoardPosition().y * controller.getMap().getWidth()
                        + unit.getView().getBoardPosition().x)] && !unit.getData().isInvisible()
                        || controller.getMap().detectorCanSee(this, friendlyUnits,
                                unit.getView().getBoardPosition())) {
                    visibleUnits.add(unit);
                }
            }
            for (AbstractUnit unit : controller.getUnitsByPlayerId(getPlayerId())) {
                if (unit.getData().getAttacksLeft() < 1)
                    continue;
                AbstractUnit toAttack = null;
                float toAttackThreat = 0;
                for (AbstractUnit o : visibleUnits) {
                    float thisThreat = threatMatrix[controller.getMap().getWidth()
                            * (int) o.getView().getBoardPosition().y + (int) o.getView().getBoardPosition().x];
                    if (controller.getUnitManager().canAttack(unit, o)
                            && (toAttack == null || thisThreat > toAttackThreat)) {
                        toAttack = o;
                        toAttackThreat = thisThreat;
                    }
                }
                if (toAttack != null) {
                    //                        Gdx.app.log(LOG + "$attack", String.format("%s --> %s", unit.getProtoId(), toAttack.getProtoId()));
                    Attack at = new Attack();
                    at.owner = getPlayerId();
                    at.turn = controller.getGameTurn();
                    at.unit = unit.getId();
                    at.target = toAttack.getId();
                    netController.sendAICommand(at);
                    valueMatrix = null;
                    threatMatrix = null;
                    return;
                }
            }

            // build units // TODO build other than marines (ie: implement chromosome 11)

            int positionToBuild = -1;
            for (int i = 0; i < valueMatrix.length; i++) {
                if (visibilityMatrix[i]) {
                    float sum = threatMatrix[i] + valueMatrix[i] + goalMatrix[i];

                    if ((positionToBuild == -1 || valueMatrix[positionToBuild] + valueMatrix[positionToBuild]
                            + goalMatrix[positionToBuild] < sum)) {
                        //                                Gdx.app.log(LOG, i + ":" + controller.isBoardPosEmpty(
                        //                                        i % controller.getMap().getWidth(),
                        //                                        i / controller.getMap().getWidth()));
                        if (controller.isBoardPosEmpty(i % controller.getMap().getWidth(),
                                i / controller.getMap().getWidth())) {
                            positionToBuild = i;
                        }
                    }
                }
            }
            Prototypes.JsonProto unitToBuild = null;

            if (positionToBuild >= 0) {
                Vector2 buildPosition = new Vector2(positionToBuild % controller.getMap().getWidth(),
                        positionToBuild / controller.getMap().getWidth());
                Array<String> protoIds = new Array<String>();
                HashMap<String, Float> buildScores = new HashMap<String, Float>();
                for (Prototypes.JsonProto proto : Prototypes.getAll(getRace())) {
                    protoIds.add(proto.id);
                    if (proto.cost > 0) {
                        buildScores.put(proto.id, 0f);
                    }
                }

                for (AbstractUnit unit : controller.getUnits()) {
                    if (unit.getOwner() == this || !visibilityMatrix[(int) (unit.getView().getBoardPosition().y
                            * controller.getMap().getWidth() + unit.getView().getBoardPosition().x)])
                        continue;

                    int unitIndex = protoIds.indexOf(unit.getProto().id, false);
                    int unitDistance = controller.getMap().getMapDist(unit.getView().getBoardPosition(),
                            buildPosition);
                    for (String key : buildScores.keySet()) {
                        buildScores.put(key, buildScores.get(key)
                                + ((Array<Float>) genome.chromosomes.get(10).genes.get(key)).get(unitIndex)
                                        / unitDistance);
                    }
                }

                String maxScore = null;
                float maxBuildScore = 0;
                while (unitToBuild == null && buildScores.keySet().size() > 0) {
                    for (String id : buildScores.keySet()) {
                        if (maxScore == null || buildScores.get(id) > buildScores.get(maxScore)) {
                            maxScore = id;
                            if (buildScores.get(id) > maxBuildScore) {
                                maxBuildScore = buildScores.get(id);
                            }
                        }
                    }

                    if (!maxScore.equals("saboteur") && buildScores.get(maxScore) > 0
                            && buildScores.get(maxScore) >= maxBuildScore
                                    - (Float) genome.chromosomes.get(10).genes.get("wait")
                            && getBankMoney() >= Prototypes.getProto(getRace(), maxScore).cost) {
                        unitToBuild = Prototypes.getProto(getRace(), maxScore);
                    } else {
                        buildScores.remove(maxScore);
                        maxScore = null;
                    }

                }
            }

            if (unitToBuild != null) {
                Build build = new Build();
                build.owner = getPlayerId();
                build.turn = controller.getGameTurn();
                build.building = unitToBuild.id;
                build.location = new Vector2(positionToBuild % controller.getMap().getWidth(),
                        positionToBuild / controller.getMap().getWidth());
                netController.sendAICommand(build);
                valueMatrix = null;
                return;
            }

            EndTurn et = new EndTurn();
            et.owner = getPlayerId();
            et.turn = controller.getGameTurn();
            netController.sendAICommand(et);
        }
    } else {
        visibilityMatrix = null;
        valueMatrix = null;
        threatMatrix = null;
        goalMatrix = null;
    }

}

From source file:com.gdx.extension.ui.list.AdvancedList.java

License:Apache License

/**
 * Remove a {@link ListRow} from this list.
 * Next {@link ListRow} will be set to selected. If there are no more {@link ListRow} next then it select the previous.
 * /*from  w w  w  .j  ava 2  s .  co m*/
 * @param item the {@link ListRow} to remove
 * @throws IllegalArgumentException if item is null
 */
public void removeItem(T item) {
    if (item == null)
        throw new IllegalArgumentException("item cannot be null.");

    Array<T> _items = listRowGroup.getActors();
    int _index = _items.indexOf(item, true);

    listRowGroup.remove(item);
    item.remove();

    // Select an item near the one removed
    if (_items.size > 1) {
        if (_index < _items.size) {
            Gdx.app.debug("Select", "Last index");
            setSelected(_index);
        } else {
            Gdx.app.debug("Select", "Previous index");
            setSelected(_index - 1);
        }
    }
}

From source file:com.kotcrab.vis.editor.module.scene.entitymanipulator.tool.PolygonTool.java

License:Apache License

private boolean checkCurrentVertexIntersection() {
    Array<Vector2> vertices = component.vertices;
    int index = vertices.indexOf(overVertex, true);
    if (index == -1)
        return true;

    Edge firstEdge;/*from w w w  .  jav  a  2s  . com*/
    Edge secondEdge;

    if (index == 0)
        firstEdge = new Edge(vertices.peek(), overVertex);
    else
        firstEdge = new Edge(vertices.get(index - 1), overVertex);

    if (index == vertices.size - 1)
        secondEdge = new Edge(vertices.first(), overVertex);
    else
        secondEdge = new Edge(vertices.get(index + 1), overVertex);

    Array<Edge> polygonEdges = new Array<>();

    for (int i = 0; i < vertices.size - 1; i++) {
        polygonEdges.add(new Edge(vertices.get(i), vertices.get(i + 1)));
    }

    polygonEdges.add(new Edge(vertices.peek(), vertices.first()));

    for (Edge edge : polygonEdges) {
        if (edge.epsilonEquals(firstEdge, 0) || edge.epsilonEquals(secondEdge, 0))
            continue;

        if (polygonLineIntersection(firstEdge.start, firstEdge.end, edge.start, edge.end))
            return true;

        if (polygonLineIntersection(secondEdge.start, secondEdge.end, edge.start, edge.end))
            return true;
    }

    return false;
}

From source file:com.ridiculousRPG.GameServiceProvider.java

License:Apache License

private <T> void shiftPos(Array<T> array, T service, T ref, int offset) {
    array.removeValue(service, true);//from www .ja  v  a  2s  .  c o m
    array.insert(array.indexOf(ref, true) + offset, service);
}

From source file:es.eucm.ead.editor.control.actions.model.Reorder.java

License:Open Source License

@Override
public Command perform(Object... args) {
    Object parent = args[0];/* w w w .  j av  a  2 s  .c  o m*/
    Array list = (Array) args[1];
    Object elementToBeReordered = args[2];
    Integer destinyPosition = (Integer) args[3];
    boolean relative = args.length == 5 && args[4] instanceof Boolean ? (Boolean) args[4] : false;
    int sourcePosition = list.indexOf(elementToBeReordered, false);

    if (relative) {
        destinyPosition += sourcePosition;
    }

    if (destinyPosition < 0) {
        destinyPosition = 0;
    } else if (destinyPosition >= list.size) {
        destinyPosition = list.size - 1;
    }

    if (sourcePosition != destinyPosition) {
        return new ReorderInListCommand(parent, list, elementToBeReordered, destinyPosition);
    }
    return null;
}

From source file:es.eucm.ead.editor.control.actions.model.ReplaceEntity.java

License:Open Source License

@Override
public CompositeCommand perform(Object... args) {
    CompositeCommand compositeCommand = new CompositeCommand();
    ModelEntity parent = (ModelEntity) args[0];
    ModelEntity current = (ModelEntity) args[1];
    ModelEntity newEntity = (ModelEntity) args[2];

    Array<ModelEntity> children = parent.getChildren();
    int indexOf = children.indexOf(current, true);
    compositeCommand.addCommand(new RemoveFromListCommand(parent, children, current));
    compositeCommand.addCommand(new AddToListCommand(parent, children, newEntity, indexOf));

    return compositeCommand;
}

From source file:kyle.game.besiege.party.Party.java

License:Open Source License

private Array<Array<Soldier>> getConsol(Array<Soldier> arrSoldier) {
    // first thing: sort arrSoldier by name
    arrSoldier.sort();//  w ww.  java2s. co  m

    Array<String> names = new Array<String>();
    Array<Array<Soldier>> consol = new Array<Array<Soldier>>();
    for (Soldier s : arrSoldier) {
        if (!names.contains(s.name, false)) {
            names.add(s.name);
            Array<Soldier> type = new Array<Soldier>();
            type.add(s);
            consol.add(type);
        } else {
            consol.get(names.indexOf(s.name, false)).add(s);
        }
    }
    return consol;
}