#include <windows.h>
#include <stdio.h>
#include <time.h>
#define BOARD_WIDTH 10
#define BOARD_HEIGHT 20
#define BLOCK_SIZE 25
#define WINDOW_WIDTH (BOARD_WIDTH * BLOCK_SIZE + 200)
#define WINDOW_HEIGHT (BOARD_HEIGHT * BLOCK_SIZE + 40)
// 方块形状定义
const int SHAPES[7][4][4] = {
{
{0,0,0,0}, {1,1,1,1}, {0,0,0,0}, {0,0,0,0}}, // I
{
{0,0,0,0}, {0,1,1,0}, {0,1,1,0}, {0,0,0,0}}, // O
{
{0,0,0,0}, {0,1,1,1}, {0,1,0,0}, {0,0,0,0}}, // L
{
{0,0,0,0}, {0,1,1,1}, {0,0,0,1}, {0,0,0,0}}, // J
{
{0,0,0,0}, {0,1,1,1}, {0,0,1,0}, {0,0,0,0}}, // T
{
{0,0,0,0}, {0,1,1,0}, {0,0,1,1}, {0,0,0,0}}, // S
{
{0,0,0,0}, {0,0,1,1}, {0,1,1,0}, {0,0,0,0}} // Z
};
// 颜色定义
const COLORREF COLORS[8] = {
RGB(0, 0, 0), // 黑色 - 背景
RGB(0, 255, 255), // 青色 - I
RGB(255, 255, 0), // 黄色 - O
RGB(255, 165, 0), // 橙色 - L
RGB(0, 0, 255), // 蓝色 - J
RGB(128, 0, 128), // 紫色 - T
RGB(0, 255, 0), // 绿色 - S
RGB(255, 0, 0) // 红色 - Z
};
// 游戏状态
int board[BOARD_HEIGHT][BOARD_WIDTH];
int currentPiece[4][4];
int nextPiece[4][4];
int currentX, currentY;
int currentType, nextType;
int score;
int level;
int linesCleared;
BOOL gameOver;
BOOL isPaused;
// 函数声明
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
void InitializeGame(void);
void NewPiece(void);
void RotatePiece(void);
int CheckCollision(void);
void LockPiece(void);
void ClearLines(void);
void DrawGame(HDC hdc);
void DrawBlock(HDC hdc, int x, int y, int colorIndex);
void DrawNextPiece(HDC hdc);
void DrawScore(HDC hdc);
void GameLoop(HWND hwnd);
void ResetGame(void);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
const char CLASS_NAME[] = "TetrisClass";
WNDCLASS wc = {0};
HWND hwnd;
MSG msg;
// 注册窗口类
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
wc.style = CS_HREDRAW | CS_VREDRAW;
if (!RegisterClass(&wc)) {
MessageBox(NULL, "窗口注册失败!", "错误", MB_ICONERROR);
return 0;
}
// 创建窗口
hwnd = CreateWindowEx(
0,
CLASS_NAME,
"俄罗斯方块 - C89 Windows API",
WS_OVERLAPPEDWINDOW & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX,
CW_USEDEFAULT, CW_USEDEFAULT,
WINDOW_WIDTH, WINDOW_HEIGHT,
NULL, NULL, hInstance, NULL
);
if (hwnd == NULL) {
MessageBox(NULL, "窗口创建失败!", "错误", MB_ICONERROR);
return 0;
}
// 初始化游戏
InitializeGame();
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// 设置定时器用于游戏循环
SetTimer(hwnd, 1, 500, NULL);
// 消息循环
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
KillTimer(hwnd, 1);
return msg.wParam;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
HDC hdc;
PAINTSTRUCT ps;
switch (uMsg) {
case WM_PAINT:
hdc = BeginPaint(hwnd, &ps);
DrawGame(hdc);
EndPaint(hwnd, &ps);
break;
case WM_TIMER:
if (!gameOver && !isPaused) {
GameLoop(hwnd);
}
break;
case WM_KEYDOWN:
if (!gameOver && !isPaused) {
switch (wParam) {
case VK_LEFT

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



