fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main() {
  5. // your code goes here
  6. return 0;
  7. }
Success #stdin #stdout 0.01s 5288KB
stdin
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>

using namespace std;

const int WIDTH = 20;
const int HEIGHT = 20;

struct Point {
    int x;
    int y;
};

vector<Point> snake;
Point food;
int direction; 
int score;

void initGame() {
    snake.push_back({WIDTH / 2, HEIGHT / 2});
    food = {rand() % WIDTH, rand() % HEIGHT};
    direction = 1; 
    score = 0;
}

void drawGame() {
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            if (i == snake[0].y && j == snake[0].x) {
                cout << "O"; 
            } else if (i == food.y && j == food.x) {
                cout << "F"; 
            } else {
                bool isSnakeBody = false;
                for (int k = 1; k < snake.size(); k++) {
                    if (i == snake[k].y && j == snake[k].x) {
                        isSnakeBody = true;
                        break;
                    }
                }
                if (isSnakeBody) {
                    cout << "o"; 
                } else {
                    cout << " ";
                }
            }
        }
        cout << endl;
    }
}

void updateGame() {
    Point newHead;
    switch (direction) {
        case 0:
            newHead = {snake[0].x, snake[0].y - 1};
            break;
        case 1: 
            newHead = {snake[0].x + 1, snake[0].y};
            break;
        case 2: 
            newHead = {snake[0].x, snake[0].y + 1};
            break;
        case 3:
            newHead = {snake[0].x - 1, snake[0].y};
            break;
    }
    snake.insert(snake.begin(), newHead);
    if (snake[0].x == food.x && snake[0].y == food.y) {
        score++;
        food = {rand() % WIDTH, rand() % HEIGHT};
    } else {
        snake.pop_back();
    }
}

void handleInput() {
    char input;
    cin >> input;
    switch (input) {
        case 'w':
            direction = 0; // up
            break;
        case 'd':
            direction = 1; 
            break;
        case 's':
            direction = 2; 
            break;
        case 'a':
            direction = 3; 
            break;
    }
}

int main() {
    srand(time(0));
    initGame();
    while (true) {
        drawGame();
        handleInput();
        updateGame();
        if (snake[0].x < 0 || snake[0].x >= WIDTH || snake[0].y < 0 || snake[0].y >= HEIGHT) {
            cout << "Game over! Your score is " << score << endl;
            break;
        }
        for (int i = 1; i < snake.size(); i++) {
            if (snake[0].x == snake[i].x && snake[0].y == snake[i].y) {
                cout << "Game over! Your score is " << score << endl;
                break;
            }
        }
    }
    return 0;
}
stdout
Standard output is empty