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

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

Introduction

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

Prototype

public T pop() 

Source Link

Document

Removes and returns the last item.

Usage

From source file:com.austinerb.project0.engine.JsonReader.java

License:Apache License

public JsonValue parse(char[] data, int offset, int length) {
    int cs, p = offset, pe = length, eof = pe, top = 0;
    int[] stack = new int[4];

    int s = 0;//  ww w .j a v  a 2 s. c  om
    Array<String> names = new Array(8);
    boolean needsUnescape = false, stringIsName = false, stringIsUnquoted = false;
    RuntimeException parseRuntimeEx = null;

    boolean debug = false;
    if (debug)
        System.out.println();

    try {

        // line 3 "JsonReader.java"
        {
            cs = json_start;
            top = 0;
        }

        // line 8 "JsonReader.java"
        {
            int _klen;
            int _trans = 0;
            int _acts;
            int _nacts;
            int _keys;
            int _goto_targ = 0;

            _goto: while (true) {
                switch (_goto_targ) {
                case 0:
                    if (p == pe) {
                        _goto_targ = 4;
                        continue _goto;
                    }
                    if (cs == 0) {
                        _goto_targ = 5;
                        continue _goto;
                    }
                case 1:
                    _match: do {
                        _keys = _json_key_offsets[cs];
                        _trans = _json_index_offsets[cs];
                        _klen = _json_single_lengths[cs];
                        if (_klen > 0) {
                            int _lower = _keys;
                            int _mid;
                            int _upper = _keys + _klen - 1;
                            while (true) {
                                if (_upper < _lower)
                                    break;

                                _mid = _lower + ((_upper - _lower) >> 1);
                                if (data[p] < _json_trans_keys[_mid])
                                    _upper = _mid - 1;
                                else if (data[p] > _json_trans_keys[_mid])
                                    _lower = _mid + 1;
                                else {
                                    _trans += (_mid - _keys);
                                    break _match;
                                }
                            }
                            _keys += _klen;
                            _trans += _klen;
                        }

                        _klen = _json_range_lengths[cs];
                        if (_klen > 0) {
                            int _lower = _keys;
                            int _mid;
                            int _upper = _keys + (_klen << 1) - 2;
                            while (true) {
                                if (_upper < _lower)
                                    break;

                                _mid = _lower + (((_upper - _lower) >> 1) & ~1);
                                if (data[p] < _json_trans_keys[_mid])
                                    _upper = _mid - 2;
                                else if (data[p] > _json_trans_keys[_mid + 1])
                                    _lower = _mid + 2;
                                else {
                                    _trans += ((_mid - _keys) >> 1);
                                    break _match;
                                }
                            }
                            _trans += _klen;
                        }
                    } while (false);

                    _trans = _json_indicies[_trans];
                    cs = _json_trans_targs[_trans];

                    if (_json_trans_actions[_trans] != 0) {
                        _acts = _json_trans_actions[_trans];
                        _nacts = (int) _json_actions[_acts++];
                        while (_nacts-- > 0) {
                            switch (_json_actions[_acts++]) {
                            case 0:
                            // line 104 "JsonReader.rl"
                            {
                                stringIsName = true;
                            }
                                break;
                            case 1:
                            // line 107 "JsonReader.rl"
                            {
                                String value = new String(data, s, p - s);
                                if (needsUnescape)
                                    value = unescape(value);
                                outer: if (stringIsName) {
                                    stringIsName = false;
                                    if (debug)
                                        System.out.println("name: " + value);
                                    names.add(value);
                                } else {
                                    String name = names.size > 0 ? names.pop() : null;
                                    if (stringIsUnquoted) {
                                        if (value.equals("true")) {
                                            if (debug)
                                                System.out.println("boolean: " + name + "=true");
                                            bool(name, true);
                                            break outer;
                                        } else if (value.equals("false")) {
                                            if (debug)
                                                System.out.println("boolean: " + name + "=false");
                                            bool(name, false);
                                            break outer;
                                        } else if (value.equals("null")) {
                                            string(name, null);
                                            break outer;
                                        }
                                        boolean couldBeDouble = false, couldBeLong = true;
                                        outer2: for (int i = s; i < p; i++) {
                                            switch (data[i]) {
                                            case '0':
                                            case '1':
                                            case '2':
                                            case '3':
                                            case '4':
                                            case '5':
                                            case '6':
                                            case '7':
                                            case '8':
                                            case '9':
                                            case '-':
                                            case '+':
                                                break;
                                            case '.':
                                            case 'e':
                                            case 'E':
                                                couldBeDouble = true;
                                                couldBeLong = false;
                                                break;
                                            default:
                                                couldBeDouble = false;
                                                couldBeLong = false;
                                                break outer2;
                                            }
                                        }
                                        if (couldBeDouble) {
                                            try {
                                                if (debug)
                                                    System.out.println("double: " + name + "="
                                                            + Double.parseDouble(value));
                                                number(name, Double.parseDouble(value), value);
                                                break outer;
                                            } catch (NumberFormatException ignored) {
                                            }
                                        } else if (couldBeLong) {
                                            if (debug)
                                                System.out.println(
                                                        "double: " + name + "=" + Double.parseDouble(value));
                                            try {
                                                number(name, Long.parseLong(value), value);
                                                break outer;
                                            } catch (NumberFormatException ignored) {
                                            }
                                        }
                                    }
                                    if (debug)
                                        System.out.println("string: " + name + "=" + value);
                                    string(name, value);
                                }
                                stringIsUnquoted = false;
                                s = p;
                            }
                                break;
                            case 2:
                            // line 181 "JsonReader.rl"
                            {
                                String name = names.size > 0 ? names.pop() : null;
                                if (debug)
                                    System.out.println("startObject: " + name);
                                startObject(name);
                                {
                                    if (top == stack.length) {
                                        int[] newStack = new int[stack.length * 2];
                                        System.arraycopy(stack, 0, newStack, 0, stack.length);
                                        stack = newStack;
                                    }
                                    {
                                        stack[top++] = cs;
                                        cs = 5;
                                        _goto_targ = 2;
                                        if (true)
                                            continue _goto;
                                    }
                                }
                            }
                                break;
                            case 3:
                            // line 187 "JsonReader.rl"
                            {
                                if (debug)
                                    System.out.println("endObject");
                                pop();
                                {
                                    cs = stack[--top];
                                    _goto_targ = 2;
                                    if (true)
                                        continue _goto;
                                }
                            }
                                break;
                            case 4:
                            // line 192 "JsonReader.rl"
                            {
                                String name = names.size > 0 ? names.pop() : null;
                                if (debug)
                                    System.out.println("startArray: " + name);
                                startArray(name);
                                {
                                    if (top == stack.length) {
                                        int[] newStack = new int[stack.length * 2];
                                        System.arraycopy(stack, 0, newStack, 0, stack.length);
                                        stack = newStack;
                                    }
                                    {
                                        stack[top++] = cs;
                                        cs = 23;
                                        _goto_targ = 2;
                                        if (true)
                                            continue _goto;
                                    }
                                }
                            }
                                break;
                            case 5:
                            // line 198 "JsonReader.rl"
                            {
                                if (debug)
                                    System.out.println("endArray");
                                pop();
                                {
                                    cs = stack[--top];
                                    _goto_targ = 2;
                                    if (true)
                                        continue _goto;
                                }
                            }
                                break;
                            case 6:
                            // line 203 "JsonReader.rl"
                            {
                                int start = p - 1;
                                if (data[p++] == '/') {
                                    while (p != eof && data[p] != '\n')
                                        p++;
                                    p--;
                                } else {
                                    while (p + 1 < eof && data[p] != '*' || data[p + 1] != '/')
                                        p++;
                                    p++;
                                }
                                if (debug)
                                    System.out.println("comment " + new String(data, start, p - start));
                            }
                                break;
                            case 7:
                            // line 216 "JsonReader.rl"
                            {
                                if (debug)
                                    System.out.println("unquotedChars");
                                s = p;
                                needsUnescape = false;
                                stringIsUnquoted = true;
                                if (stringIsName) {
                                    outer: while (true) {
                                        switch (data[p]) {
                                        case '\\':
                                            needsUnescape = true;
                                            break;
                                        case '/':
                                            if (p + 1 == eof)
                                                break;
                                            char c = data[p + 1];
                                            if (c == '/' || c == '*')
                                                break outer;
                                            break;
                                        case ':':
                                        case '\r':
                                        case '\n':
                                            break outer;
                                        }
                                        if (debug)
                                            System.out.println("unquotedChar (name): '" + data[p] + "'");
                                        p++;
                                        if (p == eof)
                                            break;
                                    }
                                } else {
                                    outer: while (true) {
                                        switch (data[p]) {
                                        case '\\':
                                            needsUnescape = true;
                                            break;
                                        case '/':
                                            if (p + 1 == eof)
                                                break;
                                            char c = data[p + 1];
                                            if (c == '/' || c == '*')
                                                break outer;
                                            break;
                                        case '}':
                                        case ']':
                                        case ',':
                                        case '\r':
                                        case '\n':
                                            break outer;
                                        }
                                        if (debug)
                                            System.out.println("unquotedChar (value): '" + data[p] + "'");
                                        p++;
                                        if (p == eof)
                                            break;
                                    }
                                }
                                p--;
                                while (data[p] == ' ')
                                    p--;
                            }
                                break;
                            case 8:
                            // line 270 "JsonReader.rl"
                            {
                                if (debug)
                                    System.out.println("quotedChars");
                                s = ++p;
                                needsUnescape = false;
                                outer: while (true) {
                                    switch (data[p]) {
                                    case '\\':
                                        needsUnescape = true;
                                        p++;
                                        break;
                                    case '"':
                                        break outer;
                                    }
                                    // if (debug) System.out.println("quotedChar: '" + data[p] + "'");
                                    p++;
                                    if (p == eof)
                                        break;
                                }
                                p--;
                            }
                                break;
                            // line 313 "JsonReader.java"
                            }
                        }
                    }

                case 2:
                    if (cs == 0) {
                        _goto_targ = 5;
                        continue _goto;
                    }
                    if (++p != pe) {
                        _goto_targ = 1;
                        continue _goto;
                    }
                case 4:
                    if (p == eof) {
                        int __acts = _json_eof_actions[cs];
                        int __nacts = (int) _json_actions[__acts++];
                        while (__nacts-- > 0) {
                            switch (_json_actions[__acts++]) {
                            case 1:
                            // line 107 "JsonReader.rl"
                            {
                                String value = new String(data, s, p - s);
                                if (needsUnescape)
                                    value = unescape(value);
                                outer: if (stringIsName) {
                                    stringIsName = false;
                                    if (debug)
                                        System.out.println("name: " + value);
                                    names.add(value);
                                } else {
                                    String name = names.size > 0 ? names.pop() : null;
                                    if (stringIsUnquoted) {
                                        if (value.equals("true")) {
                                            if (debug)
                                                System.out.println("boolean: " + name + "=true");
                                            bool(name, true);
                                            break outer;
                                        } else if (value.equals("false")) {
                                            if (debug)
                                                System.out.println("boolean: " + name + "=false");
                                            bool(name, false);
                                            break outer;
                                        } else if (value.equals("null")) {
                                            string(name, null);
                                            break outer;
                                        }
                                        boolean couldBeDouble = false, couldBeLong = true;
                                        outer2: for (int i = s; i < p; i++) {
                                            switch (data[i]) {
                                            case '0':
                                            case '1':
                                            case '2':
                                            case '3':
                                            case '4':
                                            case '5':
                                            case '6':
                                            case '7':
                                            case '8':
                                            case '9':
                                            case '-':
                                            case '+':
                                                break;
                                            case '.':
                                            case 'e':
                                            case 'E':
                                                couldBeDouble = true;
                                                couldBeLong = false;
                                                break;
                                            default:
                                                couldBeDouble = false;
                                                couldBeLong = false;
                                                break outer2;
                                            }
                                        }
                                        if (couldBeDouble) {
                                            try {
                                                if (debug)
                                                    System.out.println("double: " + name + "="
                                                            + Double.parseDouble(value));
                                                number(name, Double.parseDouble(value), value);
                                                break outer;
                                            } catch (NumberFormatException ignored) {
                                            }
                                        } else if (couldBeLong) {
                                            if (debug)
                                                System.out.println(
                                                        "double: " + name + "=" + Double.parseDouble(value));
                                            try {
                                                number(name, Long.parseLong(value), value);
                                                break outer;
                                            } catch (NumberFormatException ignored) {
                                            }
                                        }
                                    }
                                    if (debug)
                                        System.out.println("string: " + name + "=" + value);
                                    string(name, value);
                                }
                                stringIsUnquoted = false;
                                s = p;
                            }
                                break;
                            // line 411 "JsonReader.java"
                            }
                        }
                    }

                case 5:
                }
                break;
            }
        }

        // line 306 "JsonReader.rl"

    } catch (RuntimeException ex) {
        parseRuntimeEx = ex;
    }

    JsonValue root = this.root;
    this.root = null;
    current = null;
    lastChild.clear();

    if (p < pe) {
        int lineNumber = 1;
        for (int i = 0; i < p; i++)
            if (data[i] == '\n')
                lineNumber++;
        throw new SerializationException("Error parsing JSON on line " + lineNumber + " near: "
                + new String(data, p, Math.min(256, pe - p)), parseRuntimeEx);
    } else if (elements.size != 0) {
        JsonValue element = elements.peek();
        elements.clear();
        if (element != null && element.isObject())
            throw new SerializationException("Error parsing JSON, unmatched brace.");
        else
            throw new SerializationException("Error parsing JSON, unmatched bracket.");
    } else if (parseRuntimeEx != null) {
        throw new SerializationException("Error parsing JSON: " + new String(data), parseRuntimeEx);
    }
    return root;
}

