色ブロッククラスを実装する

色ブロッククラスを実装する

「colorWinRTUWP」プロジェクトを右クリックして表示されるメニューから「Add」→「New Item」を選び、「ColorBlock.cpp」「ColorBlock.h」ファイルを新規作成して追加します。追加したファイルに「ColorBlock」クラスの設計図をコーディングします(図2)。

プログラミング言語はC/C++が元祖のようなものですが、ソースファイルとヘッダーファイルを分けて書かなければならないのは、モダンなプログラミング言語と比べると面倒ですね。

図2:色ブロックを表示

・サンプルコード「ColorBlock.h」ファイル

#pragma once

class ColorBlock
{
private:
    int x, y;
    int vx, vy;
    int color;
    winrt::Windows::UI::Xaml::Controls::Image image;
public:
    ColorBlock(winrt::Windows::UI::Xaml::Controls::Canvas imageCanvas,int c);
    int Update();
};

【サンプルコードの解説】
ColorBlockクラスに色ブロックの位置(x,y)、移動量(vx,vy)、色(color)、画像(image)プロパティを宣言します。

・サンプルコード「ColorBlock.cpp」ファイル

#include "pch.h"
#include "ColorBlock.h"
#include <cstdlib>

using namespace winrt;
using namespace winrt::Windows::UI::Xaml::Media::Imaging;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::Foundation;

ColorBlock::ColorBlock(Canvas imageCanvas,int c) {
	x = rand() % 1700;
	y = rand() % 800;
	vx = (rand() % 7) - 3;
	vy = (rand() % 7) - 3;
	color = c;
    BitmapImage bitmap;
    bitmap.UriSource(Uri(
        L"ms-appx:///Assets/" + std::to_wstring(c) + L".png"
    ));
    image.Source(bitmap);
    // 表示サイズ
    image.Width(100);
    image.Height(100);
    // Canvas上の位置
    Canvas::SetLeft(image, x);
    Canvas::SetTop(image, y);
    imageCanvas.Children().Append(image);
}

int ColorBlock::Update() {
    x += vx;
	y += vy;
    Canvas::SetLeft(image, x);
    Canvas::SetTop(image, y);
    if (x >= -100 && x <= 1800 && y >= -100 && y <= 900) return 1;
	return 0;
}

【サンプルコードの解説】
プリコンパイル済みヘッダー"pch.h"、色ブロッククラス"ColorBlock.h"、乱数の<cstdlib>ヘッダーをインクルードします。
「ColorBlock」コンストラクタで(x,y)と(vx,vy)にランダムな整数を代入し、色ブロックの色(color)をセットします。Assetsから色ブロック画像(image)を読み込み、(x,y)座標に配置して、imageプロパティをImageCanvasの子要素に追加します。
「Update」メソッドで色ブロックの位置座標を移動・配置し、画面内にあれば戻り値として1を返し、画面外なら0を返します。

・サンプルコード「MainPage.h」ファイル

#pragma once

#include "MainPage.g.h"
#include "ColorBlock.h"

namespace winrt::colorWinRTUWP::implementation
{
    struct MainPage : MainPageT<MainPage>
    {
        int stage = 2;
        std::vector<std::unique_ptr<ColorBlock>> colors;
        Windows::UI::Xaml::DispatcherTimer timer{ nullptr };
 
        MainPage();
        int32_t MyProperty();
        void MyProperty(int32_t value);

        void TitleImage_PointerPressed(
            Windows::Foundation::IInspectable const& sender,
            Windows::UI::Xaml::Input::PointerRoutedEventArgs const& e);
        void Init();
        void StartTimer();
        void StopTimer();
        void UpdateFrame();
    };
}

namespace winrt::colorWinRTUWP::factory_implementation
{
(中略)
}

【サンプルコードの解説】
"ColorBlock.h"ヘッダーをインクルードします。
「MainPage」構造体で最初の面の「stage」プロパティに2を代入し、ColorBlockクラスのインスタンスを格納する「colors」プロパティと、タイマーの「timer」プロパティを宣言します。

・サンプルコード「MainPage.cpp」ファイル

#include "pch.h"
#include "MainPage.h"
#include "MainPage.g.cpp"

using namespace winrt;
using namespace Windows::UI::ViewManagement;
using namespace Windows::UI;
using namespace Windows::UI::Xaml::Media;

