Snake Game in C
Below is a simple implementation of the Snake game in C. This console-based version captures the basic mechanics of the Snake game. Copy and paste this code and run it!
// Include stdio.h, conio.h, stdlib.h and windows.h #include int gameover, score; int x, y, fruitX, fruitY, flag; int width = 20; int height = 10; int tailX[100], tailY[100]; int nTail; void setup() { gameover = 0; // Initial position of the snake x = height / 2; y = width / 2; // Initial position of the fruit fruitX = rand() % height; fruitY = rand() % width; score = 0; // Initialize score to 0 } void draw() { system("cls"); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { if (i == 0 || i == height - 1 || j == 0 || j == width - 1) { printf("#"); } else if (i == x && j == y) { printf("O"); } else if (i == fruitX && j == fruitY) { printf("F"); } else { int isTail = 0; for (int k = 0; k < nTail; k++) { if (tailX[k] == i && tailY[k] == j) { printf("o"); isTail = 1; } } if (!isTail) printf(" "); } } printf("\n"); } printf("Score:%d", score); printf("\n"); } void input() { if (_kbhit()) { switch (_getch()) { case 'a': flag = 1; break; case 's': flag = 2; break; case 'd': flag = 3; break; case 'w': flag = 4; break; case 'x': gameover = 1; break; } } } void algorithm() { Sleep(0.01); int prevX = tailX[0]; int prevY = tailY[0]; int prev2X, prev2Y; tailX[0] = x; tailY[0] = y; for (int i = 1; i < nTail; i++) { prev2X = tailX[i]; prev2Y = tailY[i]; tailX[i] = prevX; tailY[i] = prevY; prevX = prev2X; prevY = prev2Y; } switch (flag) { case 1: y--; break; case 2: x++; break; case 3: y++; break; case 4: x--; break; default: break; } if (x < 0 || x > height || y < 0 || y > width) gameover = 1; for (int i = 0; i < nTail; i++) { if (tailX[i] == x && tailY[i] == y) gameover = 1; } if (x == fruitX && y == fruitY) { score += 10; fruitX = rand() % height; fruitY = rand() % width; nTail++; } } int main() { int m, n; setup(); while (!gameover) { draw(); input(); algorithm(); } return 0; }
Note that these functions are specific to the Windows environment. If you are on a different platform, you may need to find alternatives for handling keyboard input.