Open source small and fun games writen by AI in C and C++
Posted: Thu Feb 06, 2025 2:06 pm
Here i will post small and fun Open Source games writen by AI in C and C++
Here's a simple Snake game in C using ncurses for Ubuntu 22.04:

Here's a simple Snake game in C using ncurses for Ubuntu 22.04:

Code: Select all
#include <ncurses.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#include <unistd.h>
#define WIDTH 30
#define HEIGHT 20
#define MAX_LENGTH 100
typedef struct {
int x;
int y;
} Segment;
Segment snake[MAX_LENGTH];
int length = 1;
int score = 0;
enum Direction { STOP = 0, LEFT, RIGHT, UP, DOWN };
enum Direction dir;
int foodX, foodY;
bool gameOver = false;
void generateFood() {
bool valid;
do {
valid = true;
foodX = (rand() % (WIDTH - 2)) + 1;
foodY = (rand() % (HEIGHT - 2)) + 1;
for (int i = 0; i < length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
valid = false;
break;
}
}
} while (!valid);
}
void setup() {
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
nodelay(stdscr, TRUE);
curs_set(0);
snake[0].x = WIDTH / 2;
snake[0].y = HEIGHT / 2;
dir = RIGHT;
generateFood();
}
int main() {
srand(time(NULL));
setup();
while (!gameOver) {
int ch = getch();
switch(ch) {
case KEY_LEFT:
if (dir != RIGHT) dir = LEFT;
break;
case KEY_RIGHT:
if (dir != LEFT) dir = RIGHT;
break;
case KEY_UP:
if (dir != DOWN) dir = UP;
break;
case KEY_DOWN:
if (dir != UP) dir = DOWN;
break;
case 'q':
gameOver = true;
break;
}
int newHeadX = snake[0].x;
int newHeadY = snake[0].y;
switch(dir) {
case LEFT: newHeadX--; break;
case RIGHT: newHeadX++; break;
case UP: newHeadY--; break;
case DOWN: newHeadY++; break;
case STOP: break;
}
if (newHeadX <= 0 || newHeadX >= WIDTH-1 || newHeadY <= 0 || newHeadY >= HEIGHT-1) {
gameOver = true;
continue;
}
for (int i = 1; i < length; i++) {
if (snake[i].x == newHeadX && snake[i].y == newHeadY) {
gameOver = true;
break;
}
}
if (gameOver) continue;
if (newHeadX == foodX && newHeadY == foodY) {
if (length < MAX_LENGTH) {
for (int i = length; i > 0; i--) {
snake[i] = snake[i-1];
}
length++;
}
snake[0].x = newHeadX;
snake[0].y = newHeadY;
score += 10;
generateFood();
} else {
for (int i = length-1; i > 0; i--) {
snake[i] = snake[i-1];
}
snake[0].x = newHeadX;
snake[0].y = newHeadY;
}
clear();
for (int i = 0; i < WIDTH; i++) {
mvaddch(0, i, '#');
mvaddch(HEIGHT-1, i, '#');
}
for (int i = 0; i < HEIGHT; i++) {
mvaddch(i, 0, '#');
mvaddch(i, WIDTH-1, '#');
}
for (int i = 0; i < length; i++) {
mvaddch(snake[i].y, snake[i].x, 'O');
}
mvaddch(foodY, foodX, '*');
mvprintw(HEIGHT, 2, "Score: %d", score);
refresh();
usleep(100000);
}
endwin();
printf("Game Over! Final Score: %d\n", score);
return 0;
}
Code: Select all
sudo apt-get install libncurses-dev
gcc snake.c -o snake -lncurses
./snake