今天终于写完第一个最基本的实验游戏啦!!!!!呵呵!!!是记忆游戏,是4*4格里面找相同的图像。
游戏的基本核心算法:
void GameStart(HWND hwnd)
{
//生成随机种子
srand(GetTickCount());
//创建并加载位图
HDC hdc = GetDC(hwnd);
g_pTitles[0] = new Bitmap(hdc, IDB_BLANK, g_hInsce);
g_pTitles[1] = new Bitmap(hdc, IDB_TILES1, g_hInsce);
g_pTitles[2] = new Bitmap(hdc, IDB_TILES2, g_hInsce);
g_pTitles[3] = new Bitmap(hdc, IDB_TILES3, g_hInsce);
g_pTitles[4] = new Bitmap(hdc, IDB_TILES4, g_hInsce);
g_pTitles[5] = new Bitmap(hdc, IDB_TILES5, g_hInsce);
g_pTitles[6] = new Bitmap(hdc, IDB_TILES6, g_hInsce);
g_pTitles[7] = new Bitmap(hdc, IDB_TILES7, g_hInsce);
g_pTitles[8] = new Bitmap(hdc, IDB_TILES8, g_hInsce);
//清空方块状态和图像
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
{
g_bTileStat[i][j] = FALSE; //方块没有配对是FALSE
g_iTitles[i][j] = 0;
}
//随机初始化方块图像
for(i = 0; i < 2; i++)
for(int j = 1; j < 9; j++)
{
int x = rand() % 4;
int y = rand() % 4;
while(g_iTitles[x][y] != 0)
{
x = rand() % 4;
y = rand() % 4;
}
g_iTitles[x][y] = j;
}
//初始化方块选择配对尝试计数
g_pTile1.x = g_pTile1.y = -1;
g_pTile2.x = g_pTile2.y = -1;
g_iMatches = g_iTries = 0;
}
void GamePaint(HDC hdc)
{
//绘制方块
int iTileWidth = g_pTitles[0] ->GetWidth();
int iTileHeight = g_pTitles[0] ->GetHeight();
for(int i = 0; i < 4; i++)
for(int j = 0; j < 4; j++)
if(g_bTileStat[i][j] || ((i == g_pTile1.x) && (j == g_pTile1.y)) ||
((i == g_pTile2.x) && (j == g_pTile2.y)))
g_pTitles[g_iTitles[i][j]] -> Draw(hdc, i * iTileWidth, j * iTileHeight, TRUE);
else
g_pTitles[0] -> Draw(hdc, i * iTileWidth, j * iTileHeight, TRUE);
}
void MouseButtonDown(int x, int y, BOOL bLeft)
{
// Determine which tile was clicked
int iTileX = x / g_pTitles[0]->GetWidth();
int iTileY = y / g_pTitles[0]->GetHeight();
// Make sure the tile hasn't already been matched
if (!g_bTileStat[iTileX][iTileY])
{
// See if this is the first tile selected
if (g_pTile1.x == -1)
{
// Set the first tile selection
g_pTile1.x = iTileX;
g_pTile1.y = iTileY;
}
else if ((iTileX != g_pTile1.x) || (iTileY != g_pTile1.y))
{
if (g_pTile2.x == -1)
{
// Increase the number of tries
g_iTries++;
// Set the second tile selection
g_pTile2.x = iTileX;
g_pTile2.y = iTileY;
// See if it's a match
if (g_iTitles[g_pTile1.x][g_pTile1.y] == g_iTitles
[g_pTile2.x][g_pTile2.y])
{
// Set the tile state to indicate the match
g_bTileStat[g_pTile1.x][g_pTile1.y] = TRUE;
g_bTileStat[g_pTile2.x][g_pTile2.y] = TRUE;
// Clear the tile selections
g_pTile1.x = g_pTile1.y = g_pTile2.x = g_pTile2.y = -1;
// Update the match count and check for winner
if (++g_iMatches == 8)
{
TCHAR szText[64];
wsprintf(szText, "You won in %d tries.", g_iTries);
MessageBox(g_pGame->GetWnd(), szText, TEXT("Brainiac"), MB_OK);
}
}
}
else
{
// Clear the tile selections
g_pTile1.x = g_pTile1.y = g_pTile2.x = g_pTile2.y = -1;
}
}
// Force a repaint to update the tile
InvalidateRect(g_pGame->GetWnd(), NULL, FALSE);
}
}