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

现在我们给学生增加 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的新位置。





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Anyanyamy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值