Example usage for com.badlogic.gdx InputAdapter InputAdapter

List of usage examples for com.badlogic.gdx InputAdapter InputAdapter

Introduction

In this page you can find the example usage for com.badlogic.gdx InputAdapter InputAdapter.

Prototype

InputAdapter

Source Link

Usage

From source file:com.badlogic.invaders.Invaders.java

License:Apache License

@Override
public void create() {
    Array<Controller> controllers = Controllers.getControllers();
    if (controllers.size > 0) {
        controller = controllers.first();
    }//from  ww w. ja va 2 s . c o  m
    Controllers.addListener(controllerListener);

    setScreen(new MainMenu(this));
    music = Gdx.audio.newMusic(Gdx.files.getFileHandle("data/8.12.mp3", FileType.Internal));
    music.setLooping(true);
    music.play();
    Gdx.input.setInputProcessor(new InputAdapter() {
        @Override
        public boolean keyUp(int keycode) {
            if (keycode == Keys.ENTER && Gdx.app.getType() == ApplicationType.WebGL) {
                if (!Gdx.graphics.isFullscreen())
                    Gdx.graphics.setDisplayMode(Gdx.graphics.getDisplayModes()[0]);
            }
            return true;
        }
    });

    fps = new FPSLogger();
}

From source file:com.dongbat.invasion.util.PlayerInputUtil.java

public static void init() {
    Gdx.input.setInputProcessor(new InputAdapter() {

        @Override//  ww w  . j  a  v a  2  s.  c  om
        public boolean touchDragged(int screenX, int screenY, int pointer) {
            aim(screenX, screenY);
            return true;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            fireVector = new Vector2(aimVector);
            aimVector = null;
            return true;
        }

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            aim(screenX, screenY);
            return true;
        }

        private void aim(int x, int y) {
            Vector3 v = new Vector3(x, y, 0);
            v = camera.unproject(v);
            aimVector = new Vector2(v.x, v.y);
            if (aimVector.len2() >= 400) {
                aimVector.nor().scl(20);
            }
        }
    });
}

From source file:com.esotericsoftware.spine.SimpleTest2.java

License:Open Source License

public void create() {
    camera = new OrthographicCamera();
    batch = new SpriteBatch();
    renderer = new SkeletonRenderer();
    renderer.setPremultipliedAlpha(true);
    debugRenderer = new SkeletonRendererDebug();

    atlas = new TextureAtlas(Gdx.files.internal("spineboy/spineboy.atlas"));
    SkeletonJson json = new SkeletonJson(atlas); // This loads skeleton JSON data, which is stateless.
    json.setScale(0.6f); // Load the skeleton at 60% the size it was in Spine.
    SkeletonData skeletonData = json.readSkeletonData(Gdx.files.internal("spineboy/spineboy.json"));

    skeleton = new Skeleton(skeletonData); // Skeleton holds skeleton state (bone positions, slot attachments, etc).
    skeleton.setPosition(250, 20);//  w  ww  .  j  av a  2s  .c o  m
    skeleton.setAttachment("head-bb", "head"); // Attach "head" bounding box to "head-bb" slot.

    bounds = new SkeletonBounds(); // Convenience class to do hit detection with bounding boxes.

    AnimationStateData stateData = new AnimationStateData(skeletonData); // Defines mixing (crossfading) between animations.
    stateData.setMix("run", "jump", 0.2f);
    stateData.setMix("jump", "run", 0.2f);
    stateData.setMix("jump", "jump", 0);

    state = new AnimationState(stateData); // Holds the animation state for a skeleton (current animation, time, etc).
    state.setTimeScale(0.3f); // Slow all animations down to 30% speed.
    state.addListener(new AnimationStateListener() {
        public void event(int trackIndex, Event event) {
            System.out.println(trackIndex + " event: " + state.getCurrent(trackIndex) + ", "
                    + event.getData().getName() + ", " + event.getInt());
        }

        public void complete(int trackIndex, int loopCount) {
            System.out.println(trackIndex + " complete: " + state.getCurrent(trackIndex) + ", " + loopCount);
        }

        public void start(int trackIndex) {
            System.out.println(trackIndex + " start: " + state.getCurrent(trackIndex));
        }

        public void end(int trackIndex) {
            System.out.println(trackIndex + " end: " + state.getCurrent(trackIndex));
        }
    });

    // Set animation on track 0.
    state.setAnimation(0, "run", true);

    Gdx.input.setInputProcessor(new InputAdapter() {
        final Vector3 point = new Vector3();

        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            camera.unproject(point.set(screenX, screenY, 0)); // Convert window to world coordinates.
            bounds.update(skeleton, true); // Update SkeletonBounds with current skeleton bounding box positions.
            if (bounds.aabbContainsPoint(point.x, point.y)) { // Check if inside AABB first. This check is fast.
                BoundingBoxAttachment hit = bounds.containsPoint(point.x, point.y); // Check if inside a bounding box.
                if (hit != null) {
                    System.out.println("hit: " + hit);
                    skeleton.findSlot("head").getColor().set(Color.RED); // Turn head red until touchUp.
                }
            }
            return true;
        }

        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            skeleton.findSlot("head").getColor().set(Color.WHITE);
            return true;
        }

        public boolean keyDown(int keycode) {
            state.setAnimation(0, "jump", false); // Set animation on track 0 to jump.
            state.addAnimation(0, "run", true, 0); // Queue run to play after jump.
            return true;
        }
    });
}

