Snake Game
This is a complete, playable version of the classic Snake game implemented in Godot 4. The core innovation of this project is using GDScript to manage all the game logic (movement, collision, growth, and food placement) while offloading the entire rendering of the grid, snake, and food to a single, optimized CanvasItem Shader.
The GDScript efficiently calculates the game state (a list of grid coordinates) and passes this data as uniform arrays to the shader every frame. The shader then determines the color of each pixel based on whether it falls on a food position, a snake segment, or the background.
Adjustable Uniforms (Shader Parameters):
Shader code
shader_type canvas_item;
uniform vec2 board_size = vec2(30.0, 25.0);
uniform vec2 snake_body[512];
uniform int snake_length;
uniform vec2 food_pos;
uniform bool game_over;
uniform vec4 COLOR_FONDO;
uniform vec4 COLOR_SERPIENTE;
uniform vec4 COLOR_COMIDA;
const vec4 COLOR_GAME_OVER = vec4(1.0, 1.0, 1.0, 0.5);
void fragment() {
ivec2 grid_uv = ivec2(UV * board_size);
vec4 final_color = COLOR_FONDO;
for (int i = 0; i < snake_length; i++) {
if (grid_uv == ivec2(snake_body[i])) {
final_color = COLOR_SERPIENTE;
break;
}
}
if (grid_uv == ivec2(food_pos)) {
final_color = COLOR_COMIDA;
}
if (game_over) {
final_color = mix(final_color, COLOR_GAME_OVER, COLOR_GAME_OVER.a);
}
COLOR = final_color;
}
