
本文讲解如何在 Processing 中基于时间控制实现四组交通灯的协同亮灭逻辑,重点解决红灯4秒、黄绿灯各2秒的精确时序调度问题,避免使用阻塞式 Thread.sleep(),改用 millis() 实现非阻塞、可扩展的状态机驱动方案。
本文讲解如何在 processing 中基于时间控制实现四组交通灯的协同亮灭逻辑,重点解决红灯4秒、黄绿灯各2秒的精确时序调度问题,避免使用阻塞式 `thread.sleep()`,改用 `millis()` 实现非阻塞、可扩展的状态机驱动方案。
在 Processing 中实现交通灯系统,核心挑战不是绘图,而是精确、独立且可同步的时间调度。你当前代码中尝试用 millis() % 6000 划分 6 秒周期,但存在两个关键问题:
- 逻辑错位:tipo == 1(垂直向)与 tipo == 2(水平向)的相位未真正互补(例如红灯应错开 4 秒),导致冲突;
- 状态耦合:所有灯共享同一 startTime,无法支持不同灯组按自身节奏运行(如垂直红灯持续 4 秒,水平绿灯需同步亮起 4 秒)。
✅ 正确解法是采用 “状态机 + 时间戳”模式:为每个交通灯维护当前状态(RED/YELLOW/GREEN)、进入该状态的起始毫秒数,并在 update() 中实时判断是否超时切换。
以下是重构后的 lane 类关键逻辑(第三标签页):
// 在 lane 类顶部定义状态常量
static final int STATE_RED = 0;
static final int STATE_YELLOW = 1;
static final int STATE_GREEN = 2;
// 替换原字段:移除 alphav/alphaa/alphaver 等冗余变量
int currentState = STATE_RED;
long stateStartTime; // 记录当前状态开始时间(毫秒)
int[] durations = {4000, 2000, 2000}; // 红→黄→绿 各自持续时间(ms)
lane(float positionx, float positiony, float angleS, color c, float x, float y,
float velocidade_max, float velocidade_atual, float angle, int tipo, int size) {
super(x, y, velocidade_max, velocidade_atual, angle);
this.positionx = positionx;
this.positiony = positiony;
this.angleS = angleS;
this.tipo = tipo;
this.stateStartTime = millis(); // 初始化状态时间
}
void update() {
long now = millis();
long elapsed = now - stateStartTime;
// 检查是否需要切换状态
if (elapsed >= durations[currentState]) {
// 根据灯类型决定下一状态逻辑(关键!)
if (tipo == 1) { // 垂直向灯:红(4s) → 绿(2s) → 黄(2s) → 循环
currentState = (currentState + 1) % 3;
if (currentState == 2) currentState = 1; // 跳过黄→红,改为绿→黄→红(见下方说明)
} else if (tipo == 0) { // 水平向灯:与垂直向互补 → 绿(4s) → 黄(2s) → 红(2s)
currentState = (currentState + 1) % 3;
if (currentState == 0) currentState = 2; // 红→绿?不,应红→绿→黄→红循环
}
stateStartTime = now; // 重置计时
}
}
// ✅ 更健壮的相位设计(推荐):
// 定义完整 8 秒大周期:垂直红(4s) ↔ 水平绿(4s),中间插入黄灯过渡
// 修改 update() 为统一周期驱动:
void update() {
long now = millis();
int cyclePos = (int)((now % 8000) / 1000); // 0~7 秒位置
if (tipo == 1) { // 垂直灯
if (cyclePos <p>在 draw() 中,根据 currentState 设置透明度:</p><pre class="brush:php;toolbar:false;">void draw() {
pushMatrix();
translate(positionx, positiony);
rotate(angleS);
fill(BLACK);
rect(0, 0, 150, 50);
// 仅点亮当前状态灯,其余设为低透明度(150 是半透,0 为全隐)
int alphaRed = (currentState == STATE_RED) ? 255 : 150;
int alphaGreen = (currentState == STATE_GREEN) ? 255 : 150;
int alphaYellow= (currentState == STATE_YELLOW)? 255 : 150;
fill(RED, alphaRed);
circle(120, 25, 40);
fill(GREEN, alphaGreen);
circle(75, 25, 40);
fill(YELLOW, alphaYellow);
circle(30, 25, 40);
fill(BLACK);
rect(-40, 14, 40, 20);
popMatrix();
}⚠️ 重要注意事项:
- 切勿使用 Thread.sleep():Processing 的 draw() 是单线程循环,sleep() 会冻结整个画面和交互,导致卡顿甚至崩溃;
- millis() 是唯一可靠时基:它返回自程序启动的毫秒数,稳定、非阻塞,适合所有定时任务;
- 相位同步靠全局周期:用 millis() % 8000 统一驱动所有灯,确保垂直红(0–3s)与水平绿(4–7s)严格错开;
- 调试技巧:在 draw() 中添加 text("T:" + (millis()%8000)/1000.0, 10, 20) 实时查看当前秒数,验证相位逻辑。
通过此方案,你将获得一个可预测、易维护、符合真实交通规则的信号灯系统——红灯守信 4 秒,黄灯预警 2 秒,绿灯通行 2 秒,且两组灯始终互补,保障路口安全。