From source file:com.exovum.test.animation.CreditsScreen.java

License:Creative Commons License

public CreditsScreen(final Game game, Screen parentScreen) {
    this.batch = new SpriteBatch();
    this.game = game;
    this.parent = parentScreen;

    Gdx.app.log("CreditsScreen", "Creating CreditsScreen");

    menuBackground = new Texture(Gdx.files.internal("beach-ocean-sea-bg/transparent-png/full_background.png"));

    stage = new Stage(new FitViewport(800, 480));
    Gdx.input.setInputProcessor(stage);/*  w  ww.j  a v a 2s. c om*/
    skin = new Skin(Gdx.files.internal("uiskin.json"));

    mainTable = new Table(skin);
    //mainTable.defaults().expand().fill().padBottom(4f).padTop(4f);
    mainTable.setFillParent(true);

    baseTable = new Table(skin);
    baseTable.defaults().expand().fill().padBottom(10f).padTop(10f);

    Label myHeader = new Label("General", skin, "small-font");
    myHeader.setColor(Color.FIREBRICK);
    myHeader.setAlignment(Align.center);

    Label myCredits = new Label("Programming and Development\n" + "Caleb Stevenson", skin, "small-font");
    myCredits.setColor(Color.BLACK);
    myCredits.setAlignment(Align.center);

    Label musicHeader = new Label("Music", skin, "small-font");
    musicHeader.setColor(Color.FIREBRICK);
    musicHeader.setAlignment(Align.center);

    Label musicCredits = new Label("\"Capre Diem\", \"Hidden Past\", \"Pixel Peeker Polka - slower\"\n"
            + "Kevin MacLeod (incompetech.com)\n" + "Licensed under Creative Commons: By Attribution 3.0\n"
            + "http://creativecommons.org/licenses/by/3.0/", skin, "small-font");
    musicCredits.setColor(Color.BLACK);
    musicCredits.setAlignment(Align.center);

    Label artHeader = new Label("Artwork", skin, "small-font");
    artHeader.setColor(Color.FIREBRICK);
    artHeader.setAlignment(Align.center);

    Label artCredits = new Label("Background and Tree Sprites\n" + "http://bevouliin.com\nopengameart.org",
            skin, "small-font");
    artCredits.setColor(Color.BLACK);

    artCredits.setAlignment(Align.center);

    TextButton exitButton = new TextButton("Back to Menu", skin, "small-font");

    Table buttonTable = new Table(skin);
    baseTable.add(myHeader).row();
    baseTable.add(myCredits).row();
    baseTable.add(musicHeader).row();
    baseTable.add(musicCredits).row();
    baseTable.add(artHeader).row();
    baseTable.add(artCredits).row();
    baseTable.add(buttonTable);
    //menuTable.setBackground("console2");
    // Set the color of the BACKGROUND on the buttons
    Color buttonColor = Color.SKY;
    exitButton.setColor(buttonColor);
    // Set the color of the TEXT on the buttons
    exitButton.getLabel().setColor(new Color(0.91f, 0.91f, 0.91f, 1));

    buttonTable.defaults().expand().fill().padBottom(4f).padTop(2f);
    buttonTable.add(exitButton).width(180f).height(60f);
    //buttonTable.padTop(20f).padBottom(20f);
    buttonTable.left();

    // Add baseTable containing buttonTable to the next row of mainTable
    //mainTable.add(buttonTable);
    mainTable.add(baseTable);
    // Add mainTable to the stage
    stage.addActor(mainTable);

    exitButton.addListener(new ChangeListener() {
        public void changed(ChangeEvent event, Actor actor) {
            Gdx.app.log("CreditsScreen", "Exiting to main menu");
            //game.setScreen(new AnimatorMenuScreen(game));
            //game.setScreen(parent);
            //((Game) Gdx.app.getApplicationListener()).setScreen(parent);
            ((Game) Gdx.app.getApplicationListener()).setScreen(new AnimatorMenuScreen(game));
        }
    });

    //Use an InputMultiplexer so that the Stage and keyDown input processors can both be used
    InputMultiplexer multiplexer = new InputMultiplexer();
    multiplexer.addProcessor(stage);
    multiplexer.addProcessor(new InputAdapter() {
        // If the back key is pressed, go to main menu
        // This also handles the Android 'back' button
        @Override
        public boolean keyDown(int keycode) {
            if (keycode == Input.Keys.BACK) {
                // Handle the back button
                Gdx.app.log("CreditsScreen", "KeyDown: BACK pressed");
                //AnimatorMenuScreen newMenu = new AnimatorMenuScreen(batch, game);
                //game.setScreen(newMenu);
                //game.setScreen(parent);
                //((Game) Gdx.app.getApplicationListener()).setScreen(parent);
                ((Game) Gdx.app.getApplicationListener()).setScreen(new AnimatorMenuScreen(game));
                return true;
            }
            return false;
        }
    });

    Gdx.input.setInputProcessor(multiplexer);
}

