Here A Simple 2d Game
Here A Simple 2d Game
game
This basic snake game runs in the console and uses ASCII characters to
display the game grid, the snake, and the food.
Explanation
Setup: Initializes the game settings, including the snake’s starting position
and the fruit’s random position.
Draw: Clears the console and redraws the game board, including the walls,
snake, and fruit.
Input: Detects key presses to change the direction of the snake (w, a, s, d for
movement and x to exit).
Logic: Moves the snake, handles collision detection (wall and self), and
updates the score if the snake eats the fruit.
In put:
#include <iostream>
bool gameOver;
eDirection dir;
void Setup() {
gameOver = false;
void Draw() {
// Top wall
if (j == 0)
if (i == y && j == x)
else {
print = true;
}
}
if (!print)
if (j == width - 1)
// Bottom wall
void Input() {
case 'a':
dir = LEFT;
break;
case 'd':
dir = RIGHT;
break;
case 'w':
dir = UP;
break;
case 's':
dir = DOWN;
break;
case 'x':
break;
void Logic() {
tailX[0] = x;
tailY[0] = y;
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
switch (dir) {
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
case UP:
y--;
break;
case DOWN:
y++;
break;
default:
break;
gameOver = true;
score += 10;
int main() {
Setup();
while (!gameOver) {
Draw();
Input();
Logic();
return 0;
}
Out put :
How to Play
Use W, A, S, and D to move the snake up, left, down, and right.
Try to eat the fruit (F) to grow the snake and increase your score.
Avoid hitting the walls or your own tail to prevent the game from ending.
Requirements
This game needs Windows due to Sleep() from <windows.h> and _kbhit()
from <conio.h>. If you're using a non-Windows system, you may need
alternative libraries for those functions.