17-5 枯れた大地を耕せば

解説動画

解答コード

// 土ID: 3, 草ブロックID: 2, 耕作地ID: 60, 畑の枠ID: 17
let dic_farmland175: { [key: number]: string } = {
    3: "dirt",          // 土 → 耕作が必要
    2: "dirt",          // 草ブロック → 耕作が必要  
    60: "farmland",     // 耕作地 → 耕作終了
    17: "frame"         // 畑の枠 → 次の列に移動
};

// 足元を耕す処理
function tillStep175(status: { [key: string]: number }) {
    let id = agent.inspect(AgentInspection.Block, DOWN);

    // 連想配列の値を取得する
    let blockType = dic_farmland175[id];

    if (blockType === "dirt") {
        // 土系ブロックの場合は破壊して耕作地に入れ替え
        agent.destroy(DOWN);
        agent.setItem(60, 1, 1);  // 耕作地ブロック
        agent.place(DOWN);
        player.say("土を耕作しました (ID: " + id + " -> 60)");

        status["tilled"] += 1;
        // 前に進む
        agent.move(FORWARD, 1);
        return true  // 処理続行
    } else if (blockType === "farmland") {
        // 既に耕作地の場合は作業終了
        player.say("耕作済みブロック発見!作業終了 (ID: " + id + ")");
        return false;      // 処理終了
    } else if (blockType === "frame") {
        // 畑の枠の場合は次の列に移動
        player.say("畑の枠発見!次の列に移動 (ID: " + id + ")");

        // 枠の上で転回
        agent.turn(status["turnDirection"]);
        // 枠の上で前へ進む
        agent.move(FORWARD, 1);
        // 枠の上で転回
        agent.turn(status["turnDirection"]);
        // 前へ進む(畑の中に入る)
        agent.move(FORWARD, 1);

        // 列番号を増やす
        status["row"] += 1;

        // 列が変わるごとに、転回の向きをきりかえる(右 -> 左 -> 右 ...)
        if (status["turnDirection"] === RIGHT) {
            status["turnDirection"] = LEFT;
        } else {
            status["turnDirection"] = RIGHT;
        }
        return true;  // 処理続行
    } else {
        // その他のブロック(空気含む)の場合は何もしないで前に進む
        player.say("その他のブロックです (ID: " + id + ")");
        agent.move(FORWARD, 1);
        return true;  // 処理続行
    }
}

player.onChat("17-5", () => {

    // 耕作作業中のエージェントの状態
    let tillStatus: { [key: string]: number } = {
        "row": 0,
        "tilled": 0,
        "turnDirection": RIGHT
    };

    // 耕作中の畑の列番号
    let currentRow = tillStatus["row"];

    // 最初だけ、エージェントはスタート地点から一歩前に進む
    agent.move(FORWARD, 1);

    // 最初の列に入ったので報告します
    player.say("=== " + (currentRow + 1) + "列目の耕作開始 ===");

    while (true) {
        // 新しい列に入ったときに報告します
        if (tillStatus["row"] > currentRow) {
            currentRow = tillStatus["row"];
            player.say("=== " + (currentRow + 1) + "列目の耕作開始 ===");
        }

        // エージェントに耕作をして動いてもらいます
        let shouldContinue = tillStep175(tillStatus);

        // 耕作を続けるかどうか判定します
        if (shouldContinue == false) {
            player.say("耕作済みブロックが見つかったため全処理を終了します(耕した数:" + tillStatus["tilled"] + ")");
            break;
        }
    }
});