From source file:com.kotcrab.vis.editor.module.physicseditor.util.trace.TextureConverter.java

License:Apache License

private static Array<Vector2> CreateSimplePolygon(PolygonCreationAssistance pca, Vector2 entrance,
        Vector2 last) {/*w  ww  .  j  a  va  2s.  co  m*/
    boolean entranceFound = false;
    boolean endOfHull = false;
    Array<Vector2> polygon = new Array<Vector2>();
    Array<Vector2> hullArea = new Array<Vector2>();
    Array<Vector2> endOfHullArea = new Array<Vector2>();
    Vector2 current = new Vector2();
    Vector2 zeroVec = new Vector2();
    // Get the entrance point. //todo: alle moglichkeiten testen
    if (vectorEquals(entrance, zeroVec) || !pca.InBounds(entrance)) {
        entranceFound = GetHullEntrance(pca, entrance);
        if (entranceFound) {
            current.set(entrance.x - 1f, entrance.y);
        }
    } else {
        if (pca.IsSolid(entrance)) {
            if (IsNearPixel(pca, entrance, last)) {
                current.set(last);
                entranceFound = true;
            } else {
                Vector2 temp = new Vector2();
                if (SearchNearPixels(pca, false, entrance, temp)) {
                    current.set(temp);
                    entranceFound = true;
                } else {
                    entranceFound = false;
                }
            }
        }
    }
    if (entranceFound) {
        polygon.add(entrance);
        hullArea.add(entrance);
        Vector2 next = entrance.cpy();
        do {
            // Search in the pre vision list for an outstanding point.
            Vector2 outstanding = new Vector2();
            if (SearchForOutstandingVertex(hullArea, pca.getHullTolerance(), outstanding)) {
                if (endOfHull) {
                    // We have found the next pixel, but is it on the last
                    // bit of the
                    // hull?
                    if (vectorListContains(endOfHullArea, outstanding)
                            && !vectorListContains(polygon, outstanding)) {
                        // Indeed.
                        polygon.add(outstanding);
                    }
                    // That's enough, quit.
                    break;
                }
                // Add it and remove all vertices that don't matter anymore
                // (all the vertices before the outstanding).
                polygon.add(outstanding);
                int index = vectorListIndexOf(hullArea, outstanding);
                if (index == -1) {
                    int debug = 1;
                }
                if (index >= 0) {
                    // hullArea = hullArea.subList(index + 1,
                    // hullArea.size);

                    // Array<Vector2> newArray = new Array<Vector2>
                    // (hullArea.size - (index + 1));
                    int counter = 0;
                    for (int i = index + 1; i < hullArea.size; i++) {
                        Vector2 v = hullArea.get(index);
                        // newArray.add(v);
                        hullArea.set(counter, v);
                        counter++;
                    }
                    // hullArea.clear();
                    // hullArea = newArray;
                    for (int i = 0; i < index + 1; i++) {
                        hullArea.pop();
                    }
                }
            }
            // Last point gets current and current gets next. Our little
            // spider is
            // moving forward on the hull ;).
            last.set(current);
            current.set(next);
            // Get the next point on hull.
            next = new Vector2();
            if (GetNextHullPoint(pca, last, current, next)) {
                // Add the vertex to a hull pre vision list.
                hullArea.add(next);
            } else {
                // Quit
                break;
            }
            if (vectorEquals(next, entrance) && !endOfHull) {
                // It's the last bit of the hull, search on and exit at next
                // found
                // vertex.
                endOfHull = true;
                endOfHullArea.addAll(hullArea);
            }
        } while (true);
    }
    return polygon;
}

