//声音资源文件 i++; } } /**
*创建一个给定的宇宙中的物体的数量。每一个身体都有一个随机的初始状态(size 大小,mass集中, direction方向, speed速度, color颜色, location位置). //世界里创建了一个给定的数量的球,每个球都有一个随机的初始状态 */
public void randomBodies(int number){ while (number > 0) {
int size = 20 + Greenfoot.getRandomNumber(30); //从一组数
据中随机取出一定数量的随机数 double mass = size * 7.0;
int direction= Greenfoot.getRandomNumber(360);//方向
double speed = Greenfoot.getRandomNumber(150) / 100.0; //速度 int x = Greenfoot.getRandomNumber(getWidth()); //取宽度 int y = Greenfoot.getRandomNumber(getHeight()); //取长度 int r = Greenfoot.getRandomNumber(255); int g = Greenfoot.getRandomNumber(255); int b = Greenfoot.getRandomNumber(255);
addObject (new Body (size, mass, new Vector(direction,
speed), new Color(r, g, b)), x, y); number--; } }
}
3.2 Obstacle代码
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot
第 - 6 - 页 共 14 页
and MouseInfo)
public class Obstacle extends Actor{ private String sound;
private boolean touched = false; /**
*创建一个具有相关的声音文件的一个障碍。 */
public Obstacle(String soundFile){ sound = soundFile;//声音档 } /**
*每一次循环,检查是否被击中。如果我们发挥我们的声音。
*/
public void act() {
Actor body = getOneIntersectingObject(Body.class); if (touched && body == null) //不用触碰 {
touched = false; setImage (\ }
else if (!touched && body != null){ //暂时的触碰 touched = true;
setImage (\
Greenfoot.playSound(sound); //播放声音 } }
public void playSound(){
Greenfoot.playSound(sound);
第 - 7 - 页 共 14 页
} }
3.3 SmoothMover代码
import greenfoot.*;// (World,Actor,GreenfootImage,and Greenfoot) /**
*一个变化的一个Actor,保持精确的位置(使用双打的坐标而不是整数)。它还保持当*前的运动矢量的运动形式。 */
public abstract class SmoothMover extends Actor{ private Vector movement; private double exactX; private double exactY;
public SmoothMover(){ this(new Vector()); } /**
* 创造新事物以给定的速度初始化的 */
public SmoothMover(Vector movement){ this.movement = movement; } /**
* 在当前的运动方向移动 */
public void move(){
exactX = exactX + movement.getX(); exactY = exactY + movement.getY();
super.setLocation((int) exactX, (int) exactY);
第 - 8 - 页 共 14 页
} /**
* 设置位置使用精确坐标(double) */
public void setLocation(double x, double y){ exactX = x; exactY = y;
super.setLocation((int) x, (int) y); } /**
* 设置的位置。重新定义标准的Greenfoot方法来确定 *确切的坐标更新同步 */
public void setLocation(int x, int y){ exactX = x; exactY = y;
super.setLocation(x, y); } /**
* 返回确切的x */
public double getExactX(){ return exactX; } /**
* Return the exact y co-ordinate (as a double).返回确切的y */
public double getExactY(){ return exactY;
第 - 9 - 页 共 14 页
} /**
*修改当前的运动通过添加一个新的向量到现有的运动 */
public void addForce(Vector force){ movement.add(force); } /**
*加速这种原动力的速度给定的因素。(因子小于1 * 减速)。方向保持不变。 */
public void accelerate(double factor){ movement.scale(factor);
if (movement.getLength() < 0.15) { movement.setNeutral(); } } /**
* 返回这个球的速度. */
public double getSpeed(){ return movement.getLength(); } /**
* 返回该对象的当前运动 */
public Vector getMovement(){ return movement; }
第 - 10 - 页 共 14 页