C++ Code Game Snake

6 min read Jul 01, 2024
C++ Code Game Snake

Kode C++ untuk Game Snake

Kode C++ berikut ini menunjukkan contoh sederhana dari game Snake yang bisa kamu coba jalankan:

#include 
#include 
#include 
#include 

using namespace std;

// Define snake's body
struct Snake {
    int x;
    int y;
};

// Function to print the game board
void printBoard(vector &snake, int foodX, int foodY, int width, int height) {
    system("cls"); // Clear the console

    for (int i = 0; i <= height; i++) {
        for (int j = 0; j <= width; j++) {
            // Check if current position is snake's body
            bool isSnake = false;
            for (int k = 0; k < snake.size(); k++) {
                if (snake[k].x == j && snake[k].y == i) {
                    isSnake = true;
                    break;
                }
            }

            // Print snake's body or food
            if (isSnake) {
                cout << "O";
            } else if (j == foodX && i == foodY) {
                cout << "F";
            } else {
                cout << " ";
            }
        }
        cout << endl;
    }
}

// Function to move the snake
void moveSnake(vector &snake, char direction, int &foodX, int &foodY, int width, int height) {
    // Create a new snake head
    Snake newHead = snake[0];

    // Move the head according to direction
    switch (direction) {
        case 'w':
            newHead.y--;
            break;
        case 's':
            newHead.y++;
            break;
        case 'a':
            newHead.x--;
            break;
        case 'd':
            newHead.x++;
            break;
    }

    // Check for boundary collision
    if (newHead.x < 0 || newHead.x > width || newHead.y < 0 || newHead.y > height) {
        cout << "Game Over!" << endl;
        exit(0);
    }

    // Check for self collision
    for (int i = 1; i < snake.size(); i++) {
        if (newHead.x == snake[i].x && newHead.y == snake[i].y) {
            cout << "Game Over!" << endl;
            exit(0);
        }
    }

    // Add the new head to the snake
    snake.insert(snake.begin(), newHead);

    // Check if snake eats food
    if (newHead.x == foodX && newHead.y == foodY) {
        // Generate new food position
        foodX = rand() % width;
        foodY = rand() % height;
    } else {
        // Remove the tail if snake doesn't eat food
        snake.pop_back();
    }
}

int main() {
    // Initialize game parameters
    int width = 20;
    int height = 10;
    int foodX = rand() % width;
    int foodY = rand() % height;
    vector snake;
    snake.push_back({width / 2, height / 2});

    // Game loop
    while (true) {
        // Print the game board
        printBoard(snake, foodX, foodY, width, height);

        // Get user input
        char direction = getch();

        // Move the snake
        moveSnake(snake, direction, foodX, foodY, width, height);

        // Delay for smoother gameplay
        Sleep(100);
    }

    return 0;
}

Penjelasan Kode:

  1. Header Files:

    • <iostream>: Untuk input/output.
    • <conio.h>: Untuk input karakter tunggal dan clear screen.
    • <windows.h>: Untuk delay (fungsi Sleep).
    • <vector>: Untuk menyimpan data snake sebagai vektor.
  2. Struktur Snake:

    • Mendefinisikan struktur Snake untuk menyimpan koordinat x dan y setiap bagian tubuh snake.
  3. Fungsi printBoard:

    • Mencetak papan permainan dengan snake dan food.
    • Menampilkan 'O' untuk snake, 'F' untuk food, dan ' ' untuk ruang kosong.
  4. Fungsi moveSnake:

    • Menggerakkan snake berdasarkan input arah.
    • Memeriksa collision dengan batas permainan dan snake sendiri.
    • Menambahkan head baru dan menghapus tail jika tidak makan food.
    • Menghasilkan food baru jika snake memakan food.
  5. Fungsi main:

    • Inisialisasi parameter game seperti lebar dan tinggi papan, posisi food awal, dan posisi snake awal.
    • Loop game:
      • Mencetak papan permainan.
      • Mengambil input arah dari user.
      • Menggerakkan snake.
      • Menunda sebentar (delay) untuk gameplay yang lebih halus.

Cara Menjalankan Kode:

  1. Simpan kode di file .cpp (misalnya: snake.cpp).
  2. Kompilasi kode menggunakan compiler C++ (misalnya: g++):
    g++ snake.cpp -o snake
    
  3. Jalankan file executable:
    ./snake
    

Cara Bermain:

Gunakan tombol W, A, S, D untuk mengontrol arah snake:

  • W: Ke atas
  • A: Ke kiri
  • S: Ke bawah
  • D: Ke kanan

Tujuan game adalah untuk memakan food dan membuat snake semakin panjang. Game berakhir ketika snake menabrak batas permainan atau tubuhnya sendiri.

Latest Posts


Featured Posts