交通灯模拟程序中 SetTimer 的使用
现况描述:
我采用单文档做的程序,
在void CTrafficLight_SimulateView::OnBegin()
{
// TODO: Add your command handler code here
……
SetTimer(1,50,NULL); // 用于车辆的移动更新
SetTimer(2,10000,NULL); // 控制 “红绿” 灯交替
m_nDelaytime=0;
……
}
中定义了如上定时器。
-----------------------------
在 …… OnTimer(UINT nIDEvent)
{
……
if(nIDEvent==2)
{
m_nDelaytime+=1;
m_nDelaytime=m_nDelaytime % 2;
InvalidateRect(CRect((nCenterX+80),(nCenterY-90),(nCenterX+120),(nCenterY)));
}
……
}
----------------------------
在 OnDraw 中已经实现了
……
if(m_nDelaytime==0)
{
点亮绿灯,红灯此时灭。
}
else
{
点亮红灯,绿灯此时灭。
}
……
---------------------------
现在我的问题是,把黄灯的亮和灭加进去的话,该怎么做?请求高手帮忙,感激不尽!!!
[解决办法]
if(nIDEvent==2)
{
//这里用另一个变量控制黄灯事件
m_nDelaytime+=1;
m_nDelaytime=m_nDelaytime % 2;
InvalidateRect(CRect((nCenterX+80),(nCenterY-90),(nCenterX+120),(nCenterY)));
}
if(m_nDelaytime==0)
{
点亮绿灯,红灯此时灭。
}
if else(另一个变量)
{
//亮黄灯
}
else
{
点亮红灯,绿灯此时灭。
}
[解决办法]
if else(另一个变量)
===================
else if(另一个变量)
{
//亮黄灯
}
lz 仔细点嘛
[解决办法]
void CTrafficLight::OnTimer(UINT nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
if (2 == nIDEvent)
{
KillTimer(2);
m_nLight++;
m_nLight %= 3;
switch (m_nLight)
{
case 0:
SetTimer(2, 10000, NULL);
break;
case 1:
SetTimer(2, 2000, NULL);
break;
case 2:
SetTimer(2, 8000, NULL);
break;
}
Invalidate();
}
CWnd::OnTimer(nIDEvent);
}
void CTrafficLight::OnDraw(CDC* pDC)
{
CBrush br(RGB(0, 0, 0));
CPen *pOldPen = (CPen*)pDC-> SelectStockObject(NULL_PEN);
CBrush *pOldBrush = pDC-> SelectObject(&br);
CRect rc(10, 10, 20, 20);
for (int i = 0; i < 3; i++)
{
pDC-> Ellipse(rc);
rc.OffsetRect(0, 10);
}
pDC-> SelectObject(pOldBrush);
br.DeleteObject();
if (m_nLight > = 0 && m_nLight < 3)
{
switch (m_nLight)
{
case 0:
br.CreateSolidBrush(RGB(255, 0, 0));
break;
case 1:
br.CreateSolidBrush(RGB(255, 255, 0));
break;
case 2:
br.CreateSolidBrush(RGB(0, 255, 0));
break;
}
pOldBrush = pDC-> SelectObject(&br);
rc.SetRect(10, 10, 20, 20);
rc.OffsetRect(0, m_nLight * 10);
pDC-> Ellipse(rc);
pDC-> SelectObject(pOldBrush);
br.DeleteObject();
}
pDC-> SelectObject(pOldPen);
}