您的位置:首页 > 其它

Mason 入门例子3 --- 让学生动起来

2016-03-26 09:49 183 查看
现在我们给学生增加 forceToSchoolMultiplier 和 randomMultiplier 两种力。

学生会有往操场中心行走的趋势和随机漫游的趋势。

package com.mason.learn;

import sim.engine.*;

import sim.util.*;
import sim.field.continuous.*;

public class Students extends SimState {
private static final long serialVersionUID = 1L;
public Continuous2D yard = new Continuous2D(1.0, 100, 100);
public int numStudents = 50;

double forceToSchoolMultiplier = 0.01;
double randomMultiplier = 0.1;

public Students(long seed) {
super(seed);
}

public void start() {
super.start();
// clear the yard
yard.clear();

// add some students to the yard
for (int i = 0; i < numStudents; i++) {
Student student = new Student();
yard.setObjectLocation(student, new Double2D(yard.getWidth() * 0.5
+ random.nextDouble() - 0.5, yard.getHeight() * 0.5
+ random.nextDouble() - 0.5));

schedule.scheduleRepeating(student);
}
}

public static void main(String[] args) {
doLoop(Students.class, args);
System.exit(0);
}
}


学生类实现steppable接口,每个时间步长点会按照随机顺序调用所有Student的step方法。

package com.mason.learn;

import sim.engine.*;
import sim.field.continuous.Continuous2D;
import sim.util.*;

public class Student implements Steppable {

private static final long serialVersionUID = 1L;

@Override
public void step(SimState state) {
Students students = (Students) state;
Continuous2D yard = students.yard;
Double2D me = students.yard.getObjectLocation(this);
MutableDouble2D sumForces = new MutableDouble2D();
// add in a vector to the "teacher" -- the center of the yard, so we
// don’t go too far away
sumForces.addIn(new Double2D((yard.width * 0.5 - me.x)
* students.forceToSchoolMultiplier, (yard.height * 0.5 - me.y)
* students.forceToSchoolMultiplier));
// add a bit of randomness
sumForces.addIn(new Double2D(students.randomMultiplier
* (students.random.nextDouble() * 1.0 - 0.5),
students.randomMultiplier
* (students.random.nextDouble() * 1.0 - 0.5)));
sumForces.addIn(me);
students.yard.setObjectLocation(this, new Double2D(sumForces));

}

}


我们从State中抽取yard,然后找到当前Student对象的位置。

我们使用MutableDouble来计算综合的位移,最后设置Student的新位置。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: