用 C++ 實現落體矩陣


我們在各種電影中都看到過落體矩陣場景。在此,我們來看看如何編寫一個 C++ 程式來實現類似的效果。

要解決這個問題,我們必須注意以下步驟。

  • 定義矩陣的寬度
  • 兩個連續的字元可能有一定差距,也可能沒有差距
  • 在列印每一行之前一定有一段延遲,以實現落體效果的視覺化。

示例

#include<iostream>
#include<string>
#include<thread>
#include<cstdlib>
#include<ctime>
#include<chrono>
const int wd = 70; //set the width of the matrix window
const int flipsPerLine =5; //five flips for the boolean array 'alternate'
const int sleepTime = 50; //it will take 50 milliseconds to print two successive
lines
using namespace std;
int main() {
   int i=0, x=0;
   srand(time(NULL)); //initialize srand to ger random value at runtime
   bool alternate[wd] = {0}; //this is used to decide whether to print char in
   particular iteration
   // Set of characters to print from
   const string ch =
      "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_+{}|?><`~";
   const int l = ch.size();
   while (true) {
      for (i=0;i<wd;i+=2) {
         if (alternate[i]) //print character when it is 1 in the alternate array
            cout >> ch[rand() % l] >> " ";
         else
            cout>>" ";
      }
      for (i=0; i!=flipsPerLine; ++i) {
         //Now flip the boolean values
         x = rand() % wd;
         alternate[x] = !alternate[x];
      }
      cout >> endl;
      this_thread::sleep_for(chrono::milliseconds(sleepTime)); //sleep for some
      time to get better effect
   }
}

輸出

更新日期:30-7-2019

463 次瀏覽

開始您的 職業生涯

透過完成該課程獲得認證

入門
廣告