From source file:com.explatcreations.sft.gui.ControlWidget.java

License:Open Source License

@Override
public void updateSelected() {
    highlight.update();//from   w  ww. jav  a  2 s.  c  o  m
    if (Controls.Enter.justPressed() && !isActive()) {
        final ControllerAdapter controllerListener = new ControllerAdapter() {
            @Override
            public boolean buttonDown(Controller controller, int buttonIndex) {
                for (JoypadButton button : JoypadButton.getAll()) {
                    if (!(button.info instanceof FaceInfo)) {
                        continue;
                    }
                    final FaceInfo info = (FaceInfo) button.info;
                    if (info.code == buttonIndex) {
                        Controls.setButton(name, button);
                        isActive = false;
                        resyncAllAction.eval();
                        Gdx.input.setInputProcessor(null);
                        Controllers.removeListener(this);
                    }
                }
                return false;
            }

            private void changeAxis(int axisIndex, int sign) {
                for (JoypadButton button : JoypadButton.getAll()) {
                    if (!(button.info instanceof AxisInfo)) {
                        continue;
                    }
                    final AxisInfo info = (AxisInfo) button.info;
                    if (info.axisIndex == axisIndex && info.sign == sign) {
                        Controls.setButton(name, button);
                        isActive = false;
                        resyncAllAction.eval();
                        Gdx.input.setInputProcessor(null);
                        Controllers.removeListener(this);
                    }

                }
            }

            @Override
            public boolean axisMoved(Controller controller, int axisIndex, float value) {
                final int rounded = JoypadHelper.round(value);
                changeAxis(axisIndex, rounded);
                return false;
            }

            @Override
            public boolean povMoved(Controller controller, int povIndex, PovDirection value) {
                final int sign;
                final int axisIndex;
                if (value == PovDirection.east) {
                    axisIndex = Controls.HorizontalAxis;
                    sign = 1;
                } else if (value == PovDirection.north) {
                    axisIndex = Controls.VerticalAxis;
                    sign = -1;
                } else if (value == PovDirection.south) {
                    axisIndex = Controls.VerticalAxis;
                    sign = 1;
                } else if (value == PovDirection.west) {
                    axisIndex = Controls.HorizontalAxis;
                    sign = -1;
                } else {
                    return false;
                }
                changeAxis(axisIndex, sign);
                return false;
            }
        };
        final InputAdapter inputListener = new InputAdapter() {
            @Override
            public boolean keyDown(int keycode) {
                isActive = false;
                Controls.setKey(name, keycode);
                resyncAllAction.eval();
                Gdx.input.setInputProcessor(null);
                Controllers.removeListener(controllerListener);
                return false;
            }
        };

        Gdx.input.setInputProcessor(inputListener);
        Controllers.addListener(controllerListener);
        isActive = true;
    } else if (isActive()) {

    }
}

From source file:com.felix.game.ViewportTest1.java

License:Apache License

public void create() {
    stage = new Stage();
    Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));

    label = new Label("", skin);

    Table root = new Table(skin);
    root.setFillParent(true);//from  w  ww.j  a  va  2  s.c  o  m
    root.setBackground(skin.getDrawable("default-pane"));
    root.debug().defaults().space(6);
    root.add(new TextButton("Button 1", skin));
    root.add(new TextButton("Button 2", skin)).row();
    root.add("Press spacebar to change the viewport:").colspan(2).row();
    root.add(label).colspan(2);
    stage.addActor(root);

    viewports = getViewports(stage.getCamera());
    names = getViewportNames();

    stage.setViewport(viewports.first());
    label.setText(names.first());

    Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter() {
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            int index = (viewports.indexOf(stage.getViewport(), true) + 1) % viewports.size;
            label.setText(names.get(index));
            Viewport viewport = viewports.get(index);
            stage.setViewport(viewport);
            resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            return false;
        }

    }, stage));

}