From source file:com.turbogerm.helljump.game.generator.RiseGenerator.java

License:Open Source License

private static void adjustLastRiseSection(Array<RiseSectionData> riseSectionsData) {
    RiseSectionData lastRiseSectionData = riseSectionsData.pop();

    int lastPlatformStep = lastRiseSectionData.getPlatformsData().peek().getStep();
    int newStepRange = lastPlatformStep + PlatformData.MAX_PLATFORM_DISTANCE_STEPS;

    // make sure there is maximum platform distance between last platform and end line
    // this way no platforms will be seen on end background texture
    RiseSectionData newLastRiseSectionData = new RiseSectionData(lastRiseSectionData.getType(),
            lastRiseSectionData.getName(), newStepRange, lastRiseSectionData.getDifficulty(),
            lastRiseSectionData.getPlatformsData(), lastRiseSectionData.getEnemiesData(),
            lastRiseSectionData.getItemsData());

    riseSectionsData.add(newLastRiseSectionData);
}

From source file:com.vlaaad.dice.game.user.Die.java

License:Open Source License

public Die(ProfessionDescription profession, String name, int exp, Array<Ability> abilities,
        ObjectIntMap<Ability> inventory) {
    this.profession = profession;
    this.name = name;
    this.exp = exp;
    this.abilities = abilities;
    this.inventory = inventory;
    Iterator<Ability> it = abilities.iterator();
    while (it.hasNext()) {
        Ability ability = it.next();/*from  w ww .ja v a 2 s.  c  om*/
        if (ability != null && !profession.ignoreRequirements && (!ability.requirement.isSatisfied(this))) {
            inventory.getAndIncrement(ability, 0, 1);
            it.remove();
        }
    }
    int used = getUsedSkill();
    int total = getTotalSkill();
    if (used > total) {
        System.out.print(name + " has skill overdraft, " + used + " > " + total + ", inventory = ");
    }
    while (abilities.size > 0 && getUsedSkill() > getTotalSkill()) {
        Ability popped = abilities.pop();
        if (popped != null)
            inventory.getAndIncrement(popped, 0, 1);
    }
    if (used > total)
        System.out.println(inventory);

    while (abilities.size < 6)
        abilities.add(null);
}

