老师视频里是这样定义枚举等的,上面4个一组有opposite和next下面一组没有
S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false),
S2E(null,null,true),E2N(null,null,true),N2W(null,null,true),W2S(null,null,true);
而在ControllerLamp里面currentLamp = Lamp.S2N;currentLamp.light();指定了currentLamp=SN2;
如果我想随机挑选一个非右转弯的灯做启动灯,而不是指定一个灯做启动灯就必须
S2N("N2S","S2W",false),S2W("N2E","E2W",false),E2W("W2E","E2S",false),E2S("W2N","S2N",false),
N2S("S2N","N2E",false),N2E("S2W","W2E",false),W2E("E2W","W2N",false),W2N("E2S","N2S",false),
让这8个灯都有逻辑关系,而这样和下面代码
public void light(){
this.lighted = true;
if(opposite != null){
Lamp.valueOf(opposite).light();
}
又会形成死循环。
我就基于这种想法有点思路,希望大家指正
//定义一个开关锁bSwitch,让启动灯这一组的bSwitch一直为true,而opposite一组的一直为false
public boolean bSwitch
public void light()
{
this.lighted=true;
if(opposite!=null)
{
if(bSwitch)
{
Lamp.valueOf(opposite).bSwitch=false;//启动灯被设定后,自己点亮,然后把opposite的开关锁掉 //不让opposite再打开自己,避免形成无限循环
Lamp.valueOf(opposite).light();
System.out.println(name()+" lamp is green.下面总共应该有6个方向能看到车");
}
}
}
//等变红,同时相对方向上的等也变红,而且让next变绿
public Lamp blackOut()
{
this.lighted=false;
if(opposite!=null)
{
if(bSwitch)//这里opposite的bSwitch已经是false了
{
//Lamp.valueOf(opposite).bSwitch=false;
Lamp.valueOf(opposite).blackOut();
System.out.println("绿灯从"+this+"切换到"+next);
}
//this.bSwitch=true;
}
Lamp nextLamp=null;
if(bSwitch){
//由于opposite也有next,所以让开关锁锁住对方的next,不让他自己打开,而是这启动等这一组的作为opposite打开
if(next!=null)
{
nextLamp=Lamp.valueOf(next);
nextLamp.light();
}
}
return nextLamp;
}
[ 本帖最后由 BlackHorse 于 2011-07-19 18:02 编辑 ] |
|