Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

สร้าง Falling Matrix Effect ด้วย C++: โค้ดและหลักการทำงาน

เอฟเฟกต์ "Falling Matrix" (โค้ดสีเขียวตกหล่น) ที่เห็นในภาพยนตร์ The Matrix สามารถสร้างได้ด้วย C++ แบบ Console Application โดยใช้เทคนิคพื้นฐาน: Random Characters, Boolean Array สำหรับควบคุมการแสดง, และ Delay เพื่อสร้าง Animation

หลักการทำงาน

  1. กำหนดความกว้าง (Width) ของหน้าจอ Console
  2. Boolean Array ขนาด Width: true = แสดงตัวอักษร, false = แสดง Space
  3. Random Flip: สลับค่า Boolean แบบสุ่มทุก Frame เพื่อสร้าง Effect "ตกหล่น"
  4. Character Set: กำหนดชุดตัวอักษร (อักษร, ตัวเลข, สัญลักษณ์)
  5. Delay: ใช้ std::this_thread::sleep_for ควบคุมความเร็ว

โค้ดเต็ม (ปรับปรุงให้ทันสมัย)

#include <iostream>
#include <string>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <random>

using namespace std;

int main() {
    const int WIDTH = 80;
    const int FLIPS_PER_FRAME = 5;
    const int DELAY_MS = 50;
    
    // ใช้ Random Engine ทันสมัยแทน rand()
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> char_dist(0, 93); // Index ของ Character Set
    uniform_int_distribution<> flip_dist(0, WIDTH - 1);
    uniform_int_distribution<> bool_dist(0, 1);

    // Character Set (ASCII Printable + Symbols)
    const string CHARS = 
        "1234567890"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz"
        "!@#$%^&*()_+{}|?><`~";

    vector<bool> active(WIDTH, false); // State ของแต่ละ Column

    // สีเขียวสำหรับ Windows (Optional)
    #ifdef _WIN32
    system("color 0A");
    #endif

    cout << "\033[2J\033[H"; // Clear Screen (ANSI Escape)

    while (true) {
        // 1. Render Frame
        for (int i = 0; i < WIDTH; ++i) {
            if (active[i]) {
                cout << CHARS[char_dist(gen)] << ' ';
            } else {
                cout << "  ";
            }
        }
        cout << '\n';

        // 2. Randomly Flip Columns
        for (int i = 0; i < FLIPS_PER_FRAME; ++i) {
            int idx = flip_dist(gen);
            active[idx] = !active[idx];
        }

        // 3. Delay
        this_thread::sleep_for(chrono::milliseconds(DELAY_MS));
    }
    return 0;
}

การปรับแต่ง (Customization)

  • ความเร็ว: ปรับ DELAY_MS (ค่าน้อย = เร็วขึ้น)
  • ความหนาแน่น: ปรับ FLIPS_PER_FRAME
  • ตัวอักษร: เปลี่ยน CHARS (เช่น Katakana สไตล์ Matrix จริง)
  • สี: ใช้ ANSI Escape Codes (\033[32m สีเขียว, \033[0m Reset)
  • Trailing Effect: เก็บ History หลายบรรทัด แล้ว Fade Out 漸漸

สรุป

Falling Matrix เป็นโปรเจกต์สนุกสำหรับฝึก Console I/O, Random, Multithreading (Sleep), และ ANSI Escape Codes โค้ดข้างต้นใช้ Modern C++ (<random>, <chrono>, vector) ทดแทน C-style Functions ให้ปลอดภัยและทันสมัยกว่า