From source file:com.vlaaad.dice.game.world.controllers.SpawnController.java

License:Open Source License

@SuppressWarnings("unchecked")
private void autoPlace() {
    if (placed.size > 0) {
        ObjectSet<Creature> tmp = Pools.obtain(ObjectSet.class);
        tmp.addAll(placed);//from   w w w. java 2 s .  co m
        for (Creature c : tmp) {
            removeFromPlaced(c);
        }
        tmp.clear();
        Pools.free(tmp);
    }
    Array<Grid2D.Coordinate> coordinates = Pools.obtain(Array.class);
    Set<Map.Entry<Grid2D.Coordinate, Fraction>> spawns = world.level.getElements(LevelElementType.spawn);
    for (Map.Entry<Grid2D.Coordinate, Fraction> e : spawns) {
        if (e.getValue() == world.viewer.fraction) {
            coordinates.add(e.getKey());
        }
    }
    coordinates.shuffle();
    int usedCount = Math.min(creatures.size, coordinates.size);
    Array<Creature> toPlace = Pools.obtain(Array.class);
    toPlace.addAll(creatures);
    toPlace.shuffle();
    toPlace.truncate(usedCount);
    for (Creature creature : toPlace) {
        Grid2D.Coordinate coordinate = coordinates.pop();
        place(creature, coordinate.x(), coordinate.y());
    }
    toPlace.clear();
    coordinates.clear();
    Pools.free(toPlace);
    Pools.free(coordinates);
}

