Visual C++游戏编程基础之平面地图贴图

一、基本思路

1.地图由3*4张图块组成,列方向4块,行方向3块,这里有3种不同颜色的图块;

2.将3张不同的图块分别用0、1、2表示,建立地图数组,8行8列,用0、1、2这三个数进行初始化

3.建立空白位图存到mdc,循环整个地图数组,从第一个开始,根据数组值(0或1或2)取出对应的地图,存到内存bufdc中

4.根据索引值计算行列编号,计算贴图坐标,并一张一张的贴到mdc中,mdc最后再贴到hdc;

   公式:列编号=索引值/每一列图块的个数

              行编号=索引值%每一列图块的个数

二、代码如下


#include "stdafx.h"
#include 

HINSTANCE hInst;
HBITMAP fullmap;//bitmap handle,存储初始化函数中完成的地图
HDC		mdc;   //内存DC句柄mdc

const int rows = 8,cols = 8;

ATOM				MyRegisterClass(HINSTANCE hInstance);
BOOL				InitInstance(HINSTANCE, int);
LRESULT CALLBACK	WndProc(HWND, UINT, WPARAM, LPARAM);
void				MyPaint(HDC hdc);

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	MSG msg;

	MyRegisterClass(hInstance);

	if (!InitInstance (hInstance, nCmdShow)) 
	{
		return FALSE;
	}

	while (GetMessage(&msg, NULL, 0, 0)) 
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	
	return msg.wParam;
}

ATOM MyRegisterClass(HINSTANCE hInstance)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX); 
	wcex.style			= CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc	= (WNDPROC)WndProc;
	wcex.cbClsExtra		= 0;
	wcex.cbWndExtra		= 0;
	wcex.hInstance		= hInstance;
	wcex.hIcon			= NULL;
	wcex.hCursor		= NULL;
	wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName	= NULL;
	wcex.lpszClassName	= "canvas";
	wcex.hIconSm		= NULL;

	return RegisterClassEx(&wcex);
}

BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;
	HDC hdc,bufdc;

	hInst = hInstance;

	hWnd = CreateWindow("canvas", "绘图窗口" , WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

	if (!hWnd)
	{
		return FALSE;
	}

	MoveWindow(hWnd,10,10,430,450,true);
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);
	
	int mapIndex[rows*cols] = { 2,2,2,2,0,1,0,1,  //材1
								0,2,2,0,0,0,1,1,  //材2
								0,0,0,0,0,0,0,1,  //材3
								2,0,0,0,0,0,2,2,  //材4
								2,0,0,0,0,2,2,2,  //材5
								2,0,0,0,2,2,0,0,  //材6
								0,0,2,2,2,0,0,1,  //材7
								0,0,2,0,0,0,1,1 }; //材8
	hdc = GetDC(hWnd);
	mdc = CreateCompatibleDC(hdc);
	bufdc = CreateCompatibleDC(hdc);
	fullmap = CreateCompatibleBitmap(hdc,cols*50,rows*50);//行数*图块宽;列数*图块高,建立空白位图fullmap

	SelectObject(mdc,fullmap);//将fullmap存入到mdc中

	HBITMAP map[3];
	char filename[20] = "";
	int rowNum,colNum;
	int i,x,y;

	for(i=0;i<3;i++)
	{
		sprintf(filename,"map%d.bmp",i);//利用循环把图片的文件名存到filename
		map[i] = (HBITMAP)LoadImage(NULL,filename,IMAGE_BITMAP,50,50,LR_LOADFROMFILE);
	}

	for (i=0;i

三、效果

Visual C++游戏编程基础之平面地图贴图_第1张图片

你可能感兴趣的:(游戏开发)