生活随笔
收集整理的這篇文章主要介紹了
C++五子棋(二)——游戏界面与棋子渲染
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
準備
我們首先要在程序中定義一個名為drawPNG的函數,用于輸出png格式圖片并使背景透明
#include <graphics.h>
void drawPNG(IMAGE
* picture
, int picture_x
, int picture_y
)
{DWORD
* dst
= GetImageBuffer(); DWORD
* draw
= GetImageBuffer();DWORD
* src
= GetImageBuffer(picture
); int picture_width
= picture
->getwidth(); int picture_height
= picture
->getheight(); int graphWidth
= getwidth(); int graphHeight
= getheight(); int dstX
= 0; for (int iy
= 0; iy
< picture_height
; iy
++){for (int ix
= 0; ix
< picture_width
; ix
++){int srcX
= ix
+ iy
* picture_width
; int sa
= ((src
[srcX
] & 0xff000000) >> 24); int sr
= ((src
[srcX
] & 0xff0000) >> 16); int sg
= ((src
[srcX
] & 0xff00) >> 8); int sb
= src
[srcX
] & 0xff; if (ix
>= 0 && ix
<= graphWidth
&& iy
>= 0 && iy
<= graphHeight
&& dstX
<= graphWidth
* graphHeight
){dstX
= (ix
+ picture_x
) + (iy
+ picture_y
) * graphWidth
; int dr
= ((dst
[dstX
] & 0xff0000) >> 16);int dg
= ((dst
[dstX
] & 0xff00) >> 8);int db
= dst
[dstX
] & 0xff;draw
[dstX
] = ((sr
* sa
/ 255 + dr
* (255 - sa
) / 255) << 16) | ((sg
* sa
/ 255 + dg
* (255 - sa
) / 255) << 8) | (sb
* sa
/ 255 + db
* (255 - sa
) / 255); }}}
}
初始化游戲
創建游戲界面
素材大小
- 通過查看res素材文件夾下的棋盤2.jpg可知,圖片大小為897*895
- 通過圖片大小計算可得一個格子的大小為67.4
- 先記下這些參數,后面對我們開發特別重要
創建窗口
- 首先,定義 float類型常量 BLOCKSIZE,即格子大小
const float BLOCKSIZE
= 67.4;
void init(){initgraph(897,895); loadimage(0,"res/棋盤2.jpg");
}
加載音樂
#include <mmsystem.h>
#pragma comment(lib,"winmm.lib");
- 繼續在 init() 函數中添加播放 提示語音(res/start.wav) 的語句(注意添加位置)
mciSendString("play res/start.wav",0,0,0);
棋子渲染
加載素材
- 定義 IMAGE 類型的全局變量 chessWhite 和 chessBlack
IMAGE chessWhite
;
IMAGE chessBlack
;
- 在 init() 函數定義中添加加載圖片語句如下(將black.png白棋子素材和white.png黑棋子素材加載到變量)
loadimage(&chessBlack
, "res/black.png",BLOCKSIZE
,BLOCKSIZE
,true);
loadimage(&chessWhite
, "res/white.png", BLOCKSIZE
, BLOCKSIZE
, true);
實現渲染
typedef enum{CHESS_WHITE
= -1,CHESS_BLACK
= 1
} chess_kind_t
;
- MARGIN_X為上邊界大小,MARGIN_Y為左邊界大小,因此我們定義同名全局常量
const int MARGIN_X
= 44;
const int MARGIN_Y
= 43;const int BOARD_GRAD_SIZE
= 13;
- 之后定義函數 chessDown() 用于打印棋子圖片
void chessDown(int row
, int col
, chess_kind_t kind
){mciSendString("play res/down7.wav",0,0,0); int x
= MARGIN_X
+ col
* BLOCKSIZE
- 0.5 * BLOCKSIZE
;int y
= MARGIN_Y
+ row
* BLOCKSIZE
- 0.5 * BLOCKSIZE
;if(kind
== CHESS_WHITE
){drawPNG(&chessWhite
,x
,y
);}else{drawPNG(&chessBlack
,x
,y
);}}
結束
到了這里,我們已經實現了游戲界面的初始化和棋子渲染了,接下來我們就要實現獲取鼠標信息來判斷有效點擊了
總結
以上是生活随笔為你收集整理的C++五子棋(二)——游戏界面与棋子渲染的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。