LoginSignup
6
0

More than 1 year has passed since last update.

C#でMinecraftを操作する【前編】

Last updated at Posted at 2022-12-17

C# ではじめるマインクラフトプログラミングという無料で読める本を見つけた。面白そうだったので触ってみる。

動作環境

以下の環境で動作させる。Minecraftマルチプレイ用のサーバを構築する必要がある。

  • Minecraft 1.19.3
  • OpenJDK 17.0.4
  • Visual Studio 2022 17.4.3
  • .NET 6.0.307
  • MinecraftConnection 2.0.1

MinecraftConnectionとは

MinecraftConnectionとはC#を用いてMinecraftのマルチプレイサーバをコマンド操作できるライブラリである。
Minecraftサーバの設定ファイルserver.propertiesを見ると、rconなるものを設定する項目がある。rconを使うと、リモートでMinecraftサーバをコマンド操作することができる。
MinecraftConectionを使うと1行ずつ直接コマンドを打ち込むのではなく、C#を使って効率良く作用ができる。

まず使ってみる

Program.cs
using MinecraftConnection;

string address = "192.168.0.***";
ushort port = *****;
string pass = "********";
MinecraftCommands command = new MinecraftCommands(address, port, pass);

command.SetSubTitle("Qiitaアドベントカレンダー2022");
command.DisplayTitle("横国ゲーム制作部");

*は適宜環境に応じて置き換えていただきたい。
これを実行してみると、

このようになる。
SetSubTitleはMinecraft内のsubtitleコマンドに、DisplayTitleはMinecraft内のtitleコマンドに相当すると分かる。

ブロックの設置

command.SetBlock(<x座標>,<y座標>,<z座標>,"<ブロック名>");

とするとブロックが設置できる。<>は不要である。
例えば、プレイヤーのデータを取得するGetPlayerDataと組み合わせて、

Position pos = command.GetPlayerData("*******").Postision;
command.SetBlock((int)pos.X, (int)pos.Y, (int)pos.Z, "glass");

とするとプレイヤーのいる座標(厳密にはx座標とz座標が+1ずつずれる)にガラスブロックが設置される。Postisionはライブラリ側がスペルミスをしているようなのでこれで正しく動く。
Postisionが持つX,Y,Zの値はdouble型だが、SetBlockはint型を要求してくるのでキャストしている。
これをうまく利用すれば、自動建築なども可能である。

鉱石ブロックの探索

例えば、こんなこともできる。

Program.cs
string blockName = "iron_ore";
string playerName = "*******";
List<string> targetBlocks = new List<string>();

int posX = (int)command.GetPlayerData(playerName).Postision.X;
int posY = (int)command.GetPlayerData(playerName).Postision.Y;
int posZ = (int)command.GetPlayerData(playerName).Postision.Z;


for (int x = posX; x < posX + 16; x++)
{
    for (int z = posZ; z < posZ + 16; z++)
    {
        for (int y = posY; y > -64; y--)
        {
            string result = command.SendCommand($"execute if block {x} {y} {z} {blockName}");
            if (result.Contains("passed"))
            {
                targetBlocks.Add($"{blockName} : {x} {y} {z}");
            }
        }
    }
}

foreach(string block in targetBlocks)
{
    Console.WriteLine(block);
}

これはプレイヤーのいる座標(のx座標z座標共に+1ずらした座標)からxz16ブロックずつ、y座標-63までにある鉄鉱石ブロックを探索して結果をリストに入れてコンソールに出力するプログラムである。サーバと通信しながら実行するので普通にfor文を回すよりも時間がかかる。実行結果を以下に示す。

最後に

このライブラリでできることはまだまだたくさんあるが、ここでは紹介し切れない。近日中に続編を公開できればと思う。

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0