I've implemented a teleport feature for my game and I would like some feedback on the way that I validate the user input. I am using the libGDX library.
When the player clicks the Teleport Menu button, a menu will pop up that has two TextFields pre-populated with zeros. The user can click the TextField to begin input, and then can input any string that they want to. Once the player clicks Teleport, the current Strings of the TextFields are retrieved and handed off to a method that turns them into valid integers.
Here is a screenshot of the Teleport Menu:
Here is the TeleportMenu
class, it is not too large:
public class TeleportMenu extends BZMenuTable {
private final NinePatch menuBackground;
private final MainGame game;
private final float stageWidth;
private final float stageHeight;
private TextField longitudeTextField;
private TextField latitudeTextField;
public TeleportMenu(Skin skin, Stage hudStage, NinePatch menuBackground, MainGame game, float stageWidth, float stageHeight) {
super(skin, hudStage);
this.menuBackground = menuBackground;
this.game = game;
this.stageWidth = stageWidth;
this.stageHeight = stageHeight;
}
@Override
public void build() {
TextButton teleportButton = new TextButton("Teleport", skin);
teleportButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
TeleportMenu.this.activateTeleport();
TeleportMenu.this.close();
}
});
this.menuTable.setBackground(new NinePatchDrawable(this.menuBackground));
this.menuTable.setPosition(this.stageWidth/10, this.stageHeight/8);
this.menuTable.setWidth((float)(this.stageWidth * 0.8));
this.menuTable.setHeight((float)(this.stageHeight * 0.6));
this.menuTable.add("Teleport");
this.menuTable.row();
this.menuTable.add("Latitude 0 - 50");
this.menuTable.row();
this.latitudeTextField = new TextField("0", skin);
this.menuTable.add(latitudeTextField);
this.menuTable.row();
this.menuTable.add("Longitude 0 - 50");
this.menuTable.row();
this.longitudeTextField = new TextField("0", skin);
this.menuTable.add(longitudeTextField);
this.menuTable.row();
this.menuTable.add(teleportButton).pad(10).width(this.stageWidth/5).height(this.stageHeight/12).fill();
}
private void activateTeleport() {
int xPos = this.processTextField(this.latitudeTextField.getText());
int yPos = this.processTextField(this.longitudeTextField.getText());
this.game.playerActivatedTeleport(xPos, yPos);
}
private int processTextField(String string) {
Integer position;
try {
position = Integer.parseInt(string);
} catch (Exception e) {
System.out.println("Invalid input");
position = 0;
}
if (position < 0) {
position = 0;
}
if (position >= World.WORLD_WIDTH) {
position = World.WORLD_WIDTH - 1; //because it is the index of an array
}
return position;
}
}
Specifically I am curious about the processTextField
method, but I am always interested in any kind of feedback.