I am writing a simple ascii game in java. My main loop has a tickrate set to once every 10 seconds, which calls a KeyListener attacked to the JTextArea that the game is displayed in. The KeyListener decides how the game gets updated based on what the user input was.
The delta time for the tick has to be set really high, otherwise instead of moving one space at a time, my character will move 2 or 3 or up to the entire x or y distance in a single click. Also, as the game runs longer, the character begins skipping places anyways, as if the tick rate has been decreased.
Here is my main game loop logic.
long startLoopTime = Calendar.getInstance().getTimeInMillis();
long updateLoopTime = Calendar.getInstance().getTimeInMillis();
boolean firstLoop = true;
while (true) { // keep running
startLoopTime = Calendar.getInstance().getTimeInMillis();
long tickCheck = startLoopTime - updateLoopTime;
if(firstLoop || tickCheck > 10000)
{
firstLoop = false;
listener(board, player, map);
updateLoopTime = Calendar.getInstance().getTimeInMillis();
}
}
Going through debug mode, I can see that the tick check is always > 10,000 when entering the conditional, and takes about 10 seconds to get there. However, even when the game is not in the tick check, the KeyListener is still active.
Here is my KeyListener code:
public static void listener (JTextArea board, Player player, Map map)
{
board.addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e){
Map reMap = new Map();
switch (e.getKeyCode()){
case KeyEvent.VK_W:
if(player.getInInventory())
{
//do some stuff
}
else{
reMap = moveMapUp(map, player);
board.setText(map.getMapString());
}
return;
case KeyEvent.VK_S:
if(player.getInInventory())
{
//do some stuff
}
else{
reMap = moveMapDown(map, player);
board.setText(map.getMapString());
}
return;
case KeyEvent.VK_A:
if(player.getInInventory())
{
//do some stuff
}
else{
reMap = moveMapToLeft(map, player);
board.setText(map.getMapString());
}
return;
case KeyEvent.VK_D:
if(player.getInInventory())
{
//do some stuff
}
else{
reMap = moveMapToRight(map, player);
board.setText(map.getMapString());
}
return;
case KeyEvent.VK_I:
if(!player.getInInventory()){
board.setText(inventoryString(player));
player.setInInventory(true);
}
else{
board.setText(map.getMapString());
player.setInInventory(false);
}
return;
case KeyEvent.VK_SPACE:
if(player.getInInventory())
{
//do some stuff
}
else
{
interact(map, player);
}
}
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
});
}
I dont really understand why the game is able to update more frequently than the tickrate, while still being tied to it. I also dont understand why as the game goes on, the apparent tick rate seems to drop, and my character begins speeding across the map on a single key press, instead of just moving one space like it had before. Any help or explanations would be appreciated.