#include #defi" /> #include #defi" /> #include #defi"/>

Why isnt my snake printing to the screen?

72 Views Asked by At

I'm writing snake using raylib and C yet m snake is not printing to the screen , Why?

#include "raylib.h"
#include <stdio.h>
#include <stdlib.h>

#define CELLSIZE 30
#define CELLCOUNT 25

Color green = {173, 204, 96, 255};
Color darkGreen = {43, 51, 24, 255};

typedef struct{
        int orit;
        Vector2 pos;
} cells;

int main(void){
        unsigned int Size = 3;

        cells* snake = malloc(sizeof * snake * Size);

        snake[0].pos.x = 6;
        snake[0].pos.y = 9;
        snake[1].pos.x = 5;
        snake[1].pos.y = 9;
        snake[2].pos.x = 4;
        snake[2].pos.y = 9;

        InitWindow(CELLSIZE * CELLCOUNT, CELLSIZE * CELLCOUNT, "retro snake");
        SetTargetFPS(60);

        Vector2 foodPos = {
                GetRandomValue(0, CELLCOUNT - 1),
                                             
        while (!WindowShouldClose())
        {
                BeginDrawing();
                ClearBackground(green);

                DrawRectangle(foodPos.x * CELLSIZE, foodPos.y * CELLSIZE, CELLSIZE, CELLSIZE, darkGreen);

                for (unsigned int i; i < Size; i++){

                        DrawRectangle(snake[i].pos.x * CELLSIZE, snake[i].pos.y * CELLSIZE, CELLSIZE, CELLSIZE, darkGreen);
                }

                EndDrawing();
        }

        CloseWindow();
        free(snake);

        return 0;
}             

Its really confusing, i was expecting it to be printed to the screen but all i get is this:

as you can see, the food prints yet the snake doesnt

I also use pointers as my snakes size is variable

2

There are 2 best solutions below

0
Flori On

Unsigned int i could be anything since in C variables don`t have a default value like in Java. So it could be anything. You have to initialize i to 0.

for (unsigned int i = 0; i < Size; i++) {
    DrawRectangle(snake[i].pos.x * CELLSIZE, snake[i].pos.y * CELLSIZE, CELLSIZE, CELLSIZE, darkGreen);
}
0
Shresth Pratap On

There is an issue with your loop in the main function. Specifically, you're missing the initialization of the loop counter variable, i. Without initializing i, the loop behavior is undefined, and it may not execute as you expected it to.

for (unsigned int i = 0; i < Size; i++) {
    DrawRectangle(snake[i].pos.x * CELLSIZE, snake[i].pos.y * CELLSIZE, CELLSIZE, CELLSIZE, darkGreen);
}

Here we initialized i = 0, so that the loop will start from the first index and display the segments of the snake.