我正在做一个交通灯模拟,现在我试图让交通灯切换颜色(包括汽车和行人交通灯)。问题是,我有8个交通灯每个十字路口和12个交叉口。我试过使用计时器和计数器,但问题是间隔没有得到尊重:
如果开始的颜色是红色,红色的时间是8,绿色的时间是10,那么当颜色变成绿色的时候,在两秒钟内它就会变回红色。以下是计时器代码:
private void timerTrafficLights_Tick(object sender, EventArgs e)
{
counter++;
foreach(TrafficLight t in trafficLights)
{
if(counter%t.RedTime==0 &&t.TrafficColor==TrafficLightColor.RED)
{
t.SwitchLight(t, TrafficLightColor.GREEN, t.ID);
}
else if(counter % t.GreenTime==0 && t.TrafficColor==TrafficLightColor.GREEN)
{
t.SwitchLight(t, TrafficLightColor.RED, t.ID);
}
}
foreach(PedestrianLight p in pedestrianLights)
{
if(counter % p.RedTime==0 && p.LightColor == PedestrianLightColor.RED)
{
p.SwitchLight(p, p.ID, PedestrianLightColor.GREEN);
}
else if (counter % p.GreenTime ==0 && p.LightColor == PedestrianLightColor.GREEN)
{
p.SwitchLight(p, p.ID, PedestrianLightColor.RED);
}
}
UI.InvalidateEvent.InvalidatePanel();
}
private void TimerTrafficLights()
{
timerTrafficLights.Interval = 1000;
timerTrafficLights.Tick += new EventHandler(timerTrafficLights_Tick);
timerTrafficLights.Start();
}当模拟开始时,计时器启动,模拟开始时计数器的值为0。
发布于 2016-05-21 16:39:40
我会以面向对象的方式来处理这个任务。改变TrafficLight (和PedestrianLight)颜色的不是您的计时器,而是类本身知道何时该更改颜色。
在这个场景中,您的TrafficLight类可能如下所示
// I show just the TrafficLight class, but the same is true for the
// PedestrianLight class (better if both derives from the same base class)
public class TrafficLight
{
private int counter = 0;
public TrafficLightColor TrafficColor { get; set; }
public int ID {get;set;}
public int RedTime { get; set; }
public int GreenTime { get; set; }
public void SwitchLight(TrafficLightColor color)
{
if(color != TrafficColor)
{
TrafficColor = color;
// Restart the counter everytime the color changes.....
// So the next change happens for the current color.
counter = 0;
}
}
public void Tick()
{
if (this.TrafficColor == TrafficLightColor.RED && counter == RedTime)
SwitchLight(TrafficLightColor.GREEN);
else if ((this.TrafficColor == TrafficLightColor.GREEN && counter == GreenTime)
SwitchLight(TrafficLightColor.RED);
}
}现在,Timer事件只对TrafficLight (和PedestrianLight)的每个实例调用Tick方法。
private void timerTrafficLights_Tick(object sender, EventArgs e)
{
foreach(TrafficLight t in trafficLights)
t.Tick();
foreach(PedestrianLight p in pedestrianLights)
p.Tick();
UI.InvalidateEvent.InvalidatePanel();
}这样,您就不需要在类之外保留一个外部滴答计数器。每个实例都知道自己的边界,并在时机成熟时改变颜色。您甚至可以为红灯和绿灯设置不同的时间,因为更改颜色的所有逻辑都包含在实例本身中,它与自己的红绿设置一起工作。
发布于 2016-05-21 15:18:04
把这样的东西加到交通/行人灯类中
public int startTime;有了这个,您只需要存储开始时间。在每一个滴答,你将检查差异是否大于阈值。更改后,将时间重置为当前。
https://stackoverflow.com/questions/37364463
复制相似问题