namespace winrt::colorWinRTUWP::implementation
{
    MainPage::MainPage()
    {
(中略)
    }

    int32_t MainPage::MyProperty()
    {
        throw hresult_not_implemented();
    }

    void MainPage::MyProperty(int32_t /* value */)
    {
        throw hresult_not_implemented();
    }

    void MainPage::TitleImage_PointerPressed(
        Windows::Foundation::IInspectable const& sender,
        Windows::UI::Xaml::Input::PointerRoutedEventArgs const& e)
    {
        // 画像が押されたときの処理
        TitleGrid().Visibility(Windows::UI::Xaml::Visibility::Collapsed);
        ImageCanvas().Visibility(Windows::UI::Xaml::Visibility::Visible);
        Init();
        StartTimer();
    }

    void MainPage::Init()
    {
        ImageCanvas().Children().Clear();
        colors.clear();
        for (int i = 0; i < 3*stage; ++i)
        {
            colors.push_back(std::make_unique<ColorBlock>(ImageCanvas(), i % 3));
        }
    }

    void MainPage::StartTimer()
    {
    }

    void MainPage::StopTimer()
    {
    }

    void MainPage::UpdateFrame()
    {
    }
}

【サンプルコードの解説】
「「MainPage」構造体のTitleImage_PointerPressedメソッドで、タイトル画像がクリックされたらタイトルGridを隠してImageCanvasを表示し、「Init」「StartTimer」メソッドを呼び出します。
InitメソッドでImageCanvasの子要素とcolors配列をクリアし、stage*3色(R・G・B)の数だけColorBlockクラスのインスタンスを生成してcolors配列に追加します。

色ブロックを移動し、すべて画面外に出たら
ゲームオーバー処理する

まだ色ブロックは配置しただけでタイマーによる移動をしていなかったので、10FPSの速度で移動量ずつ動かします。すべての色ブロックが画面外に出たらゲームオーバーで、タイトル画面に戻ります。

・サンプルコード「MainPage.cpp」ファイル

(前略)
namespace winrt::colorWinRTUWP::implementation
{
    MainPage::MainPage()
    {
(中略)
    }

    int32_t MainPage::MyProperty()
    {
        throw hresult_not_implemented();
    }

    void MainPage::MyProperty(int32_t /* value */)
    {
        throw hresult_not_implemented();
    }

    void MainPage::TitleImage_PointerPressed(
        Windows::Foundation::IInspectable const& sender,
        Windows::UI::Xaml::Input::PointerRoutedEventArgs const& e)
    {
(中略)
    }

    void MainPage::Init()
    {
(中略)
    }

    void MainPage::StartTimer()
    {
        timer = Windows::UI::Xaml::DispatcherTimer();

        timer.Interval(std::chrono::milliseconds(100));

        timer.Tick([this](auto const&, auto const&)
            {
                // 約10 FPSで呼び出される処理
                UpdateFrame();
            });

        timer.Start();
    }

    void MainPage::StopTimer()
    {
        if (timer)
        {
            timer.Stop();
        }
    }

    void MainPage::UpdateFrame()
    {
        int flg = 0;
        for (auto& col : colors)
        {
            flg += col->Update();
        }
        if (flg == 0)
        {
            TitleGrid().Visibility(Windows::UI::Xaml::Visibility::Visible);
            ImageCanvas().Visibility(Windows::UI::Xaml::Visibility::Collapsed);
            StopTimer();
        }
    }
}

【サンプルコードの解説】
「MainPage」構造体でStartTimerメソッドでタイマーを起動し、100ミリ秒ごと(10FPS)に「UpdateFrame」メソッドを呼び出してタイマーをスタートします。
「StopTimer」メソッドでタイマーをストップします。
「UpdateFrame」メソッドですべての色ブロックを更新(Updateメソッド)し、画面内に1個も残っていなければ(flg == 0)、タイトルGridを表示してImageCanvasを隠し、タイマーを停止します。

【コラム】ガラパゴス

筆者がプログラミングしていることは時代遅れで、ガラケーのようにガラパゴスの道を歩んでいるような気がしてきました…。

人気記事トップ10

人気記事ランキングをもっと見る

企画広告も役立つ情報バッチリ! Sponsored