From source file:com.gdx.extension.ui.input.InputCatcher.java

License:Apache License

/**
 * Create an input catcher with defined style.
 * /*from ww w.  j  a v a 2 s  .  c  o m*/
 * @param defaultInputs default inputs or null if any
 * @param catchingMessage the message displayed in catching mode
 * @param style the style to use
 */
public InputCatcher(InputArray defaultInputs, String catchingMessage, InputCatcherStyle style) {
    setTouchable(Touchable.enabled);

    capturedInputs = new InputArray();
    mouseListener = new InputAdapter();

    currentInputs = new InputArray();
    if (defaultInputs != null) {
        currentInputs.addAll(defaultInputs);
    }

    inputsLabel = new Label((defaultInputs != null) ? defaultInputs.toString() : "",
            style.desactivatedLabelStyle);
    catchingLabel = new Label(catchingMessage, style.activatedLabelStyle);

    setStyle(style);
    if (style.desactivatedBackground != null) {
        setBackground(style.desactivatedBackground);
    }
    setActor(inputsLabel);

    mouseListener = new InputAdapter() {

        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            if (isCatching) {
                capturedInputs.add(new InputHolder(InputType.Mouse, button));
                return true;
            }
            return false;
        }

        @Override
        public boolean touchUp(int screenX, int screenY, int pointer, int button) {
            if (isCatching && capturedInputs.size > 0) {
                onInternalStopCatching();
                return true;
            }
            return false;
        }

        @Override
        public boolean keyDown(int keycode) {
            if (isCatching) {
                if (keycode == Keys.ESCAPE) {
                    onInternalStopCatching();
                } else {
                    capturedInputs.add(new InputHolder(InputType.Keyboard, keycode));
                }
                return true;
            }
            return false;
        }

        @Override
        public boolean keyUp(int keycode) {
            if (isCatching) {
                onInternalStopCatching();
                return true;
            }
            return false;
        }

        @Override
        public boolean scrolled(int amount) {
            if (isCatching) {
                int _scrollInput = 0;
                if (amount < 0) {
                    _scrollInput = Buttons.WHEEL_UP;
                } else {
                    _scrollInput = Buttons.WHEEL_DOWN;
                }
                capturedInputs.add(new InputHolder(InputType.Mouse, _scrollInput));
                onInternalStopCatching();
                return true;
            }
            return false;
        }
    };
    addListener(new InputListener() {

        @Override
        public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
            if (!isCatching && button == Buttons.LEFT) {
                onInternalStartCatching();
            }
            return true;
        }

        @Override
        public void enter(InputEvent event, float x, float y, int pointer, Actor fromActor) {
            if (isCatching)
                return;

            Drawable _overBackground = InputCatcher.this.style.overBackground;
            if (_overBackground != null) {
                setBackground(_overBackground);
            }
        }

        @Override
        public void exit(InputEvent event, float x, float y, int pointer, Actor toActor) {
            if (isCatching)
                return;

            Drawable _desactivatedBackground = InputCatcher.this.style.desactivatedBackground;
            if (_desactivatedBackground != null) {
                setBackground(_desactivatedBackground);
            }
        }

    });
}

From source file:com.github.squidpony.SquidBasicDemo.java

