Sorry for unclear title, but I'm trying to make snake in python using pygame, and i currently have two variables, x and y, that determine the position of the head of the snake. I need to find what the values of these variables were ten ticks ago so i can replace the tail with the background color. How ca i do that?
Asked
Active
Viewed 29 times
1 Answers
0
What I recommend is that you keep a list of points that describes the blocks/points the snake is currently occupying(i.e. the places the head has been within a certain amount of time). When it moves, remove from the back(the oldest element) and replace the tail with the background color, then add a new element to the front with the current direction. This way would need a current direction, so you know what point the snake head goes to.
Incomplete example:
def move(snake, curDir, speed):
for i in range(speed): #speed is the amount it moves
# repaint tail with background, snake[i] is each point to remove
snake = snake[speed:] # the back is no longer occupied
x_offset = ? #determine offset using curDir
y_offset = ?
for i in range(speed):
snake.append((snake[-1]+x_offset, snake[-1]+y_offset)) # the head moves
# paint each new point/block with the snake color
return snake # python is weird for pass-by-references
snake = [(1,2), (1,3), (1,4)] #where all the parts are
curDir = "up"
speed = 1
snake = move(snake, curDir, speed) # changes snake to [(1,3), (1,4), (1,5)]
Note that the partial code I showed does not say anything about it hitting stuff, like walls or apples, and if an apple is eaten, you have a few options:
- Wait until the snake moves, then just don't remove the tail.
- Extend the tail backwards(what happens if it hits something?).
- Keep a entire list of the positions the snake was in, then go look for the newest unoccupied ones.
kenntnisse
- 379
- 1
- 11