Creating the "Spots" game (15-puzzle) using WinAPI in C++ involves several components:
- Window Creation and Management: Setting up the main window, handling resizing, and ensuring the layout adapts accordingly.
- Game Logic: Managing the tile positions, shuffling the tiles, handling user moves, and checking for the win condition.
- Timer: Implementing a timer to track the duration of the game.
- Rendering: Drawing the tiles with colors, numbers in Verdana font, and handling responsive layouts.
- File Operations: Saving the game result (time) to a file upon completion.
Below is the complete C++ WinAPI program that fulfills all the requirements. Make sure to compile it with a suitable compiler that supports WinAPI (like Visual Studio).
#include <windows.h>
#include <string>
#include <ctime>
#include <fstream>
#include <sstream>
#include "resource.h" // If you have resources, otherwise omit
using namespace std;
// Constants
const int GRID_SIZE = 4;
const int TOTAL_TILES = GRID_SIZE * GRID_SIZE;
const int TILE_MARGIN = 5;
const UINT TIMER_ID = 1;
const UINT TIMER_INTERVAL = 1000; // 1 second
// Global Variables
HINSTANCE hInst;
HWND hMainWnd;
HFONT hFont;
int tiles[GRID_SIZE][GRID_SIZE]; // 0 represents the empty cell
int emptyRow = GRID_SIZE - 1;
int emptyCol = GRID_SIZE - 1;
bool gameStarted = false;
int secondsElapsed = 0;
// Forward declarations
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
void InitializeGame();
bool IsMoveValid(int row, int col);
void MoveTile(int row, int col);
bool CheckWin();
void DrawTiles(HDC hdc, RECT clientRect);
void StartTimer();
void StopTimer();
void SaveResult();
// Entry Point
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
// Register Window Class
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.lpszClassName = "SpotsGameClass";
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
RegisterClass(&wc);
// Create Window
hMainWnd = CreateWindowEx(
0,
"SpotsGameClass",
"Spots (15-Puzzle)",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
400, 400,
NULL,
NULL,
hInstance,
NULL
);
if (!hMainWnd)
return 0;
ShowWindow(hMainWnd, nCmdShow);
UpdateWindow(hMainWnd);
// Message Loop
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
// Window Procedure
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
{
// Initialize Font
LOGFONT lf;
ZeroMemory(&lf, sizeof(LOGFONT));
lf.lfHeight = 24;
lf.lfWeight = FW_BOLD;
strncpy(lf.lfFaceName, "Verdana", LF_FACESIZE);
hFont = CreateFontIndirect(&lf);
// Initialize Game
InitializeGame();
}
break;
case WM_SIZE:
{
InvalidateRect(hwnd, NULL, TRUE);
}
break;
case WM_LBUTTONDOWN:
{
int xPos = LOWORD(lParam);
int yPos = HIWORD(lParam);
RECT clientRect;
GetClientRect(hwnd, &clientRect);
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
int tileWidth = (width - (GRID_SIZE + 1) * TILE_MARGIN) / GRID_SIZE;
int tileHeight = (height - (GRID_SIZE + 1) * TILE_MARGIN) / GRID_SIZE;
int col = xPos / (tileWidth + TILE_MARGIN);
int row = yPos / (tileHeight + TILE_MARGIN);
if (row >= 0 && row < GRID_SIZE && col >= 0 && col < GRID_SIZE)
{
if (IsMoveValid(row, col))
{
MoveTile(row, col);
InvalidateRect(hwnd, NULL, TRUE);
if (CheckWin())
{
StopTimer();
MessageBox(hwnd, ("You won in " + to_string(secondsElapsed) + " seconds!").c_str(), "Congratulations", MB_OK);
SaveResult();
InitializeGame();
InvalidateRect(hwnd, NULL, TRUE);
}
}
}
}
break;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
RECT clientRect;
GetClientRect(hwnd, &clientRect);
DrawTiles(hdc, clientRect);
EndPaint(hwnd, &ps);
}
break;
case WM_TIMER:
{
if (wParam == TIMER_ID)
{
secondsElapsed++;
InvalidateRect(hwnd, NULL, TRUE);
}
}
break;
case WM_DESTROY:
{
if (hFont)
DeleteObject(hFont);
PostQuitMessage(0);
}
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
// Initialize Game
void InitializeGame()
{
// Initialize tiles in order
int num = 1;
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
if (i == GRID_SIZE - 1 && j == GRID_SIZE - 1)
{
tiles[i][j] = 0; // Empty cell
emptyRow = i;
emptyCol = j;
}
else
{
tiles[i][j] = num++;
}
}
}
// Shuffle tiles by making random legal moves
srand((unsigned int)time(NULL));
int shuffleMoves = 1000;
for (int i = 0; i < shuffleMoves; i++)
{
// Choose a random direction to move the empty space
int direction = rand() % 4;
int newRow = emptyRow;
int newCol = emptyCol;
switch (direction)
{
case 0: newRow = emptyRow - 1; break; // Up
case 1: newRow = emptyRow + 1; break; // Down
case 2: newCol = emptyCol - 1; break; // Left
case 3: newCol = emptyCol + 1; break; // Right
}
if (newRow >= 0 && newRow < GRID_SIZE && newCol >= 0 && newCol < GRID_SIZE)
{
tiles[emptyRow][emptyCol] = tiles[newRow][newCol];
tiles[newRow][newCol] = 0;
emptyRow = newRow;
emptyCol = newCol;
}
}
// Reset Timer
StopTimer();
secondsElapsed = 0;
StartTimer();
}
// Check if the tile at (row, col) can be moved to empty space
bool IsMoveValid(int row, int col)
{
if ((abs(emptyRow - row) == 1 && emptyCol == col) ||
(abs(emptyCol - col) == 1 && emptyRow == row))
{
return true;
}
return false;
}
// Move the tile at (row, col) to the empty space
void MoveTile(int row, int col)
{
tiles[emptyRow][emptyCol] = tiles[row][col];
tiles[row][col] = 0;
emptyRow = row;
emptyCol = col;
}
// Check if the current arrangement is the winning one
bool CheckWin()
{
int num = 1;
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
if (i == GRID_SIZE - 1 && j == GRID_SIZE - 1)
{
if (tiles[i][j] != 0)
return false;
}
else
{
if (tiles[i][j] != num++)
return false;
}
}
}
return true;
}
// Draw Tiles
void DrawTiles(HDC hdc, RECT clientRect)
{
// Set font
HFONT oldFont = (HFONT)SelectObject(hdc, hFont);
SetBkMode(hdc, TRANSPARENT);
// Calculate tile size
int width = clientRect.right - clientRect.left;
int height = clientRect.bottom - clientRect.top;
int tileWidth = (width - (GRID_SIZE + 1) * TILE_MARGIN) / GRID_SIZE;
int tileHeight = (height - (GRID_SIZE + 1) * TILE_MARGIN) / GRID_SIZE;
// Draw Timer
std::ostringstream oss;
oss << "Time: " << secondsElapsed << "s";
std::string timerStr = oss.str();
SetTextColor(hdc, RGB(0, 0, 0));
TextOutA(hdc, 10, 10, timerStr.c_str(), timerStr.length());
// Draw Tiles
for (int i = 0; i < GRID_SIZE; i++)
{
for (int j = 0; j < GRID_SIZE; j++)
{
if (tiles[i][j] == 0)
continue; // Skip empty cell
RECT tileRect;
tileRect.left = TILE_MARGIN + j * (tileWidth + TILE_MARGIN);
tileRect.top = TILE_MARGIN + i * (tileHeight + TILE_MARGIN) + 30; // Offset for timer
tileRect.right = tileRect.left + tileWidth;
tileRect.bottom = tileRect.top + tileHeight;
// Set tile color
HBRUSH hBrush;
switch (tiles[i][j] % 5)
{
case 0: hBrush = CreateSolidBrush(RGB(255, 192, 192)); break; // Light Red
case 1: hBrush = CreateSolidBrush(RGB(192, 255, 192)); break; // Light Green
case 2: hBrush = CreateSolidBrush(RGB(192, 192, 255)); break; // Light Blue
case 3: hBrush = CreateSolidBrush(RGB(255, 255, 192)); break; // Light Yellow
case 4: hBrush = CreateSolidBrush(RGB(255, 192, 255)); break; // Light Pink
default: hBrush = CreateSolidBrush(RGB(200, 200, 200)); break;
}
FillRect(hdc, &tileRect, hBrush);
DeleteObject(hBrush);
// Draw Tile Border
Rectangle(hdc, tileRect.left, tileRect.top, tileRect.right, tileRect.bottom);
// Draw Number
std::string numStr = std::to_string(tiles[i][j]);
SIZE textSize;
GetTextExtentPoint32A(hdc, numStr.c_str(), numStr.length(), &textSize);
int textX = tileRect.left + (tileWidth - textSize.cx) / 2;
int textY = tileRect.top + (tileHeight - textSize.cy) / 2;
SetTextColor(hdc, RGB(0, 0, 0));
TextOutA(hdc, textX, textY, numStr.c_str(), numStr.length());
}
}
// Restore Font
SelectObject(hdc, oldFont);
}
// Start the timer
void StartTimer()
{
if (!gameStarted)
{
SetTimer(hMainWnd, TIMER_ID, TIMER_INTERVAL, NULL);
gameStarted = true;
}
}
// Stop the timer
void StopTimer()
{
if (gameStarted)
{
KillTimer(hMainWnd, TIMER_ID);
gameStarted = false;
}
}
// Save the result to a file
void SaveResult()
{
std::ofstream outFile("results.txt", std::ios::app);
if (outFile.is_open())
{
outFile << "Win Time: " << secondsElapsed << " seconds\n";
outFile.close();
}
}
// Resource Header (if needed)
// If you don't have any resources, you can omit this part.
// #include "resource.h"
Explanation of the Code:
-
Global Variables:
tiles[GRID_SIZE][GRID_SIZE]: Represents the grid of tiles. A value of 0 signifies the empty cell.
emptyRow and emptyCol: Track the position of the empty cell.
secondsElapsed: Tracks the time elapsed since the start of the game.
-
WinMain:
- Registers the window class and creates the main application window.
- Enters the message loop to process events.
-
WndProc:
- Handles various window messages:
WM_CREATE: Initializes the font and game.
WM_SIZE: Invalidates the window to trigger a repaint when resized.
WM_LBUTTONDOWN: Determines which tile was clicked and attempts to move it.
WM_PAINT: Handles drawing the tiles and the timer.
WM_TIMER: Updates the timer every second.
WM_DESTROY: Cleans up resources and exits the application.
-
InitializeGame:
- Sets up the tiles in order and then shuffles them by making random legal moves to ensure the puzzle is solvable.
- Resets and starts the timer.
-
IsMoveValid & MoveTile:
IsMoveValid: Checks if the clicked tile is adjacent to the empty space.
MoveTile: Swaps the clicked tile with the empty space.
-
CheckWin:
- Checks if the tiles are in the correct order, indicating the player has won.
-
DrawTiles:
- Draws each tile with a specific color, border, and number in Verdana font.
- Also displays the elapsed time at the top.
-
Timer Functions:
StartTimer: Starts the game timer.
StopTimer: Stops the game timer.
SaveResult: Appends the win time to a results.txt file.
Notes:
- Responsive Design: The
DrawTiles function calculates tile sizes based on the current window size, ensuring that tiles scale appropriately when the window is resized.
- Font: The Verdana font is created with a height of 24 and bold weight for better visibility.
- Colors: Tiles are given different light colors based on their number to make the game visually appealing.
- File Saving: Upon winning, the elapsed time is saved to a
results.txt file in the application's directory.
- Shuffling: The game is shuffled by making 1000 random valid moves, ensuring the puzzle is solvable.
Compilation Instructions:
-
Using Visual Studio:
- Create a new "Win32 Project".
- Replace the generated
WinMain and related functions with the code above.
- Ensure that you have the necessary project settings for a Windows application.
-
Using g++ (MinGW):
Final Remarks
This program provides a complete implementation of the "Spots" game with all the requested features. It adheres to the constraints of not using vector, algorithm, or map from the C++ Standard Library and relies solely on arrays and basic file operations. The use of WinAPI ensures that the application is responsive and native to the Windows environment.