17-10 大地と闇の気配の復活

解説動画

解答コード

// 反対方向を定義する連想配列は、17-8と同じものを使います
// let dic_opposite: { [key: number]: number } = {
//     [RIGHT]: LEFT,
//     [LEFT]: RIGHT
// };

// ブロック番号の連想配列
let dic_item1710: { [key: string]: number } = {
    "frame": 17,    // 畑の枠
    "carrot": 141   // 人参
};

// エージェントの状態を表す連想配列
let dic_agentStatus1710: { [key: string]: number } = {
    "row": 0,
    "turnDirection": LEFT
};

// エリアの状態を表す連想配列
let dic_areaStatus1710: { [key: string]: number } = {
    "rowMax": 15
};

// エージェントをエリア内で移動させる関数
function move1710(agentStatus: { [key: string]: number }, areaStatus: { [key: string]: number }, items: { [key: string]: number }) {

    // エージェントを1歩前に進めます
    agent.move(FORWARD, 1);

    // エージェントの足元のブロックを取得します
    let blockIdBelow = agent.inspect(AgentInspection.Block, DOWN);

    // 足元が畑の枠の場合は、方向転換しながら、行を移動します
    let shouldTurn = (blockIdBelow == items["frame"]);
    if (shouldTurn) {
        if (agentStatus["row"] >= areaStatus["rowMax"]) {
            // 現在の行がエリアの最大行数以上の場合は、移動を終了します
            return false;
        }
        // エージェントを横に向かせて、1ブロック前進させます
        agent.turn(agentStatus["turnDirection"]);
        agent.move(FORWARD, 1);
        // エージェントを横に向かせて、畑の方を向きます
        agent.turn(agentStatus["turnDirection"]);
        // 次の方向転換のときの、向きを反転させます
        agentStatus["turnDirection"] = dic_opposite[agentStatus["turnDirection"]];
        // 行数を更新します
        agentStatus["row"] += 1;
    }

    // 移動を続けるので true を返します
    return true;
}

// 人参を収穫する関数
function harvest1710(agentStatus: { [key: string]: number }, areaStatus: { [key: string]: number }, items: { [key: string]: number }) {
    let blockIdFront = agent.inspect(AgentInspection.Block, FORWARD);
    if (blockIdFront !== items["carrot"]) {
        return 0;
    }
    agent.destroy(FORWARD);
    return 1;
}

// コマンドのチャット入力で人参の収穫を行います
player.onChat("17-10", () => {
    player.say("人参の収穫を開始します");
    player.say("エージェントが人参を刈り取るので、落ちた人参を拾い集めてください");
    let carrotCount = 0;
    while (true) {
        carrotCount += harvest1710(dic_agentStatus1710, dic_areaStatus1710, dic_item1710);
        let shouldContinue = move1710(dic_agentStatus1710, dic_areaStatus1710, dic_item1710);
        if (shouldContinue == false) {
            break;
        }
    }
    player.say("人参の刈り取りが完了しました。刈り取った数:" + carrotCount + "株");
    player.say("拾った人参を樽に入れてください");
});