帮我写一段MFC打地鼠游戏代码
时间: 2023-06-12 15:01:55 浏览: 78
好的,以下是一段基于MFC的打地鼠游戏代码:
首先,在 MFC 预定义的应用程序类(如 CWinApp)中添加以下定义:
#define MAX_MOUSES 9
#define TIMER_ID 1234
然后,在窗口类(如 CMainFrame)中添加以下变量和函数声明:
private:
int m_nScore;
int m_nMouses[MAX_MOUSES];
int m_nCurrentMouseIndex;
CRect m_rcHole;
bool m_bIsGameOver;
void StartGame();
void EndGame();
void GenerateMouses();
接着,在窗口类的构造函数中添加以下初始化代码:
CMainFrame::CMainFrame()
{
// 初始化游戏参数
m_nScore = 0;
m_nCurrentMouseIndex = 0;
m_bIsGameOver = true;
m_rcHole = CRect(200, 200, 400, 400);
// 创建计时器
SetTimer(TIMER_ID, 1000, NULL);
}
在窗口类中定义以下处理函数:
void CMainFrame::OnPaint()
{
CPaintDC dc(this); // 用于绘制的设备上下文
// 绘制地洞
dc.FillSolidRect(m_rcHole, RGB(150, 75, 0));
// 绘制得分
CString strScore;
strScore.Format(_T("Score: %d"), m_nScore);
dc.TextOut(10, 10, strScore);
// 绘制老鼠
CRect rcMouse;
for (int i = 0; i < MAX_MOUSES; i++)
{
if (m_nMouses[i] == 1)
{
rcMouse = CRect(
m_rcHole.left + 20*(i%3),
m_rcHole.top + 20*(i/3),
m_rcHole.left + 20*(i%3+1),
m_rcHole.top + 20*(i/3+1));
dc.FillSolidRect(rcMouse, RGB(255, 255, 255));
}
}
}
void CMainFrame::OnLButtonDown(UINT nFlags, CPoint point)
{
if (!m_bIsGameOver && m_rcHole.PtInRect(point))
{
// 点击老鼠
for (int i = 0; i < MAX_MOUSES; i++)
{
CRect rcMouse(
m_rcHole.left + 20*(i%3),
m_rcHole.top + 20*(i/3),
m_rcHole.left + 20*(i%3+1),
m_rcHole.top + 20*(i/3+1));
if (m_nMouses[i] == 1 && rcMouse.PtInRect(point))
{
m_nMouses[i] = 0;
m_nCurrentMouseIndex--;
m_nScore += 10;
if (m_nCurrentMouseIndex <= 0)
{
// 重新生成老鼠
GenerateMouses();
}
break;
}
}
}
else if (m_bIsGameOver)
{
// 开始新游戏
StartGame();
}
}
void CMainFrame::OnTimer(UINT_PTR nIDEvent)
{
if (nIDEvent == TIMER_ID && !m_bIsGameOver)
{
// 产生新老鼠
if (m_nCurrentMouseIndex < MAX_MOUSES)
{
int nIndex;
do {
nIndex = rand() % MAX_MOUSES;
} while (m_nMouses[nIndex] == 1);
m_nMouses[nIndex] = 1;
m_nCurrentMouseIndex++;
}
else
{
// 游戏结束
EndGame();
}
// 重绘窗口
Invalidate();
}
CFrameWnd::OnTimer(nIDEvent);
}
void CMainFrame::StartGame()
{
m_nScore = 0;
m_nCurrentMouseIndex = 0;
memset(m_nMouses, 0, sizeof(m_nMouses));
GenerateMouses();
m_bIsGameOver = false;
}
void CMainFrame::EndGame()
{
KillTimer(TIMER_ID);
if (AfxMessageBox(_T("Game over!\nTry again?"), MB_YESNO) == IDYES)
{
StartGame();
}
else
{
m_bIsGameOver = true;
}
}
void CMainFrame::GenerateMouses()
{
int nCount = rand() % 5 + 5;
for (int i = 0; i < nCount; i++)
{
int nIndex;
do {
nIndex = rand() % MAX_MOUSES;
} while (m_nMouses[nIndex] == 1);
m_nMouses[nIndex] = 1;
m_nCurrentMouseIndex++;
}
}
完成以上代码编写后,即可得到简单且流畅地打地鼠游戏!