Question

I'm writing a snake game in TI-Basic, and every time I move I need to see if the head of the snake has hit any point in the tail. The tail is stored as a circular list-based queue, and I can add the beginning and end in constant time.

The only hard part is that I have to do something similar to this on every iteration: (S = Size of the list)

For(I,1,S)
    If X=LX(I) and Y=LY(I)
    Then
        Disp "GAME OVER"
        Return
    End
End

It's a fairly short loop, but it takes forever even on a list of 10 items. I tried the sequence way:

If sum(seq(X=LX(I) and Y=LY(I),I,1,S))
...

The only other optimization I can think of is to not check values for N to N+2 (because the first part of your tail that's possible to hit is at N+3), but that just puts off the problem after 4 points, and having the game unplayable with 14 points is no better than being unplayable after 10 points.

Using assembly isn't an option because I don't have a link cable (or the desire to write assembly).

Was it helpful?

Solution

Never used TI-Basic...

but how about also storing a 2D array of the game board. Each element in that array indicates if the snake is present. When you move forward, set the value of the array at the head point, and clear the value at the old tail end point. Then to test for collision, you can just do one lookup into the 2D array.

OTHER TIPS

The entire block:

For(I,1,S)
    If X=LX(I) and Y=LY(I)
    Then
        Disp "GAME OVER"
        Return
    End
End

can be replaced with:

If sum(X=LX and Y=LY)
Then
    Disp "Game Over"
    Return
End

X=LX applies the test piecewise to every element of LX, and the same goes for Y=LY. The sum() checks if there is a 1 in the intersection of the two lists.

What I did, when I was programming Snake, was to check if the pixel in front of the snake was on. If it was, I would check if this pixel is the "food" pixel, otherwise, the game would stop.

Example, with I and J being head and tail positions, (F, G) being the direction of the snake, and (M, N) being the food.

if Pxl-Test(I+F, J+G) #pixel in front of snake
then
if I+F=M and J+G=N
stop
end

Much more memory-conservant than a 2D array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top