Skip to content

Instantly share code, notes, and snippets.

@Ratstail91
Created October 13, 2013 04:06
Show Gist options
  • Save Ratstail91/6958065 to your computer and use it in GitHub Desktop.
Save Ratstail91/6958065 to your computer and use it in GitHub Desktop.
The slither algorithm, as outlined in this video: http://youtu.be/Gx5D09s5X6U This is not a valid language, it's just a simple pseudocode outline.
enum Turn:
left, right, straight
end
enum Direction:
north, south, east, west
end
class Segment:
Segment* next = null,
Turn turn,
Direction dir = north
int x = 0
int y = 0
end
--given the parent's direction and this one's turn, determine a new direction
Direction calcDirection(Direction d, Turn t):
switch(d):
north:
switch(t):
left: return west
right: return east
straight: return north
end
south:
switch(t):
left: return east
right: return west
straight: return south
end
east:
switch(t):
left: return south
right: return north
straight: return east
end
west:
switch(t):
left: return north
right: return south
straight: return west
end
end
end
--given the parent's position, direction & this one's turn, determine new position
int, int calcPosition(int x, int y, Direction pDir, Turn t)
switch(pDir):
north:
switch(t):
left: return x-1, y
right: return x+1, y
straight: return x, y-1
end
south:
switch(t):
left: return x+1, y
right: return x-1, y
straight: return x, y+1
end
east:
switch(t):
left: return x, y-1
right: return x, y+1
straight: return x+1, y
end
west:
switch(t):
left: return x, y+1
right: return x, y-1
straight: return x-1, y
end
end
end
--add a new segment to the end of the snake (takes the snake's head as the parameter)
int addNewSegment(Segment* node, Turn t):
if (node->next != null):
return 1 + addNewSegment(node->next, t)
end
--create the new segment
node->next = new Segment
node->next->turn = t
node->next->dir = calcDirection(node->dir, node->next->t)
node->next->x, node->next->y = calcPosition(node->x, node->y, node->dir, node->next->turn)
return 1
end
--check to see if the existing snake is valid (doesn't cross itself)
bool checkValid(Segment* node):
static bool grid[int][int] = {false} --a static, infinite, 2D grid of booleans, who's members default to false
if (grid[node->x][node->y]):
return false --the snake crosses itself
else:
grid[node->x][node->y] = true
if (node->next == null):
return true --reached the end of the snake without crossing itself
end
return checkValid(node->next)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment