3

I am writing a snake program in java that paints a series of rectangles. I don't understand how to delay my direction changes for blocks in order so that the snake rectangles change direction all at the same spot that the arrow key was hit. I need to wait within one method while the rest of the program continues to run. When an arrow key is pressed, it triggers this method to change the direction of my rectangles(u for up, d for down...)

`public void changeDirection(String dir)
{
    for(int i = 0; i<snakearray.size(); i++)
    {
     //checks to make sure youre not changing straight from l to r or u to d
        if(dir.equals("r")||dir.equals("l"))
        {
            if(//direction of currect element is up or down)
            //makes the current element of the array change to the new direction
            {snakearray.set(i, snakearray.get(i).newDirection(dir));}
        }
        else if(dir.equals("u")||dir.equals("d"))
        {
            if(//current element's direction is right or left)
            {snakearray.set(i, snakearray.get(i).newDirection(dir));}
        }
        //pause method but not game method needed here????
    }
}`

is there a way to implement the pause i need to? i've tried the thread.sleep(20) method but that pauses my entire program...

katelyn e
  • 31
  • 4

2 Answers2

1

Forget about creating a new thread only for one simple method. You want a timing that executes moving for example once a second, and you should change the way you are moving the snake.

First the timing:

swing.Timer:https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html Its very easy to use and it has a lot of funcionalities.

Or you can implement a very basic timing by measuring the time since the last move.

You will need a lastTime and a now variables.

now = currentTime();
if(now - lastTime > delay){
    moveSnakeParts();
    lastTime = currentTime();
}

Secondly you don't want to delay the parts of the snake. A snake has a head which you can control and a list of body parts. All you have to do is moving the head storing its previous position, moving first body part to heads previous position and storing first bodyparts previous position and so on... I hope you get it.

eldo
  • 1,327
  • 2
  • 16
  • 27
  • i have my program set up so that its flowing movement so the head like doesn't move by its length each time because that ended up looking too choppy, that's why i don't have the tail moving to the head's previous position becuase they would be almost entirely on top of one another – katelyn e Apr 13 '17 at 21:31
  • You dont have to move your snake by length still you can move the next piece of snakes position to the end of the heads last position. Lets say your snake pieces are 10 by 10 sqares and it moves by 1px. If heads bottom left is 0 0 then its bottom right is 10 0 and that will be the position of the first body piece after 1px movement to the left. Anyway you can create its movement in many ways but its Not sleeping what will solve your ploblem. – eldo Apr 14 '17 at 19:32
  • I suggest you to implement it the way like i answered and if you have problem with your desired movement ask one more question about it. – eldo Apr 14 '17 at 19:34
0

You can use a so called ScheduledExecutorService. This will allow you to execute your code in a separate Thread with a given delay.


Example:

  @Test
  public void test() throws ExecutionException, InterruptedException {
    final ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture<?> future = service.schedule(() -> changeDirection("r"), 2, TimeUnit.SECONDS);

    // Just for the test to wait until the direction change has been executed
    // In your code you would not need this if you want your program to continue
    future.get();
  }

  private void changeDirection(String dir) {
    System.out.println("Changing direction to " + dir);
    // Your code
  }

Explanation:

The code above executes your method with 2 seconds delay. The return value called future here is available to be able to track when the execution has been finished. If you use it, your program will wait until the execution is done.
As you do not want your main program to wait, just ignore/do not use the call future.get() and your main code will continue to execute without delay, only the scheduled method will be delayed.

JDC
  • 4,247
  • 5
  • 31
  • 74