プログラミングの一般的なパターンでは、コード内でデータとして渡したり処理したりできるキャラクター コマンドなど、概念のデータ表現を作成します。 このミニゲームでは、コマンドは UI インタラクションから生成し、実行するキャラクターに渡すデータとして処理する必要があります。
このプロジェクトでは、コマンドは abstract クラスとして表現され、それぞれのコマンドは、forward_command
と turnright_command
など、この command
クラスのサブクラスです。 コマンドの abstract クラスを使用することは、有効なコマンドは abstract でないサブクラスであるという意味です。 command
クラスのインスタンスを直接作成しようとする場合、コードをコンパイルしようとするとエラーになります。
キャラクター コマンドは command
クラスのサブクラスなので、前のステップのキャラクターの ExecuteCommand()
関数など、command
クラスが必要なあらゆる場所でこれを使用できます。 ExecuteCommand()
の最初のパラメータはコマンド タイプが必要です。これは、引数として command
サブクラスのインスタンスを問題なく使用できるということです。
各サブクラスでは DebugString()
の実装を提供します。コマンド値を出力するときに、それに適切なテキストが関連付けられていますが、必要に応じてクラスにさらに違いを加えることができます。
クラスのインスタンスを比較できるように、これらのクラスには unique 指定子もあります。 この指定子により、比較できるようになります。
モジュール スコープで (モジュール
で直接) そのインスタンスを作成できるように、これらのクラスには computes 指定子もあります。 これは、単一の一意のインスタンスを作成して各コマンドを表現できるということです。たとえば、前進コマンドには Commands.Forward
です。
この例では、さらにサブクラスを作成することで、後でコマンドを追加できるように、enum 型の代わりに、コマンド サブクラスのインスタンスを使用しています。 enum
型でこれを変更したり、公開済みの初期バージョンのプロジェクトの後に enum 型に値を追加したりすることはできません。そのため、プロジェクトを公開した後でデータを変更する必要がない場合、enum
型がより適切です。
以下は、コマンド実装の完全なコードです。
# This file contains the data representation of all the commands that the NPC can receive
# and utilities for the data to help with debugging and troubleshooting issues.
# Each type of command that the NPC can perform will be an instance of this class.
# The class has the unique specifier to make instances of the class comparable.
# The class has the computes specifier to be able to instantiate it at module-scope.
# The class has the abstract specifier so it cannot be instantiated directly, and
# requires subclasses to implement any non-initialized functions, like DebugString().
command := class<computes><unique><abstract>:
DebugString():string
次のステップ
コマンドを定義し、必要な数だけ追加する方法を説明しました。
次のステップでは、UI でこれらのコマンドを使用する方法とキャラクターを制御するためのカスタム UI を追加する方法を説明します。
5. Controlling the NPC with UI
Learn how to create and update a custom, dynamic in-game UI using Verse.