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

来源:互联网 发布:看韩剧用什么软件 编辑:程序博客网 时间:2024/06/10 01:46

现在我们给学生增加 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 yardyard.clear();// add some students to the yardfor (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;@Overridepublic 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 awaysumForces.addIn(new Double2D((yard.width * 0.5 - me.x)* students.forceToSchoolMultiplier, (yard.height * 0.5 - me.y)* students.forceToSchoolMultiplier));// add a bit of randomnesssumForces.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的新位置。





0 0