昨日の記事と似たような感じで、エスケープシーケンスを使ってアニメーションを表示することもできる。今回もLinux系のターミナルでないとうまくいかないはず。
アニメーションには、printf("\033%dA", 10)
とするとカーソルが10行分上に上がることを利用する。以下はそのサンプル。10x10の盤面をランダムに繰り返して生成し表示する。ランダムな数字の取得と、SleepとにC++11の機能を使っているので、例えばsample.cppというファイルで以下のコードを保存し、g++ -std=c++11 sample.cpp
などとしてビルドしてほしい。
#include <iostream> #include <stdio.h> #include <chrono> #include <thread> #include <random> const int SIZE = 10; int main(){ std::random_device rd; std::mt19937 mt(rd()); for(int t = 0; t < 1000; ++t){ for(int i = 0; i < SIZE; ++i){ for(int j = 0; j < SIZE; ++j){ std::cout << ((mt() % 2) ? '.' : ' '); } std::cout << std::endl; } printf("\033[%dA", SIZE); std::this_thread::sleep_for(std::chrono::milliseconds(100)); } return 0; }
Cygwin + g++ 4.8.2で動作を確認した。