List of usage examples for com.badlogic.gdx InputAdapter InputAdapter
InputAdapter
From source file:dhx.amidakuji.view.UIGameBuild.java
License:Open Source License
public UIGameBuild(BitmapFont bitmap, AmidakujiMain game) { this.batch = new SpriteBatch(); this.game = game; gameInputProcessor = new InputAdapter() { @Override// w w w .ja v a 2 s . c o m public boolean keyDown(int keycode) { if (!keyDown) { if (keycode == Input.Keys.R) { AmidakujiController.planAmidakuji(); AmidakujiController.calcAmidakuji(); return true; } else if (keycode == Input.Keys.S) { // TODO: shuffle (switch top texts among each other as // well as bottom texts) and calculate some amidakuji // and on random time stop calculating return true; } else if (keycode == Input.Keys.ESCAPE) { UIGameBuild.this.game.setScreen(UIGameBuild.this.game.getMenuBuild()); return true; } else if (keycode == Input.Keys.H) { if (showControls) { showControls = false; } else { showControls = true; } return true; } keyDown = true; } return false; } @Override public boolean keyUp(int keycode) { if (keyDown != false) { keyDown = false; return true; } return false; } @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) { if (!showScrollBar) { return false; } scroll = false; return true; } @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { if (!showScrollBar) { return false; } screenY = AmidakujiMain.height - screenY; // has to be converted, because of different y origins Rectangle rec = new Rectangle(sbX, sbY, sbWidth, sbHeight); if (rec.contains(screenX, screenY)) { scroll = true; } lastPosition = screenX; return true; } @Override public boolean touchDragged(int screenX, int screenY, int pointer) { if (!showScrollBar) { return false; } if (scroll) { // DESC-> on click and drag on scroll knob xOffset -= (screenX - lastPosition) / (amidakujiViewport / totalWidth); sbX += (screenX - lastPosition); } else { // DESC-> on click and drag NOT on scroll knob xOffset += (screenX - lastPosition); sbX -= (screenX - lastPosition) * (amidakujiViewport / totalWidth); } lastPosition = screenX; if ((xOffset) <= (totalWidth - amidakujiViewport) * -1f) { // DESC-> scroll to the right xOffset = (totalWidth - amidakujiViewport) * -1f; sbX = xOffset * (amidakujiViewport / totalWidth) * -1f; return false; } else if (xOffset > 0) { // DESC-> scroll to the left xOffset = 0; sbX = 0; return false; } return true; } }; }
From source file:es.eucm.ead.editor.utils.ImageBorderTracer.java
License:Open Source License
@Override public void create() { super.create(); Pixmap pm;/*from w w w .j ava 2s . c o m*/ pm = createSamplePixmap(300, 300, null); samplePixmap = new Texture(pm); for (Geometry g : GeometryUtils.findBorders(pm, .1, 2)) { red.add(GeometryUtils.jtsCoordsToGdx(g.getCoordinates())); } pm = openImagePixmap(); imagePixmap = new Texture(pm); for (Geometry g : GeometryUtils.findBorders(pm, .1, 2)) { Coordinate[] cs = g.getCoordinates(); for (Coordinate c : cs) { c.setCoordinate(new Coordinate(c.x, c.y)); } blue.add(GeometryUtils.jtsCoordsToGdx(cs)); } Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { int polygonsTouched = 0; for (Polygon polygon : blue) { if (polygon.contains(screenX, Gdx.graphics.getHeight() - screenY)) { polygonsTouched++; } } Gdx.app.log("ImageBorderTracer", "Blue polygon" + (polygonsTouched % 2 == 0 ? " not" : "") + " touched"); return false; } }); }
From source file:net.mostlyoriginal.blackjack.BlackjackGame.java
public BlackjackGame() { commander = new EventCommander(); phaseSystemsMap = new HashMap<BlackJackSystems, BaseBlackjackSystem>(); IGetPhaseFromId resolver = new IGetPhaseFromId() { @Override/*from w ww . j av a 2 s. c o m*/ public BaseBlackjackSystem system(BlackJackSystems name) { return phaseSystemsMap.get(name); } }; phaseSystemsMap.put(BlackJackSystems.CountCheck, new CountCheckSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.DealHidden, new DealHiddenSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.DealShown, new DealShownSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.PlayerChoice, new PlayerChoiceSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.CleanupSystem, new CleanupSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.UpdateWinnerPlayerSystem, new UpdateWinnerSystem(resolver)); phaseSystemsMap.put(BlackJackSystems.SelectNextPlayer, new SelectNextPlayerSystem(resolver, 2)); cardgameFramework = CardgameFramework.builder().victoryChecker(new IVictoryDecider() { @Override public boolean isVictoryCondition() { return mGameEnd.get(); } }).phaseSystems(new ArrayList<BasePhaseSystem>(phaseSystemsMap.values())) .startingSystem(phaseSystemsMap.get(BlackJackSystems.SelectNextPlayer)).eventCommander(commander) .build(); InputMultiplexer inputMultiplexer = new InputMultiplexer(new InputAdapter() { @Override public boolean keyDown(int keycode) { if (keycode == Input.Keys.ESCAPE) { mGameEnd.set(true); } return super.keyDown(keycode); } }); Gdx.input.setInputProcessor(inputMultiplexer); initBlackJack(); }
From source file:org.destinationsol.menu.InputMapControllerScreen.java
License:Apache License
@Override public void setEnterNewKey(boolean newKey) { isEnterNewKey = newKey;/*from w w w. j av a 2 s . c o m*/ // Cancel the key input if (!isEnterNewKey) { Gdx.input.setInputProcessor(null); Controllers.clearListeners(); } else { // Capture the new key input // Keyboard items Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(int keycode) { // Don't capture the escape key if (keycode == Input.Keys.ESCAPE) return true; if (selectedIndex >= controllerItems) { removeDuplicateKeys(keycode); InputConfigItem item = itemsList.get(selectedIndex); item.setInputKey(Input.Keys.toString(keycode)); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; return true; // return true to indicate the event was handled } }); // Controller items // setup the listener that prints events to the console Controllers.addListener(new ControllerListener() { public int indexOf(Controller controller) { return Controllers.getControllers().indexOf(controller, true); } @Override public void connected(Controller controller) { } @Override public void disconnected(Controller controller) { } @Override public boolean buttonDown(Controller controller, int buttonIndex) { // Do nothing on button down - register the button up event return true; } @Override public boolean buttonUp(Controller controller, int buttonIndex) { System.out.println("#" + indexOf(controller) + ", button " + buttonIndex + " up"); if (selectedIndex < controllerItems) { removeDuplicateButtons(buttonIndex); InputConfigItem item = itemsList.get(selectedIndex); item.setIsAxis(false); item.setControllerInput(buttonIndex); item.setInputKey("Button: " + buttonIndex); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; return true; // return true to indicate the event was handled } @Override public boolean axisMoved(Controller controller, int axisIndex, float value) { System.out.println("#" + indexOf(controller) + ", axis " + axisIndex + ": " + value); if (value > 0.5f || value < -0.5f) { if (selectedIndex < controllerItems) { InputConfigItem item = itemsList.get(selectedIndex); item.setIsAxis(true); item.setControllerInput(axisIndex); item.setInputKey("Axis: " + axisIndex); itemsList.set(selectedIndex, item); } Gdx.input.setInputProcessor(null); Controllers.clearListeners(); isEnterNewKey = false; } return true; } @Override public boolean povMoved(Controller controller, int povIndex, PovDirection value) { return false; } @Override public boolean xSliderMoved(Controller controller, int sliderIndex, boolean value) { return false; } @Override public boolean ySliderMoved(Controller controller, int sliderIndex, boolean value) { return false; } @Override public boolean accelerometerMoved(Controller controller, int accelerometerIndex, Vector3 value) { return false; } }); } }
From source file:org.destinationsol.menu.InputMapKeyboardScreen.java
License:Apache License
@Override public void setEnterNewKey(boolean newKey) { isEnterNewKey = newKey;/*from www . j a va2 s. c om*/ // Cancel the key input if (!isEnterNewKey) { Gdx.input.setInputProcessor(null); } else { // Capture the new key input Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyUp(int keycode) { // Don't capture the escape key if (keycode == Input.Keys.ESCAPE) return true; removeDuplicateKeys(keycode); InputConfigItem item = itemsList.get(selectedIndex); item.setInputKey(Input.Keys.toString(keycode)); itemsList.set(selectedIndex, item); Gdx.input.setInputProcessor(null); isEnterNewKey = false; return true; // return true to indicate the event was handled } }); } }
From source file:scenes.Chat.java
private void openChatWindow() { previousProcessor = Gdx.input.getInputProcessor(); enteredMessage = ""; isTyping = true;//from w w w.ja v a 2 s . c o m Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyDown(int keyCode) { if (keyCode == Input.Keys.ENTER) { GameClient.sendChatMessage(enteredMessage); enteredMessage = ""; isTyping = false; Gdx.input.setInputProcessor(previousProcessor); } return true; } @Override public boolean keyTyped(char character) { if (character == '\b' && enteredMessage.length() > 0) enteredMessage = enteredMessage.substring(0, enteredMessage.length() - 1); if (character == '\b' || character == '\t' || character == '\n' || character == '\r' || character == '\f' || character == '`' || character == '\u0000' || enteredMessage.length() >= 30) return true; enteredMessage += character; return true; } }); }
From source file:scenes.MatchScreen.java
@Override public void create() { xOffset = Gdx.graphics.getWidth() / 2 - (match.getMap().getWidth() / 2); yOffset = Gdx.graphics.getHeight() / 2 - (match.getMap().getHeight() / 2) + 100; layout = new GlyphLayout(); shapeRenderer = new ShapeRenderer(); shapeRenderer.setAutoShapeType(true); batch = new SpriteBatch(); //img = new Texture("Badlogic.jpg"); FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/MunroSmall.ttf")); FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter(); parameter.size = 35;/*from w w w. j ava2 s . c o m*/ font30 = generator.generateFont(parameter); // font size 12 pixels font30.setColor(CircleColors.black); parameter.size = 20; font20 = generator.generateFont(parameter); // font size 12 pixels font20.setColor(CircleColors.black); generator.dispose(); //Box2D float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); camera = new OrthographicCamera(); camera.setToOrtho(false, w / SCALE, h / SCALE); matrix = new Matrix4(); matrix.scale(w, h, 1f); if (match.GetWorld() == null) { match.SetWorld(new World(new Vector2(0, 0), false)); } //b2dr = new Box2DDebugRenderer(); batch = new SpriteBatch(); new Timer().schedule(new TimerTask() { @Override public void run() { timeLeft--; } }, 1000, 1000); Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyDown(int keyCode) { if (keyCode == Input.Keys.W) { // goforward SendMessage("pressed goforward"); } if (keyCode == Input.Keys.A) { // strafeleft SendMessage("pressed strafeleft"); } if (keyCode == Input.Keys.S) { // gobackward SendMessage("pressed gobackward"); } if (keyCode == Input.Keys.D) { // strafeleft SendMessage("pressed straferight"); } if (keyCode == Input.Keys.UP || keyCode == Input.Keys.SPACE || keyCode == Input.Keys.NUMPAD_8) { // attack SendMessage("pressed attack"); } if (keyCode == Input.Keys.LEFT || keyCode == Input.Keys.NUMPAD_4) { // turnleft SendMessage("pressed turnleft"); } if (keyCode == Input.Keys.RIGHT || keyCode == Input.Keys.NUMPAD_6) { // turnright SendMessage("pressed turnright"); } if (keyCode == Input.Keys.ESCAPE) { //overlay -> pausescreen Config.overlay = new PauseScreen(); } return true; } @Override public boolean keyUp(int keyCode) { if (keyCode == Input.Keys.W) { // goforward SendMessage("released goforward"); } if (keyCode == Input.Keys.A) { // strafeleft SendMessage("released strafeleft"); } if (keyCode == Input.Keys.S) { // gobackward SendMessage("released gobackward"); } if (keyCode == Input.Keys.D) { // strafeleft SendMessage("released straferight"); } if (keyCode == Input.Keys.UP || keyCode == Input.Keys.SPACE || keyCode == Input.Keys.NUMPAD_8) { // attack SendMessage("released attack"); } if (keyCode == Input.Keys.LEFT || keyCode == Input.Keys.NUMPAD_4) { // turnleft SendMessage("released turnleft"); } if (keyCode == Input.Keys.RIGHT || keyCode == Input.Keys.NUMPAD_6) { // turnright SendMessage("released turnright"); } if (keyCode == Input.Keys.Q) { // previousWeapon SendMessage("released previousWeapon"); } if (keyCode == Input.Keys.E) { // nextWeapon SendMessage("released nextWeapon"); } return true; } }); if (match.tUpdate != null) { match.tUpdate.interrupt(); } if (match.tRefresh != null) { match.tRefresh.interrupt(); } match.tUpdate = new Thread() { public void run() { try { while (true) { match.Update(); Thread.sleep(17); } } catch (InterruptedException ex) { } } }; match.tRefresh = new Thread() { public void run() { try { while (true) { GameClient.sendMatch(match); Thread.sleep(250); } } catch (InterruptedException ex) { } } }; if (match.getPlayers().get(0).getName().equals(Config.username)) { match.tRefresh.start(); } match.tUpdate.start(); }
From source file:scenes.SplashScreen.java
@Override public void create() { layout = new GlyphLayout(); batch = new SpriteBatch(); //initialize fonts FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/MunroSmall.ttf")); FreeTypeFontParameter parameter = new FreeTypeFontParameter(); parameter.size = 60;/* w ww. j a v a2 s. c o m*/ font60 = generator.generateFont(parameter); // font size 12 pixels font60.setColor(Color.BLACK); parameter.size = 40; font30 = generator.generateFont(parameter); // font size 12 pixels font30.setColor(0.38f, 0.38f, 0.38f, 1f); generator.dispose(); // don't forget to dispose to avoid memory leaks! fade = new FontFade(font30); Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyDown(int keyCode) { Config.page = new EnterName(); return true; } }); }
From source file:scenes.TutorialMatchScreen.java
@Override public void create() { xOffset = Gdx.graphics.getWidth() / 2 - (match.getMap().getWidth() / 2); yOffset = Gdx.graphics.getHeight() / 2 - (match.getMap().getHeight() / 2) + 100; layout = new GlyphLayout(); shapeRenderer = new ShapeRenderer(); shapeRenderer.setAutoShapeType(true); batch = new SpriteBatch(); //img = new Texture("Badlogic.jpg"); FreeTypeFontGenerator generator = new FreeTypeFontGenerator(Gdx.files.internal("fonts/MunroSmall.ttf")); FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter(); parameter.size = 35;//from w w w .jav a2 s . c o m font30 = generator.generateFont(parameter); // font size 12 pixels font30.setColor(CircleColors.black); parameter.size = 20; font20 = generator.generateFont(parameter); // font size 12 pixels font20.setColor(CircleColors.black); generator.dispose(); //Box2D float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); camera = new OrthographicCamera(); camera.setToOrtho(false, w / SCALE, h / SCALE); matrix = new Matrix4(); matrix.scale(w, h, 1f); if (match.GetWorld() == null) { match.SetWorld(new World(new Vector2(0, 0), false)); } //b2dr = new Box2DDebugRenderer(); batch = new SpriteBatch(); new Timer().schedule(new TimerTask() { @Override public void run() { timeLeft--; } }, 1000, 1000); Gdx.input.setInputProcessor(new InputAdapter() { @Override public boolean keyDown(int keyCode) { if (keyCode == Input.Keys.W) { // goforward moveForward(); SendMessage("pressed goforward"); } if (keyCode == Input.Keys.A) { // strafeleft strafeLeft(); SendMessage("pressed strafeleft"); } if (keyCode == Input.Keys.S) { // gobackward moveBackwards(); SendMessage("pressed gobackward"); } if (keyCode == Input.Keys.D) { // strafeleft strafeRight(); SendMessage("pressed straferight"); } if (keyCode == Input.Keys.UP || keyCode == Input.Keys.SPACE || keyCode == Input.Keys.NUMPAD_8) { // attack shoot(); SendMessage("pressed attack"); } if (keyCode == Input.Keys.LEFT || keyCode == Input.Keys.NUMPAD_4) { // turnleft turnLeft(); SendMessage("pressed turnleft"); } if (keyCode == Input.Keys.RIGHT || keyCode == Input.Keys.NUMPAD_6) { // turnright turnRight(); SendMessage("pressed turnright"); } if (keyCode == Input.Keys.ESCAPE) { //overlay -> pausescreen Config.overlay = new PauseScreen(); } return true; } @Override public boolean keyUp(int keyCode) { if (keyCode == Input.Keys.W) { // goforward SendMessage("released goforward"); } if (keyCode == Input.Keys.A) { // strafeleft SendMessage("released strafeleft"); } if (keyCode == Input.Keys.S) { // gobackward SendMessage("released gobackward"); } if (keyCode == Input.Keys.D) { // strafeleft SendMessage("released straferight"); } if (keyCode == Input.Keys.UP || keyCode == Input.Keys.SPACE || keyCode == Input.Keys.NUMPAD_8) { // attack SendMessage("released attack"); } if (keyCode == Input.Keys.LEFT || keyCode == Input.Keys.NUMPAD_4) { // turnleft SendMessage("released turnleft"); } if (keyCode == Input.Keys.RIGHT || keyCode == Input.Keys.NUMPAD_6) { // turnright SendMessage("released turnright"); } if (keyCode == Input.Keys.Q) { // previousWeapon SendMessage("released previousWeapon"); } if (keyCode == Input.Keys.E) { // nextWeapon SendMessage("released nextWeapon"); } return true; } }); if (match.tUpdate != null) { match.tUpdate.interrupt(); } if (match.tRefresh != null) { match.tRefresh.interrupt(); } match.tUpdate = new Thread() { public void run() { try { while (true) { match.Update(); Thread.sleep(17); } } catch (InterruptedException ex) { } } }; match.tRefresh = new Thread() { public void run() { try { while (true) { GameClient.sendMatch(match); Thread.sleep(250); } } catch (InterruptedException ex) { } } }; if (match.getPlayers().get(0).getName().equals(Config.username)) { match.tRefresh.start(); } match.tUpdate.start(); moveForward(); }
From source file:squidpony.gdx.examples.BasicDemo.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 . j av a2 s .co m*/ 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<>(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<>(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.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.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), FakeLanguageGen.SWAHILI.mix(FakeLanguageGen.JAPANESE_ROMANIZED, 0.5) .mix(FakeLanguageGen.FRENCH, 0.35).mix(FakeLanguageGen.RUSSIAN_ROMANIZED, 0.25) .mix(FakeLanguageGen.GREEK_ROMANIZED, 0.2).mix(FakeLanguageGen.ENGLISH, 0.15) .mix(FakeLanguageGen.FANCY_FANTASY_NAME, 0.12).mix(FakeLanguageGen.LOVECRAFT, 0.1) .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); //findPathPreScanned includes the current cell (goal) by default, which is helpful when // you're finding a path to a monster or loot, and want to bump into it, but here can be // confusing because you would "move into yourself" as your first move without this. // Getting a sublist avoids potential performance issues with removing from the start of an // ArrayList, since it keeps the original list around and only gets a "view" of it. if (!toCursor.isEmpty()) toCursor = toCursor.subList(1, toCursor.size()); } 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); //findPathPreScanned includes the current cell (goal) by default, which is helpful when // you're finding a path to a monster or loot, and want to bump into it, but here can be // confusing because you would "move into yourself" as your first move without this. // Getting a sublist avoids potential performance issues with removing from the start of an // ArrayList, since it keeps the original list around and only gets a "view" of it. if (!toCursor.isEmpty()) toCursor = toCursor.subList(1, toCursor.size()); 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); }