私はアレン・B・ダウニーが書いた本「Think Java」からJavaを学んでいます。第 5 章では、GridWorld
オブジェクトを表すバグ、岩、グリッド自体などの「アクター」を含む 10x10 のグリッドを基本的にどこに持つかという概念が導入されています。コードがインストールされると、GridWorld
GUI は「バグ」と「ロック」の 2 つのアクターを含むグリッドを表示します。
アクターをクリックすると、そのアクターで呼び出すことができるメソッドを含むドロップダウン メニューが表示されます。
割り当ての 1 つは、Math.random();
namedrandomBug
を使用してバグをパラメーターとして取り、バグの方向を 0、90、180、または 270 のいずれかに設定するメソッドを作成することです。可能であればバグを移動します。
randomBug
次の割り当ては、整数を取り、時間n
を繰り返すように変更することn
です。
これは私のコードです:
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com)
*
* This code is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* @author Cay Horstmann
*/
import info.gridworld.actor.ActorWorld;
import info.gridworld.actor.Bug;
import info.gridworld.actor.Rock;
/**
* This class runs a world that contains a bug and a rock, added at random
* locations. Click on empty locations to add additional actors. Click on
* populated locations to invoke methods on their occupants. <br />
* To build your own worlds, define your own actors and a runner class. See the
* BoxBugRunner (in the boxBug folder) for an example. <br />
* This class is not tested on the AP CS A and AB exams.
*/
public class BugRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Bug redbug = new Bug();
world.add(redbug);
System.out.println(redbug.getLocation());
world.show();
randomBug(redbug, Math.random(), 5);
}
public static void randomBug(Bug x, double y, int n){
if (y <= 0.2 && n >= 0){
x.setDirection(0);
if (x.canMove()) x.move();
} else if (y >= 0.3 && y <= 0.5 && n >= 0){
x.setDirection(90);
if (x.canMove()) x.move();
} else if (y >= 0.6 && y <= 0.8 && n >= 0){
x.setDirection(180);
if (x.canMove()) x.move();
} else {
x.setDirection(270);
if (x.canMove()) x.move();
}
randomBug(x, Math.random(), n-1);
}
}
再帰関数を使用してプロセスを 5 回繰り返そうとしているので、グリッドの端に到達しない限り、バグは 5 回移動する必要があります。ときどき発生する問題は、条件を使用して制限したにもかかわらず、バグが 5 回以上移動し、6 または 10 ステップになることですn <= 0
。
割り当てを実行できるようにするには、コードで何を変更または追加する必要がありますか?