From source file:com.vlaaad.dice.game.world.view.visualizers.actions.ShamanDefenceVisualizer.java

License:Open Source License

@Override
public IFuture<Void> visualize(final ShamanDefenceResult result) {
    final Future<Void> future = Future.make();
    final WorldObjectView view = visualizer.viewController.getView(result.creatureToAddEffect);
    final AnimationSubView appear = new AnimationSubView(0.1f, Config.findRegions(ANIMATION_NAME),
            Animation.PlayMode.NORMAL);/*from  w  ww.  j  a  v a2s .c  o  m*/
    init(appear);
    view.addSubView(appear);
    SoundManager.instance.playMusicAsSound("ability-" + result.ability.name);
    appear.getActor().addListener(new AnimationListener() {
        @Override
        protected void onAnimationEvent(AnimationEvent event) {
            view.removeSubView(appear);
            Array<TextureRegion> playRegions = Array.with(appear.animation.getKeyFrames());
            playRegions.removeIndex(0);
            playRegions.add(playRegions.peek());
            final AnimationSubView play = new AnimationSubView(0.5f, playRegions, Animation.PlayMode.LOOP);
            init(play);
            view.addSubView(play);
            result.creature.world.dispatcher.add(Creature.REMOVE_EFFECT, new EventListener<EffectEvent>() {
                @Override
                public void handle(EventType<EffectEvent> type, EffectEvent event) {
                    if (event.creature == result.creature && event.effect == result.effectToApply) {
                        result.creature.world.dispatcher.remove(Creature.REMOVE_EFFECT, this);
                        view.removeSubView(play);
                        if (result.creature.isKilled())
                            return;
                        SoundManager.instance.playMusicAsSound("ability-" + result.ability.name);
                        Array<TextureAtlas.AtlasRegion> disappearRegions = new Array<TextureAtlas.AtlasRegion>(
                                Config.findRegions(ANIMATION_NAME));
                        disappearRegions.pop();
                        final AnimationSubView disappear = new AnimationSubView(0.1f, disappearRegions,
                                Animation.PlayMode.REVERSED);
                        init(disappear);
                        view.addSubView(disappear);
                        disappear.getActor().addListener(new AnimationListener() {
                            @Override
                            protected void onAnimationEvent(AnimationEvent event) {
                                view.removeSubView(disappear);
                            }
                        });

                    }
                }
            });
            future.happen();

        }
    });
    return future;
}

