Question

I am writing a snake game in Java. As part of the game I have to randomly allocate a token that the snake will "eat" to increment the score. So here I am using a random generator, but in order not to generate a token within the body of the snake, I'm using this logic:

token_x = (tokenPositionGenerator.nextInt(40)*10)+30;
token_y = (tokenPositionGenerator.nextInt(40)*10)+30;

// check if token is generated in place of snake head

if (token_x == head_x || token_y == head_y)
{
    generateNewToken();
}

// check if token is generated within rest of snakes body
for (int i=0;i<tail_x.size();i++){
    if (token_x == tail_x.get(i) || token_y == tail_y.get(i))
    {
        generateNewToken();
    }
}
  • head_x, head_y is (x,y) position of snake head.
  • tail_x and tail_y are lists containing (x,y) positions of tail objects.
  • generateNewToken() is recursively calling the method.

Now when a token is generated, within the snake's body, I get a stackoverflow exception. Not sure how to avoid that.

Any thoughts on this, maybe I could achieve with a different logic?

Was it helpful?

Solution

I would suggest that you rewrite your code and solve the problem without recursion - as it is not needed here.

If I understood you right, you a generating tokens at randomized positions and check if the snake (head or tail) is already occupying this location.

Here is how I would try to solve your task

  • Generate a random token
  • Check if head or tail positions match the tokens position
  • if yes, re-generate the token (while-loop?)
  • if no, you are finished

hmm another question: are your checks correct? What would you check to see if head and token are at the same position in x/y-ccordinates? At the moment you are checking if either the x-coordinate is the same (head and token are on the same row) or the y-coordinate. But both must match, or? So I would replace the conditional or || by a conditional and &&.

OTHER TIPS

You are missing a base case that exits the recursive method. Without a base case your method will recursively call itself and never terminate until the machine becomes overwhelmed. I suspect your head check is the base case.

Try this:

if (token_x == head_x || token_y == head_y)
{
  return;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top