@Override
public void create() {
    //These variables, corresponding to the screen's width and height in cells and a cell's width and height in
    //pixels, must match the size you specified in the launcher for input to behave.
    //This is one of the more common places a mistake can happen.
    //In our desktop launcher, we gave these arguments to the configuration:
    //   config.width = 80 * 8;
    //  config.height = 40 * 18;
    //Here, config.height refers to the total number of rows to be displayed on the screen.
    //We're displaying 32 rows of dungeon, then 8 more rows of text generation to show some tricks with language.
    //gridHeight is 32 because that variable will be used for generating the dungeon and handling movement within
    //the upper 32 rows. Anything that refers to the full height, which happens rarely and usually for things like
    //screen resizes, just uses gridHeight + 8. Next to it is gridWidth, which is 80 because we want 80 grid spaces
    //across the whole screen. cellWidth and cellHeight are 8 and 18, and match the multipliers for config.width and
    //config.height, but in this case don't strictly need to because we soon use a "Stretchable" font. While
    //gridWidth and gridHeight are measured in spaces on the grid, cellWidth and cellHeight are the pixel dimensions
    //of an individual cell. The font will look more crisp if the cell dimensions match the config multipliers
    //exactly, and the stretchable fonts (technically, distance field fonts) can resize to non-square sizes and
    //still retain most of that crispness.
    gridWidth = 80;//from ww w.  ja v  a 2  s.  com
    gridHeight = 24;
    cellWidth = 14;
    cellHeight = 21;
    // gotta have a random number generator. We can seed an RNG with any long we want, or even a String.
    rng = new RNG("SquidLib!");

    //Some classes in SquidLib need access to a batch to render certain things, so it's a good idea to have one.
    batch = new SpriteBatch();
    //Here we make sure our Stage, which holds any text-based grids we make, uses our Batch.
    stage = new Stage(new StretchViewport(gridWidth * cellWidth, (gridHeight + 8) * cellHeight), batch);
    // the font will try to load CM-Custom as an embedded bitmap font with a distance field effect.
    // this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used.
    display = new SquidLayers(gridWidth, gridHeight + 8, cellWidth, cellHeight,
            DefaultResources.getStretchableTypewriterFont());
    // a bit of a hack to increase the text height slightly without changing the size of the cells they're in.
    // this causes a tiny bit of overlap between cells, which gets rid of an annoying gap between vertical lines.
    // if you use '#' for walls instead of box drawing chars, you don't need this.
    display.setTextSize(cellWidth, cellHeight + 1);

    // this makes animations very fast, which is good for multi-cell movement but bad for attack animations.
    display.setAnimationDuration(0.03f);

    //These need to have their positions set before adding any entities if there is an offset involved.
    //There is no offset used here, but it's still a good practice here to set positions early on.
    display.setPosition(0, 0);

    //This uses the seeded RNG we made earlier to build a procedural dungeon using a method that takes rectangular
    //sections of pre-drawn dungeon and drops them into place in a tiling pattern. It makes good "ruined" dungeons.
    dungeonGen = new DungeonGenerator(gridWidth, gridHeight, rng);
    //uncomment this next line to randomly add water to the dungeon in pools.
    //dungeonGen.addWater(15);
    //decoDungeon is given the dungeon with any decorations we specified. (Here, we didn't, unless you chose to add
    //water to the dungeon. In that case, decoDungeon will have different contents than bareDungeon, next.)
    decoDungeon = dungeonGen.generate();
    //getBareDungeon provides the simplest representation of the generated dungeon -- '#' for walls, '.' for floors.
    bareDungeon = dungeonGen.getBareDungeon();
    //When we draw, we may want to use a nicer representation of walls. DungeonUtility has lots of useful methods
    //for modifying char[][] dungeon grids, and this one takes each '#' and replaces it with a box-drawing character.
    lineDungeon = DungeonUtility.hashesToLines(decoDungeon);
    //Coord is the type we use as a general 2D point, usually in a dungeon.
    //Because we know dungeons won't be incredibly huge, Coord performs best for x and y values less than 256, but
    // by default it can also handle some negative x and y values (-3 is the lowest it can efficiently store). You
    // can call Coord.expandPool() or Coord.expandPoolTo() if you need larger maps to be just as fast.
    cursor = Coord.get(-1, -1);
    // here, we need to get a random floor cell to place the player upon, without the possibility of putting him
    // inside a wall. There are a few ways to do this in SquidLib. The most straightforward way is to randomly
    // choose x and y positions until a floor is found, but particularly on dungeons with few floor cells, this can
    // have serious problems -- if it takes too long to find a floor cell, either it needs to be able to figure out
    // that random choice isn't working and instead choose the first it finds in simple iteration, or potentially
    // keep trying forever on an all-wall map. There are better ways! These involve using a kind of specific storage
    // for points or regions, getting that to store only floors, and finding a random cell from that collection of
    // floors. The two kinds of such storage used commonly in SquidLib are the "packed data" as short[] produced by
    // CoordPacker (which use very little memory, but can be slow, and are treated as unchanging by CoordPacker so
    // any change makes a new array), and GreasedRegion objects (which use slightly more memory, tend to be faster
    // on almost all operations compared to the same operations with CoordPacker, and default to changing the
    // GreasedRegion object when you call a method on it instead of making a new one). Even though CoordPacker
    // sometimes has better documentation, GreasedRegion is generally a better choice; it was added to address
    // shortcomings in CoordPacker, particularly for speed, and the worst-case scenarios for data in CoordPacker are
    // no problem whatsoever for GreasedRegion. CoordPacker is called that because it compresses the information
    // for nearby Coords into a smaller amount of memory. GreasedRegion is called that because it encodes regions,
    // but is "greasy" both in the fatty-food sense of using more space, and in the "greased lightning" sense of
    // being especially fast. Both of them can be seen as storing regions of points in 2D space as "on" and "off."

    // Here we fill a GreasedRegion so it stores the cells that contain a floor, the '.' char, as "on."
    GreasedRegion placement = new GreasedRegion(bareDungeon, '.');
    //player is, here, just a Coord that stores his position. In a real game, you would probably have a class for
    //creatures, and possibly a subclass for the player. The singleRandom() method on GreasedRegion finds one Coord
    // in that region that is "on," or -1,-1 if there are no such cells. It takes an RNG object as a parameter, and
    // if you gave a seed to the RNG constructor, then the cell this chooses will be reliable for testing. If you
    // don't seed the RNG, any valid cell should be possible.
    player = placement.singleRandom(rng);
    //This is used to allow clicks or taps to take the player to the desired area.
    toCursor = new ArrayList<Coord>(200);
    //When a path is confirmed by clicking, we draw from this List to find which cell is next to move into.
    awaitedMoves = new ArrayList<Coord>(200);
    //DijkstraMap is the pathfinding swiss-army knife we use here to find a path to the latest cursor position.
    //DijkstraMap.Measurement is an enum that determines the possibility or preference to enter diagonals. Here, the
    // MANHATTAN value is used, which means 4-way movement only, no diagonals possible. Alternatives are CHEBYSHEV,
    // which allows 8 directions of movement at the same cost for all directions, and EUCLIDEAN, which allows 8
    // directions, but will prefer orthogonal moves unless diagonal ones are clearly closer "as the crow flies."
    playerToCursor = new DijkstraMap(decoDungeon, DijkstraMap.Measurement.MANHATTAN);
    //These next two lines mark the player as something we want paths to go to or from, and get the distances to the
    // player from all walkable cells in the dungeon.
    playerToCursor.setGoal(player);
    playerToCursor.scan(null);

    //The next three lines set the background color for anything we don't draw on, but also create 2D arrays of the
    //same size as decoDungeon that store simple indexes into a common list of colors, using the colors that looks
    // up as the colors for the cell with the same x and y.
    bgColor = SColor.DARK_SLATE_GRAY;
    colorIndices = DungeonUtility.generatePaletteIndices(decoDungeon);
    bgColorIndices = DungeonUtility.generateBGPaletteIndices(decoDungeon);
    // this creates an array of sentences, where each imitates a different sort of language or mix of languages.
    // this serves to demonstrate the large amount of glyphs SquidLib supports.
    // there's no need to put much effort into understanding this section yet, and many games won't use the language
    // generation code at all. If you want to know what this does, the parameters are:
    // minimum words in a sentence, maximum words in a sentence, "mid" punctuation that can be after a word (like a
    // comma), "end" punctuation that can be at the end of a sentence, frequency of "mid" punctuation (the chance in
    // 1.0 that a word will have something like a comma appended after it), and the limit on how many chars to use.
    lang = new String[] {
            FakeLanguageGen.ENGLISH.sentence(5, 10, new String[] { ",", ",", ",", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.17, gridWidth - 4),
            FakeLanguageGen.GREEK_AUTHENTIC.sentence(5, 11, new String[] { ",", ",", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.2, gridWidth - 4),
            FakeLanguageGen.GREEK_ROMANIZED.sentence(5, 11, new String[] { ",", ",", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.2, gridWidth - 4),
            FakeLanguageGen.LOVECRAFT.sentence(3, 9, new String[] { ",", ",", ";" },
                    new String[] { ".", ".", "!", "!", "?", "...", "..." }, 0.15, gridWidth - 4),
            FakeLanguageGen.FRENCH.sentence(4, 12, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.17, gridWidth - 4),
            FakeLanguageGen.RUSSIAN_AUTHENTIC.sentence(6, 13, new String[] { ",", ",", ",", ",", ";", " -" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.25, gridWidth - 4),
            FakeLanguageGen.RUSSIAN_ROMANIZED.sentence(6, 13, new String[] { ",", ",", ",", ",", ";", " -" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.25, gridWidth - 4),
            FakeLanguageGen.JAPANESE_ROMANIZED.sentence(5, 13, new String[] { ",", ",", ",", ",", ";" },
                    new String[] { ".", ".", ".", "!", "?", "...", "..." }, 0.12, gridWidth - 4),
            FakeLanguageGen.SWAHILI.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.SOMALI.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.HINDI_ROMANIZED.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.ARABIC_ROMANIZED.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.NORSE.addModifiers(FakeLanguageGen.Modifier.SIMPLIFY_NORSE).sentence(4, 9,
                    new String[] { ",", ",", ",", ";", ";" }, new String[] { ".", ".", ".", "!", "?" }, 0.12,
                    gridWidth - 4),
            FakeLanguageGen.INUKTITUT.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.NAHUATL.sentence(4, 9, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?" }, 0.12, gridWidth - 4),
            FakeLanguageGen.FANTASY_NAME.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.22, gridWidth - 4),
            FakeLanguageGen.FANCY_FANTASY_NAME.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.22, gridWidth - 4),
            FakeLanguageGen.GOBLIN.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "?", "...", "..." }, 0.12, gridWidth - 4),
            FakeLanguageGen.ELF.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "?", "..." }, 0.22, gridWidth - 4),
            FakeLanguageGen.DEMONIC.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "!", "!", "..." }, 0.1, gridWidth - 4),
            FakeLanguageGen.INFERNAL.sentence(4, 8, new String[] { ",", ",", ",", ";", ";" },
                    new String[] { ".", ".", ".", "?", "?", "..." }, 0.22, gridWidth - 4),
            FakeLanguageGen.FRENCH.mix(FakeLanguageGen.JAPANESE_ROMANIZED, 0.65).sentence(5, 9,
                    new String[] { ",", ",", ",", ";" }, new String[] { ".", ".", ".", "!", "?", "?", "..." },
                    0.14, gridWidth - 4),
            FakeLanguageGen.ENGLISH.addAccents(0.5, 0.15).sentence(5, 10, new String[] { ",", ",", ",", ";" },
                    new String[] { ".", ".", ".", "!", "?", "..." }, 0.17, gridWidth - 4),
            // mixAll is useful when mixing many languages; it takes alternating languages and weights for
            // the preceding language, and doesn't care what order the pairs are given in (the mix method
            // does care, which can be confusing when more than two languages are mixed).
            FakeLanguageGen.mixAll(FakeLanguageGen.SWAHILI, 1.0, FakeLanguageGen.JAPANESE_ROMANIZED, 1.0,
                    FakeLanguageGen.FRENCH, 1.0, FakeLanguageGen.RUSSIAN_ROMANIZED, 1.0,
                    FakeLanguageGen.GREEK_ROMANIZED, 1.0, FakeLanguageGen.ENGLISH, 1.2, FakeLanguageGen.ELF,
                    1.0, FakeLanguageGen.LOVECRAFT, 0.75).sentence(5, 10, new String[] { ",", ",", ",", ";" },
                            new String[] { ".", ".", ".", "!", "?", "..." }, 0.2, gridWidth - 4), };

    // this is a big one.
    // SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse
    // (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both.
    // keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish
    // between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The
    // implementation here handles hjkl keys (also called vi-keys), numpad, arrow keys, and wasd for 4-way movement.
    // Shifted letter keys produce capitalized chars when passed to KeyHandler.handle(), but we don't care about
    // that so we just use two case statements with the same body, i.e. one for 'A' and one for 'a'.
    // You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the
    // path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger
    // the event when someone clicks.
    input = new SquidInput(new SquidInput.KeyHandler() {
        @Override
        public void handle(char key, boolean alt, boolean ctrl, boolean shift) {
            switch (key) {
            case SquidInput.UP_ARROW:
            case 'k':
            case 'w':
            case 'K':
            case 'W': {
                //-1 is up on the screen
                move(0, -1);
                break;
            }
            case SquidInput.DOWN_ARROW:
            case 'j':
            case 's':
            case 'J':
            case 'S': {
                //+1 is down on the screen
                move(0, 1);
                break;
            }
            case SquidInput.LEFT_ARROW:
            case 'h':
            case 'a':
            case 'H':
            case 'A': {
                move(-1, 0);
                break;
            }
            case SquidInput.RIGHT_ARROW:
            case 'l':
            case 'd':
            case 'L':
            case 'D': {
                move(1, 0);
                break;
            }
            case 'Q':
            case 'q':
            case SquidInput.ESCAPE: {
                Gdx.app.exit();
                break;
            }
            }
        }
    },
            //The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen
            //input and converts it to grid coordinates (here, a cell is 12 wide and 24 tall, so clicking at the
            // pixel position 15,51 will pass screenX as 1 (since if you divide 15 by 12 and round down you get 1),
            // and screenY as 2 (since 51 divided by 24 rounded down is 2)).
            new SquidMouse(cellWidth, cellHeight, gridWidth, gridHeight, 0, 0, new InputAdapter() {

                // if the user clicks and there are no awaitedMoves queued up, generate toCursor if it
                // hasn't been generated already by mouseMoved, then copy it over to awaitedMoves.
                @Override
                public boolean touchUp(int screenX, int screenY, int pointer, int button) {
                    if (awaitedMoves.isEmpty()) {
                        if (toCursor.isEmpty()) {
                            cursor = Coord.get(screenX, screenY);
                            //This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current
                            // player position to the position the user clicked on. The "PreScanned" part is an optimization
                            // that's special to DijkstraMap; because the whole map has already been fully analyzed by the
                            // DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player
                            // moves, we only need to do a fraction of the work to find the best path with that info.
                            toCursor = playerToCursor.findPathPreScanned(cursor);
                        }
                        awaitedMoves.addAll(toCursor);
                    }
                    return true;
                }

                @Override
                public boolean touchDragged(int screenX, int screenY, int pointer) {
                    return mouseMoved(screenX, screenY);
                }

                // causes the path to the mouse position to become highlighted (toCursor contains a list of Coords that
                // receive highlighting). Uses DijkstraMap.findPathPreScanned() to find the path, which is rather fast.
                @Override
                public boolean mouseMoved(int screenX, int screenY) {
                    if (!awaitedMoves.isEmpty())
                        return false;
                    if (cursor.x == screenX && cursor.y == screenY) {
                        return false;
                    }
                    cursor = Coord.get(screenX, screenY);
                    //This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current
                    // player position to the position the user clicked on. The "PreScanned" part is an optimization
                    // that's special to DijkstraMap; because the whole map has already been fully analyzed by the
                    // DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player
                    // moves, we only need to do a fraction of the work to find the best path with that info.

                    toCursor = playerToCursor.findPathPreScanned(cursor);
                    return false;
                }
            }));
    //Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT
    Gdx.input.setInputProcessor(new InputMultiplexer(stage, input));
    //You might be able to get by with the next line instead of the above line, but the former is preferred.
    //Gdx.input.setInputProcessor(input);
    // and then add display, our one visual component, to the list of things that act in Stage.
    stage.addActor(display);

}