From source file:com.vlaaad.dice.game.world.view.visualizers.actions.TeleportVisualizer.java

License:Open Source License

private Array<TextureAtlas.AtlasRegion> compose(String name) {
    Array<TextureAtlas.AtlasRegion> result = composes.get(name);
    if (result == null) {
        result = new Array<TextureAtlas.AtlasRegion>(Config.findRegions(name));
        Array<TextureAtlas.AtlasRegion> rev = new Array<TextureAtlas.AtlasRegion>(result);
        rev.pop();
        rev.reverse();/* w  ww  .  ja  va2 s .  co m*/
        for (int i = 0; i < 1; i++) {
            result.add(result.get(result.size - 2));
            result.add(result.get(result.size - 2));
        }
        result.addAll(rev);
        composes.put(name, result);
    }
    return result;
}

From source file:im.ligas.worms.worm.impl.ReverseWormImpl.java

License:Open Source License

private void reverse(Array<Float> body) {
    Array<Float> copy = new Array<Float>(body);
    body.clear();//from   w ww.  ja v a2s  .  com
    while (copy.size > 0) {
        Float y = copy.pop();
        Float x = copy.pop();
        body.add(x);
        body.add(y);
    }
}

From source file:kyle.game.besiege.Kingdom.java

License:Open Source License

