1. 程式人生 > >Windows 下利用MFC實現的中國象棋棋盤繪製程式

Windows 下利用MFC實現的中國象棋棋盤繪製程式

最近在啃 Jeff ProsiseMFC Windows 程式設計》這本書,以前雖然也學過MFC,當時用的是孫鑫的視訊教程和書,學完後,似乎感覺有收穫,也的確可以編點小的MFC程式,不過總感覺沒有吃透,所以下決心,還是學這本書好,當時急於學習,偏偏網上這本書缺貨,所以買了大家評價都不錯的孫鑫那本,結果感覺還是不太好。突然想起某人說過,凡是教Windows程式設計的,書中圖片過多,基本不要看,說的雖然很過,不過的確感覺用IDE引匯出來的程式自己還是不能完全吃透,《MFC Windows 程式設計》就真的是主要靠手工程式碼,最近也學完一部分了,突發奇想畫個象棋棋盤,鞏固一下知識。完全手工程式碼輸入,僅以拋磚引玉,因為沒有考慮太多的縮放和解析度問題,所以程式在不同的機子上可能會有效果不好的情況,假如有時間再改改。不要奇怪我怎麼會在

.NET橫行的時代還在學大家都認為已經不行的MFC,我在網上晃了很久,發現懂MFC是很多公司的基本要求,無奈。。。。。。。。。。

ChineseChessBoard.h

class CMyApp : public CWinApp

{

public:

virtual BOOL InitInstance();

};

class CMainWindow : public CFrameWnd

{

public:

CMainWindow();

protected:

afx_msg voidOnPaint();

DECLARE_MESSAGE_MAP()

};

ChineseChessBoard.cpp

#include <afxwin.h>

#include <cmath>

#include "Hello.h"

CMyApp myApp;

//CMyApp member functions

BOOL CMyApp::InitInstance()

{

m_pMainWnd = new CMainWindow;

m_pMainWnd->ShowWindow(SW_SHOWMAXIMIZED);

m_pMainWnd->UpdateWindow();

return TRUE;

}

BEGIN_MESSAGE_MAP(CMainWindow,CFrameWnd)

ON_WM_PAINT()

END_MESSAGE_MAP()

CMainWindow::CMainWindow()

{

Create(NULL,_T("象棋棋盤"),WS_OVERLAPPEDWINDOW);

}

//CMainWindow mesage map and member functions

void CMainWindow::OnPaint()

{

CPaintDC dc(this);

CRect rect;

GetClientRect(&rect);

//畫背景

CBrush bkBrush(RGB(192,192,192));

dc.FillRect(rect,&bkBrush);

//確定畫象棋棋盤的範圍

rect.DeflateRect(200,30);

rect.OffsetRect(0,15);

//畫下象棋棋盤的背景

CBrush brush(RGB(128,128,128));

dc.FillRect(rect,&brush);

//無聊,給點立體感

rect.InflateRect(2,2);

dc.Draw3dRect(rect,RGB(255,255,255),RGB(255,255,255));

rect.DeflateRect(2,2);

//開始畫縱橫線

CPen pen(PS_SOLID,2,RGB(0,0,0));

CPen *pOldPen = dc.SelectObject(&pen);

int nGridWidth = rect.Width()/8;//橫向寬度,共格

int nGridHeight = rect.Height()/9;//縱向寬度,共格

for(int i = 0; i < 10; ++i)//畫橫線,10

{

int y = (nGridHeight * i) + rect.top;

dc.MoveTo(rect.left,y);

dc.LineTo(rect.right,y);

}

for(int i = 0; i < 8; ++i)//畫豎線,畫筆,空下最右的豎線

{

int x = (nGridWidth * i) + rect.left;

//中間為界限,無豎線

dc.MoveTo(x,rect.top);

dc.LineTo(x,rect.top + nGridHeight * 4);

dc.MoveTo(x,rect.top + nGridHeight * 5);

dc.LineTo(x,rect.bottom);

}

//補上左界限的豎筆及最右的豎線,此以rect.right畫最右豎線,最重合

dc.MoveTo(rect.left,rect.top + nGridHeight * 4);

dc.LineTo(rect.left,rect.top + nGridHeight * 5);

dc.MoveTo(rect.right,rect.top);

dc.LineTo(rect.right,rect.bottom);

//輸出文字“楚河漢界”

dc.SelectObject(pOldPen);

CRect textRect(rect.left,rect.top + nGridHeight * 4,

rect.right,rect.top + nGridHeight * 5);

CFont font;

font.CreatePointFont(520,_T("宋體"));

CFont *pOldFont = dc.SelectObject(&font);

dc.SetBkMode(TRANSPARENT);

dc.DrawText(_T("楚河漢界"),-1,textRect,

DT_SINGLELINE | DT_CENTER | DT_VCENTER);

dc.SelectObject(pOldFont);

}