帮我写一段MFC打地鼠代码
时间: 2023-06-12 15:01:53 浏览: 152
好的,请稍等,我为您生成一段MFC打地鼠代码:
```c++
#include <afxwin.h>
#include <time.h>
const int GAME_WIDTH = 500;
const int GAME_HEIGHT = 500;
const int TIMER_INTERVAL = 500;
const int HOLE_SIZE = 50;
const int HIT_THRESHOLD = 20;
class CGameWindow : public CFrameWnd {
public:
CGameWindow() {
Create(NULL, L"MFC打地鼠游戏", WS_OVERLAPPEDWINDOW, CRect(0, 0,
GAME_WIDTH, GAME_HEIGHT));
srand(time(0));
SetTimer(1, TIMER_INTERVAL, NULL);
}
afx_msg void OnPaint() {
CPaintDC dc(this);
for (int i = 0; i < m_holes.size(); i++) {
CRect holeRect = GetHoleRect(m_holes[i]);
if (m_holes[i].hit) {
dc.FillSolidRect(holeRect, RGB(255, 0, 0));
} else {
dc.FillSolidRect(holeRect, RGB(127, 127, 127));
}
}
}
afx_msg void OnLButtonDown(UINT flags, CPoint point) {
for (int i = 0; i < m_holes.size(); i++) {
if (GetHoleRect(m_holes[i]).PtInRect(point)) {
if (!m_holes[i].hit) {
m_holes[i].hit = true;
Invalidate();
}
}
}
}
afx_msg void OnTimer(UINT_PTR timerID) {
m_timerCount++;
if (m_timerCount % 5 == 0) {
GenerateNewHole();
}
for (int i = 0; i < m_holes.size(); i++) {
if (m_holes[i].hit) {
m_holes[i].hitCountdown--;
if (m_holes[i].hitCountdown == 0) {
m_holes.erase(m_holes.begin() + i);
i--;
}
} else {
m_holes[i].lifetime--;
if (m_holes[i].lifetime == 0) {
m_holes.erase(m_holes.begin() + i);
i--;
}
}
}
Invalidate();
}
DECLARE_MESSAGE_MAP();
private:
struct Hole {
int x, y;
bool hit;
int hitCountdown;
int lifetime;
};
std::vector<Hole> m_holes;
int m_timerCount = 0;
CRect GetHoleRect(Hole hole) {
return CRect(hole.x - HOLE_SIZE / 2, hole.y - HOLE_SIZE / 2,
hole.x + HOLE_SIZE / 2, hole.y + HOLE_SIZE / 2);
}
void GenerateNewHole() {
Hole newHole;
newHole.x = rand() % (GAME_WIDTH - HOLE_SIZE) + HOLE_SIZE / 2;
newHole.y = rand() % (GAME_HEIGHT - HOLE_SIZE) + HOLE_SIZE / 2;
newHole.hit = false;
newHole.hitCountdown = 3;
newHole.lifetime = 10;
m_holes.push_back(newHole);
}
};
BEGIN_MESSAGE_MAP(CGameWindow, CFrameWnd)
ON_WM_PAINT()
ON_WM_LBUTTONDOWN()
ON_WM_TIMER()
END_MESSAGE_MAP()
class CGameApp : public CWinApp {
public:
virtual BOOL InitInstance() {
CGameWindow* pMainWnd = new CGameWindow;
m_pMainWnd = pMainWnd;
pMainWnd->ShowWindow(m_nCmdShow);
pMainWnd->UpdateWindow();
return TRUE;
}
};
CGameApp theApp;
```
这段代码实现一个简单的打地鼠游戏,当您单击地鼠,地鼠会变成红色,并在3秒钟后消失。游戏每隔0.5秒钟刷新一次画面,每隔5秒钟会生成一个新的地鼠出现在随机位置。请注意,这只是一个简单示例,您可能需要根据您的实际需求进行修改和扩展。
阅读全文