以下是一个简单的带登录界面的游戏代码,使用C++和WinAPI编写:
```cpp
#include <Windows.h>
#include <string>
// 全局变量
HINSTANCE hInst;
HWND hwndMain, hwndLogin, hwndUsername, hwndPassword;
// 函数声明
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK LoginProc(HWND, UINT, WPARAM, LPARAM);
// WinMain函数
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
hInst = hInstance;
// 注册窗口类
WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.hInstance = hInstance;
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.lpszClassName = L"MainWindow";
RegisterClassEx(&wcex);
// 创建主窗口
hwndMain = CreateWindow(L"MainWindow", L"游戏", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600, nullptr, nullptr, hInstance, nullptr);
if (!hwndMain)
{
return FALSE;
}
// 显示主窗口
ShowWindow(hwndMain, nCmdShow);
UpdateWindow(hwndMain);
// 进入消息循环
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
// 主窗口过程函数
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
// 创建登录窗口
hwndLogin = CreateWindow(L"STATIC", L"", WS_POPUP | WS_BORDER | SS_CENTER, 300, 200, 200, 160, hWnd, nullptr, hInst, nullptr);
hwndUsername = CreateWindow(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER, 50, 30, 100, 20, hwndLogin, nullptr, hInst, nullptr);
hwndPassword = CreateWindow(L"EDIT", L"", WS_CHILD | WS_VISIBLE | WS_BORDER | ES_PASSWORD, 50, 70, 100, 20, hwndLogin, nullptr, hInst, nullptr);
CreateWindow(L"BUTTON", L"登录", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 50, 110, 100, 25, hwndLogin, (HMENU)1, hInst, nullptr);
SetWindowText(hwndLogin, L"登录");
break;
case WM_COMMAND:
switch (LOWORD(wParam))
{
case 1:
// 获取用户名和密码
wchar_t username[256], password[256];
GetWindowText(hwndUsername, username, 256);
GetWindowText(hwndPassword, password, 256);
// 验证用户名和密码是否正确
if (std::wstring(username) == L"admin" && std::wstring(password) == L"123456")
{
// 登录成功,关闭登录窗口
DestroyWindow(hwndLogin);
}
else
{
// 登录失败,弹出提示框
MessageBox(hWnd, L"用户名或密码错误", L"错误", MB_OK | MB_ICONERROR);
}
break;
}
break;
case WM_PAINT:
// 绘制主窗口
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// 登录窗口过程函数
LRESULT CALLBACK LoginProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_PAINT:
// 绘制登录窗口
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hWnd, &ps);
Rectangle(hdc, 0, 0, 200, 160);
TextOut(hdc, 10, 10, L"用户名:", 8);
TextOut(hdc, 10, 50, L"密码:", 6);
EndPaint(hWnd, &ps);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
```
这个代码创建了一个带有登录界面的游戏窗口,其中登录界面是由一个静态控件(用于绘制边框)和三个子控件(两个文本框和一个按钮)组成的。当用户点击登录按钮时,程序会验证用户名和密码,如果正确则关闭登录窗口并进入游戏,否则弹出错误提示框。