#include
#include
#include
#include
#define WIDTH 20
#define HEIGHT 20
#define UP 1
#define DOWN 2
#define LEFT 3
#define RIGHT 4
int snakeX[100], snakeY[100];
int snakeLength;
int foodX, foodY;
int direction;
int gameOver;
void gotoxy(int x, int y) {
COORD coord;
coord.X = x;
coord.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void initializeGame() {
snakeLength = 1;
snakeX[0] = WIDTH / 2;
snakeY[0] = HEIGHT / 2;
direction = RIGHT;
gameOver = 0;
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
void drawBoard() {
system("cls");
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("n");
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
if (j == 0) {
printf("#");
}
if (i == snakeY[0] && j == snakeX[0]) {
printf("O");
} else if (i == foodY && j == foodX) {
printf("@");
} else {
int isBodyPart = 0;
for (int k = 1; k < snakeLength; k++) {
if (i == snakeY[k] && j == snakeX[k]) {
printf("o");
isBodyPart = 1;
}
}
if (!isBodyPart) {
printf(" ");
}
}
if (j == WIDTH - 1) {
printf("#");
}
}
printf("n");
}
for (int i = 0; i < WIDTH + 2; i++) {
printf("#");
}
printf("n");
}
void updateSnakePosition() {
for (int i = snakeLength - 1; i > 0; i--) {
snakeX[i] = snakeX[i - 1];
snakeY[i] = snakeY[i - 1];
}
switch (direction) {
case UP:
snakeY[0]--;
break;
case DOWN:
snakeY[0]++;
break;
case LEFT:
snakeX[0]--;
break;
case RIGHT:
snakeX[0]++;
break;
}
}
void generateFood() {
foodX = rand() % WIDTH;
foodY = rand() % HEIGHT;
}
void checkCollision() {
if (snakeX[0] < 0 || snakeX[0] >= WIDTH || snakeY[0] < 0 || snakeY[0] >= HEIGHT) {
gameOver = 1;
}
for (int i = 1; i < snakeLength; i++) {
if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
gameOver = 1;
}
}
if (snakeX[0] == foodX && snakeY[0] == foodY) {
snakeLength++;
generateFood();
}
}
void updateDirection() {
if (_kbhit()) {
switch (_getch()) {
case 'w':
if (direction != DOWN) direction = UP;
break;
case 's':
if (direction != UP) direction = DOWN;
break;
case 'a':
if (direction != RIGHT) direction = LEFT;
break;
case 'd':
if (direction != LEFT) direction = RIGHT;
break;
}
}
}
int main() {
initializeGame();
while (!gameOver) {
drawBoard();
updateDirection();
updateSnakePosition();
checkCollision();
Sleep(100);
}
printf("Game Over!n");
return 0;
}