ゲームが作れるようになるまでがんばる日記

ゲーム制作のことを中心にゲームに関することを書いています

履歴を取る

パッドのボタン入力を60フレーム分取っておいて、コマンド入力の判定に用いるなど、データの履歴を利用したい場合がある。その場合には一定サイズのバッファに新しい入力データを追加し、古いデータを破棄することで表現できる。
STLのdeque(デック)を使ってテストしてみたのが次のコード。
push_back()でデータを追加した後、サイズを調べ、必要なサイズを越えていたら、pop_front()で先頭のデータを取り除いている。

#include <iostream>
#include <random>
#include <deque>

int main(void){
    std::random_device rnd;
    std::mt19937 mt(rnd());  
    std::uniform_int_distribution<int> rand100(0,99);
    std::deque<int> history;
    const int kMax = 10;
    for(int i=0; i<kMax; i++) {
        history.push_back(rand100(mt));
    }
    for(int i=0; i<5; i++) {
        history.push_back(rand100(mt));
        if(history.size() > kMax) {
            history.pop_front();
        }
        for(auto value : history) {
            std::cout << value << ' ';
        }
        std::cout << std::endl;
    }
}

実行例
38 20 64 55 2 14 14 98 75 15 
20 64 55 2 14 14 98 75 15 64 
64 55 2 14 14 98 75 15 64 32 
55 2 14 14 98 75 15 64 32 67 
2 14 14 98 75 15 64 32 67 43