public void initializeCities() {
    Array<String> cityArray = Assets.cityArray;
    //      Scanner scanner = Assets.cityList;

    //      int currentFaction = 2; // no bandits or player 
    //      int factionRepeats = 0;

    //      int maxRepeats = (int) (Math.random()*3) + 1; // max 2, min 0
    int maxRepeats = 4;

    //      while (scanner.hasNextLine() && (map.cityCorners.size > 0 && map.cityCenters.size > 0)) {
    while (cityArray.size > 0 && (map.cityCorners.size > 0 && map.cityCenters.size > 0)) {
        //         System.out.println("adding city");
        City city;//from  w  ww  .j  a  v a  2 s .  c  o m
        int x, y;
        boolean useCorner = true; // later allow to use center
        if (Math.random() > .5)
            useCorner = false; // later allow to use center
        // make with corner
        if (useCorner) {
            Corner corner;
            corner = map.cityCorners.random();
            x = (int) corner.getLoc().x;
            y = (int) corner.getLoc().y;
            map.cityCorners.removeValue(corner, true);
            map.availableCorners.removeValue(corner, true);

            // remove neighboring corners 2 levels deep!
            for (Corner adj : corner.adjacent) {
                if (adj != null) {
                    map.cityCorners.removeValue(adj, true);
                    map.availableCorners.removeValue(adj, true);
                    for (int i = 0; i < adj.adjacent.size(); i++) {
                        // two levels deep
                        if (adj.adjacent.get(i) != null)
                            map.cityCorners.removeValue(adj.adjacent.get(i), true);
                    }
                }
            }
            // remove neighboring centers
            for (Center adj : corner.touches) {
                if (adj != null) {
                    map.cityCenters.removeValue(adj, true);
                    map.availableCenters.removeValue(adj, true);
                }
            }
            int index = -1;
            // calculate the closest city
            double closestDistance = 9999999;
            City closestCity = null;
            for (City c : cities) {
                double distance = c.distTo(x, Map.HEIGHT - y);
                if (distance < closestDistance) {
                    closestCity = c;
                    closestDistance = distance;
                }
            }
            Faction faction = null;
            if (closestCity == null || closestCity.getFaction().cities.size > maxRepeats) {
                int factionIndex = 2;
                while (Faction.get(factionIndex).cities.size > maxRepeats)
                    factionIndex++;
                faction = Faction.get(factionIndex);
            } else
                faction = closestCity.getFaction();

            city = new City(this, cityArray.pop(), index, faction, x, Map.HEIGHT - y, CITY_START_WEALTH);
            //            city = new City(this, cityArray.pop(), index, Faction.get(currentFaction), x, Map.HEIGHT-y, CITY_START_WEALTH);
            city.setCorner(corner);
        }
        // make with center
        else {
            Center center;
            center = map.cityCenters.random();
            x = (int) center.loc.x;
            y = (int) center.loc.y;
            map.cityCenters.removeValue(center, true);
            map.availableCenters.removeValue(center, true);

            for (Corner adj : center.corners) {
                if (adj != null) {
                    map.cityCorners.removeValue(adj, true);
                    //                  map.availableLocationSites.removeValue(adj.loc, false);
                    for (int i = 0; i < adj.adjacent.size(); i++) {
                        // two levels deep
                        if (adj.adjacent.get(i) != null) {
                            map.cityCorners.removeValue(adj.adjacent.get(i), true);
                            //                        map.availableLocationSites.removeValue(adj.adjacent.get(i).loc, false);
                        }
                    }
                }
            }
            for (Center adjCenter : center.neighbors) {
                if (adjCenter != null) {
                    map.cityCenters.removeValue(adjCenter, true);
                    //                  map.availableLocationSites.removeValue(adjCenter.loc, false);
                }
            }
            int index = -1;
            //            city = new City(this, scanner.next(), index, Faction.get(currentFaction), x, Map.HEIGHT-y, CITY_START_WEALTH);

            // calculate the closest city
            double closestDistance = 9999999;
            City closestCity = null;
            for (City c : cities) {
                double distance = c.distTo(x, Map.HEIGHT - y);
                if (distance < closestDistance) {
                    closestCity = c;
                    closestDistance = distance;
                }
            }
            Faction faction = null;
            if (closestCity == null || closestCity.getFaction().cities.size > maxRepeats) {
                // TODO set faction to be lowest numbered faction without repeats
                int factionIndex = 2;
                while (Faction.get(factionIndex).cities.size > maxRepeats)
                    factionIndex++;
                faction = Faction.get(factionIndex);
            } else
                faction = closestCity.getFaction();

            city = new City(this, cityArray.pop(), index, faction, x, Map.HEIGHT - y, CITY_START_WEALTH);
            //            city = new City(this, cityArray.pop(), index, Faction.get(currentFaction), x, Map.HEIGHT-y, CITY_START_WEALTH);

            city.setCenter(center);
        }

        addCity(city);
        //         factionRepeats++;
        //         if (factionRepeats > maxRepeats) {
        //            currentFaction++;
        //            factionRepeats = 0;
        //            maxRepeats = (int) (Math.random()*3) + 1;
        //         }
    }

    // assign factions to cities
    //      for (City c : cities) {
    //         c.changeFaction(Faction.get(2));
    //      }
    // best solution: calculate city locations in advance, then assign factions, then create cities.

    System.out.println("Number cities: " + cities.size);
}

From source file:kyle.game.besiege.Kingdom.java

License:Open Source License

public void initializeVillages() {
    //      Scanner scanner = Assets.villageList;
    Array<String> villageArray = Assets.villageArray;

    //      while (scanner.hasNextLine() && map.availableCenters.size > 0) {
    while (villageArray.size > 0 && map.availableCenters.size > 0) {
        Center center = map.availableCenters.random();

        //         Village village = new Village(this, scanner.next(), -1, null, (float) center.loc.x, (float) (Map.HEIGHT-center.loc.y), VILLAGE_START_WEALTH);         
        Village village = new Village(this, villageArray.pop(), -1, null, (float) center.loc.x,
                (float) (Map.HEIGHT - center.loc.y), VILLAGE_START_WEALTH);
        villages.add(village);//  www .ja  va 2s.com
        village.center = center;
        addActor(village);
    }
    System.out.println("Number villages: " + villages.size);
}