From source file:com.idp.engine.App.java

@Override
 public void create() {

     if (com.idp.engine.base.Idp.app != null) {
         com.idp.engine.base.Idp.app.dispose();
     }/*from   www .ja  va  2s.  c om*/
     instance = this;
     com.idp.engine.base.Idp.app = this;
     com.idp.engine.base.Idp.input = new IdpInput();
     com.idp.engine.base.Idp.files = new com.idp.engine.base.IdpFiles();
     com.idp.engine.base.Idp.logger = null;
     initDp();
     com.idp.engine.base.Idp.input.startProcessing();

     Idp.input.setBackKeyProcessor(new InputAdapter() {
         public boolean keyDown(int keycode) {
             if (keycode == Input.Keys.BACK) {
                 try {
                     popScreen();
                 } catch (EmptyStackException ex) {
                     Gdx.app.exit();
                 }
                 return true;
             }
             return false;
         }
     });
     Idp.input.setCatchBackKey(true);
     Gdx.graphics.setContinuousRendering(false); // important to save battery

     dialogs = GDXDialogsSystem.install();
 }

From source file:com.jemchicomac.backfire.Backfire.java

License:Apache License

public void create() {
    stage = new Stage();
    Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));

    label = new Label("", skin);

    Table root = new Table(skin);
    root.setFillParent(true);/* w  w  w .  ja  va  2s .c  om*/
    root.setBackground(skin.getDrawable("default-pane"));
    root.debug().defaults().space(6);
    root.add(new TextButton("Button 1", skin));
    root.add(new TextButton("Button 2", skin)).row();
    root.add("Press spacebar to change the viewport:").colspan(2).row();
    root.add("Press 'F' for fullscreen and 'ESC' for exit").colspan(2).row();

    root.add(label).colspan(2);
    stage.addActor(root);

    // Setting up camera

    cam = new OrthographicCamera(VIRTUAL_WIDTH, VIRTUAL_HEIGHT);
    cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
    //cam.position.set(cam.viewportWidth, cam.viewportHeight, 0);
    //cam.update();

    //viewports = getViewports(stage.getCamera());

    viewports = getViewports(cam);

    names = getViewportNames();

    stage.setViewport(viewports.get(DEFAULT_POLICY));
    label.setText(names.get(DEFAULT_POLICY));

    spriteBatch = new SpriteBatch();

    cam.update();

    // Player

    loadPlayerTextures();

    // Input processor

    Gdx.input.setInputProcessor(new InputMultiplexer(new InputAdapter() {
        public boolean keyDown(int keycode) {
            if (keycode == Input.Keys.SPACE) {
                int index = (viewports.indexOf(stage.getViewport(), true) + 1) % viewports.size;
                label.setText(names.get(index));
                Viewport viewport = viewports.get(index);
                stage.setViewport(viewport);
                resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
            }

            if (keycode == Input.Keys.F) {
                Gdx.graphics.setDisplayMode(Gdx.graphics.getDesktopDisplayMode().width,
                        Gdx.graphics.getDesktopDisplayMode().height, true);
            }

            if (keycode == Input.Keys.A) {
                cam.zoom += 0.02;
            }
            if (keycode == Input.Keys.Q) {
                cam.zoom -= 0.02;
            }

            if (keycode == Keys.ESCAPE)
                Gdx.app.exit();

            return false;
        }
    }, stage));
}