台球小游戏

· · 个人记录

#include <windows.h>
#include <tchar.h>
#include <cmath>
#include <vector>
#include <cstdio>

using namespace std;

// ========== 常量 ==========
const double PI = 3.1415926535;
const int TABLE_X = 80;
const int TABLE_Y = 110;
const int TABLE_W = 880;
const int TABLE_H = 440;
const double BALL_R = 10;
const double FRICTION = 0.985;
const double MIN_SPEED = 0.05;
const int POCKET_R = 18;
const int WIN_W = 1040;
const int WIN_H = 640;
const int TIMER_ID = 1;

// 球袋坐标
int pockets[6][2] = {
    {TABLE_X, TABLE_Y},
    {TABLE_X + TABLE_W / 2, TABLE_Y - 3},
    {TABLE_X + TABLE_W, TABLE_Y},
    {TABLE_X, TABLE_Y + TABLE_H},
    {TABLE_X + TABLE_W / 2, TABLE_Y + TABLE_H + 3},
    {TABLE_X + TABLE_W, TABLE_Y + TABLE_H}
};

// ========== 球结构体 ==========
struct Ball {
    double x, y;
    double vx, vy;
    COLORREF color;
    int value;
    bool inPocket;
    bool isCue;
    bool isRed;
    double homeX, homeY;
};

vector<Ball> balls;
bool aiming = false;
double aimX = 0, aimY = 0;
int score1 = 0, score2 = 0;
int currentPlayer = 1;
bool redPhase = true;
bool needRed = true;
bool gameOver = false;
int winner = 0;

HWND g_hWnd;

// ========== 工具函数 ==========
bool allStopped() {
    for (size_t i = 0; i < balls.size(); i++) {
        Ball& b = balls[i];
        if (!b.inPocket && (fabs(b.vx) > MIN_SPEED || fabs(b.vy) > MIN_SPEED))
            return false;
    }
    return true;
}

// ========== 初始化球 ==========
void initBalls() {
    balls.clear();
    redPhase = true;
    needRed = true;
    gameOver = false;
    winner = 0;
    score1 = 0;
    score2 = 0;
    currentPlayer = 1;

    // 母球
    Ball cue;
    cue.x = TABLE_X + 200;
    cue.y = TABLE_Y + TABLE_H / 2.0;
    cue.vx = cue.vy = 0;
    cue.color = RGB(255, 255, 255);
    cue.value = 0;
    cue.inPocket = false;
    cue.isCue = true;
    cue.isRed = false;
    cue.homeX = cue.x; cue.homeY = cue.y;
    balls.push_back(cue);

    // 15个红球(三角形)
    double startX = TABLE_X + TABLE_W * 0.65;
    double startY = TABLE_Y + TABLE_H / 2.0;
    double dx = BALL_R * 2 + 1;
    double dy = (BALL_R * 2 + 1) * 0.866;
    for (int row = 0; row < 5; row++) {
        for (int col = 0; col <= row; col++) {
            Ball b;
            b.x = startX + row * dx;
            b.y = startY + (col - row / 2.0) * dy;
            b.vx = b.vy = 0;
            b.color = RGB(220, 30, 30);
            b.value = 1;
            b.inPocket = false;
            b.isCue = false;
            b.isRed = true;
            b.homeX = b.x; b.homeY = b.y;
            balls.push_back(b);
        }
    }

    // 彩球
    struct { COLORREF c; double x; double y; int v; } colors[] = {
        {RGB(255, 200, 0),   TABLE_X + 150, TABLE_Y + TABLE_H * 0.3, 2},
        {RGB(0, 170, 0),      TABLE_X + 150, TABLE_Y + TABLE_H * 0.7, 3},
        {RGB(150, 75, 20),    TABLE_X + 150, TABLE_Y + TABLE_H / 2.0, 4},
        {RGB(30, 80, 220),    TABLE_X + TABLE_W / 2.0, TABLE_Y + TABLE_H / 2.0, 5},
        {RGB(255, 105, 180),  TABLE_X + TABLE_W * 0.65 - BALL_R * 3, TABLE_Y + TABLE_H / 2.0, 6},
        {RGB(20, 20, 20),     TABLE_X + TABLE_W - 100, TABLE_Y + TABLE_H / 2.0, 7}
    };
    for (int i = 0; i < 6; i++) {
        Ball b;
        b.x = colors[i].x; b.y = colors[i].y;
        b.vx = b.vy = 0;
        b.color = colors[i].c;
        b.value = colors[i].v;
        b.inPocket = false;
        b.isCue = false;
        b.isRed = false;
        b.homeX = b.x; b.homeY = b.y;
        balls.push_back(b);
    }
}

// ========== 碰撞 ==========
void ballCollision(Ball& a, Ball& b) {
    double dx = b.x - a.x;
    double dy = b.y - a.y;
    double dist = sqrt(dx * dx + dy * dy);
    if (dist < BALL_R * 2 && dist > 0.001) {
        double overlap = BALL_R * 2 - dist;
        double nx = dx / dist, ny = dy / dist;
        a.x -= nx * overlap / 2;
        a.y -= ny * overlap / 2;
        b.x += nx * overlap / 2;
        b.y += ny * overlap / 2;

        double dvx = b.vx - a.vx;
        double dvy = b.vy - a.vy;
        double dot = dvx * nx + dvy * ny;
        if (dot < 0) {
            a.vx += dot * nx;
            a.vy += dot * ny;
            b.vx -= dot * nx;
            b.vy -= dot * ny;
        }
    }
}

// ========== 进袋检测 ==========
void checkPockets() {
    for (size_t i = 0; i < balls.size(); i++) {
        Ball& b = balls[i];
        if (b.inPocket) continue;
        for (int p = 0; p < 6; p++) {
            double dx = b.x - pockets[p][0];
            double dy = b.y - pockets[p][1];
            if (sqrt(dx * dx + dy * dy) < POCKET_R) {
                b.inPocket = true;
                b.vx = b.vy = 0;

                if (b.isCue) {
                    if (currentPlayer == 1) score1 = max(0, score1 - 4);
                    else score2 = max(0, score2 - 4);
                    currentPlayer = (currentPlayer == 1) ? 2 : 1;
                    b.x = b.homeX; b.y = b.homeY;
                    b.inPocket = false;
                    needRed = true;
                } else if (b.isRed) {
                    if (currentPlayer == 1) score1 += b.value;
                    else score2 += b.value;
                    needRed = false;
                    bool hasRed = false;
                    for (size_t j = 0; j < balls.size(); j++)
                        if (balls[j].isRed && !balls[j].inPocket) { hasRed = true; break; }
                    if (!hasRed) redPhase = false;
                } else {
                    if (redPhase) {
                        if (currentPlayer == 1) score1 += b.value;
                        else score2 += b.value;
                        needRed = true;
                        b.inPocket = false;
                        b.x = b.homeX; b.y = b.homeY;
                    } else {
                        if (currentPlayer == 1) score1 += b.value;
                        else score2 += b.value;
                        bool anyBall = false;
                        for (size_t j = 0; j < balls.size(); j++)
                            if (!balls[j].isCue && !balls[j].inPocket) { anyBall = true; break; }
                        if (!anyBall) {
                            gameOver = true;
                            winner = (score1 > score2) ? 1 : (score2 > score1 ? 2 : 0);
                        }
                    }
                }
                break;
            }
        }
    }
}

// ========== 物理更新 ==========
void update() {
    if (gameOver) return;
    for (size_t i = 0; i < balls.size(); i++) {
        Ball& b = balls[i];
        if (b.inPocket) continue;
        b.x += b.vx;
        b.y += b.vy;
        b.vx *= FRICTION;
        b.vy *= FRICTION;
        if (fabs(b.vx) < MIN_SPEED) b.vx = 0;
        if (fabs(b.vy) < MIN_SPEED) b.vy = 0;

        if (b.x - BALL_R < TABLE_X) { b.x = TABLE_X + BALL_R; b.vx = -b.vx * 0.8; }
        if (b.x + BALL_R > TABLE_X + TABLE_W) { b.x = TABLE_X + TABLE_W - BALL_R; b.vx = -b.vx * 0.8; }
        if (b.y - BALL_R < TABLE_Y) { b.y = TABLE_Y + BALL_R; b.vy = -b.vy * 0.8; }
        if (b.y + BALL_R > TABLE_Y + TABLE_H) { b.y = TABLE_Y + TABLE_H - BALL_R; b.vy = -b.vy * 0.8; }
    }

    for (size_t i = 0; i < balls.size(); i++)
        for (size_t j = i + 1; j < balls.size(); j++)
            if (!balls[i].inPocket && !balls[j].inPocket)
                ballCollision(balls[i], balls[j]);

    checkPockets();
}

// 记录击球前的分数,用于判断是否进球
int scoreBeforeShot = 0;
bool shotInProgress = false;

void startShot() {
    scoreBeforeShot = (currentPlayer == 1) ? score1 : score2;
    shotInProgress = true;
}

void endShotCheck() {
    if (!shotInProgress) return;
    if (!allStopped()) return;
    shotInProgress = false;
    int scoreAfter = (currentPlayer == 1) ? score1 : score2;
    if (scoreAfter <= scoreBeforeShot && !gameOver) {
        currentPlayer = (currentPlayer == 1) ? 2 : 1;
        needRed = true;
    }
}

// ========== 绘图 ==========
void drawGame(HDC hdc) {
    // 背景
    HBRUSH hBg = CreateSolidBrush(RGB(45, 45, 50));
    RECT rcClient;
    GetClientRect(g_hWnd, &rcClient);
    FillRect(hdc, &rcClient, hBg);
    DeleteObject(hBg);

    // 球桌边框
    HBRUSH hFrame = CreateSolidBrush(RGB(110, 65, 20));
    RECT rcFrame = {TABLE_X - 28, TABLE_Y - 28, TABLE_X + TABLE_W + 28, TABLE_Y + TABLE_H + 28};
    FillRect(hdc, &rcFrame, hFrame);
    DeleteObject(hFrame);

    // 台呢
    HBRUSH hCloth = CreateSolidBrush(RGB(28, 125, 48));
    RECT rcCloth = {TABLE_X, TABLE_Y, TABLE_X + TABLE_W, TABLE_Y + TABLE_H};
    FillRect(hdc, &rcCloth, hCloth);
    DeleteObject(hCloth);

    // 开球区D形
    HPEN hWhitePen = CreatePen(PS_SOLID, 1, RGB(255, 255, 255));
    HPEN hOldPen = (HPEN)SelectObject(hdc, hWhitePen);
    HGDIOBJ hOldBrush = SelectObject(hdc, GetStockObject(NULL_BRUSH));
    Arc(hdc, TABLE_X + 150 - 60, TABLE_Y + TABLE_H / 2 - 60,
        TABLE_X + 150 + 60, TABLE_Y + TABLE_H / 2 + 60,
        TABLE_X + 150, TABLE_Y + TABLE_H / 2 - 60,
        TABLE_X + 150, TABLE_Y + TABLE_H / 2 + 60);
    MoveToEx(hdc, TABLE_X + 150, TABLE_Y + TABLE_H / 2 - 60, NULL);
    LineTo(hdc, TABLE_X + 150, TABLE_Y + TABLE_H / 2 + 60);

    // 球袋
    HBRUSH hPocket = CreateSolidBrush(RGB(0, 0, 0));
    SelectObject(hdc, hPocket);
    for (int i = 0; i < 6; i++) {
        Ellipse(hdc, pockets[i][0] - POCKET_R, pockets[i][1] - POCKET_R,
                pockets[i][0] + POCKET_R, pockets[i][1] + POCKET_R);
    }
    DeleteObject(hPocket);

    // 球
    for (size_t i = 0; i < balls.size(); i++) {
        Ball& b = balls[i];
        if (b.inPocket) continue;
        HBRUSH hBall = CreateSolidBrush(b.color);
        SelectObject(hdc, hBall);
        Ellipse(hdc, (int)(b.x - BALL_R), (int)(b.y - BALL_R),
                (int)(b.x + BALL_R), (int)(b.y + BALL_R));
        DeleteObject(hBall);
        HPEN hBallPen = CreatePen(PS_SOLID, 1, RGB(0, 0, 0));
        SelectObject(hdc, hBallPen);
        SelectObject(hdc, GetStockObject(NULL_BRUSH));
        Ellipse(hdc, (int)(b.x - BALL_R), (int)(b.y - BALL_R),
                (int)(b.x + BALL_R), (int)(b.y + BALL_R));
        DeleteObject(hBallPen);
    }

    // 瞄准线 + 球杆
    if (aiming && allStopped() && !gameOver) {
        Ball& cue = balls[0];
        double dx = aimX - cue.x;
        double dy = aimY - cue.y;
        double len = sqrt(dx * dx + dy * dy);
        if (len > 1) {
            double nx = dx / len, ny = dy / len;
            double power = min(len / 300.0, 1.0);

            // 瞄准虚线
            HPEN hDash = CreatePen(PS_DASH, 2, RGB(255, 255, 255));
            SelectObject(hdc, hDash);
            MoveToEx(hdc, (int)cue.x, (int)cue.y, NULL);
            LineTo(hdc, (int)(cue.x + nx * 350), (int)(cue.y + ny * 350));
            DeleteObject(hDash);

            // 球杆
            int cueLen = 130 + (int)(power * 70);
            HPEN hCue = CreatePen(PS_SOLID, 7, RGB(170, 105, 40));
            SelectObject(hdc, hCue);
            MoveToEx(hdc, (int)(cue.x - nx * (BALL_R + 6)),
                     (int)(cue.y - ny * (BALL_R + 6)), NULL);
            LineTo(hdc, (int)(cue.x - nx * (BALL_R + 6 + cueLen)),
                   (int)(cue.y - ny * (BALL_R + 6 + cueLen)));
            DeleteObject(hCue);

            // 杆头
            HPEN hTip = CreatePen(PS_SOLID, 5, RGB(240, 240, 240));
            SelectObject(hdc, hTip);
            MoveToEx(hdc, (int)(cue.x - nx * (BALL_R + 6)),
                     (int)(cue.y - ny * (BALL_R + 6)), NULL);
            LineTo(hdc, (int)(cue.x - nx * (BALL_R + 18)),
                   (int)(cue.y - ny * (BALL_R + 18)));
            DeleteObject(hTip);

            // 力度条
            HBRUSH hBarBg = CreateSolidBrush(RGB(70, 70, 70));
            RECT rcBar = {TABLE_X, TABLE_Y + TABLE_H + 45, TABLE_X + 300, TABLE_Y + TABLE_H + 62};
            FillRect(hdc, &rcBar, hBarBg);
            DeleteObject(hBarBg);
            HBRUSH hBar = CreateSolidBrush(RGB(255, (int)(200 - power * 150), 0));
            RECT rcFill = {TABLE_X, TABLE_Y + TABLE_H + 45,
                           TABLE_X + (int)(300 * power), TABLE_Y + TABLE_H + 62};
            FillRect(hdc, &rcFill, hBar);
            DeleteObject(hBar);
        }
    }

    SelectObject(hdc, hOldPen);
    SelectObject(hdc, hOldBrush);

    // ===== 文字信息 =====
    SetBkMode(hdc, TRANSPARENT);

    TCHAR buf[128];
    HFONT hFont = CreateFont(26, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
                              DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
                              DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
    HFONT hOldFont = (HFONT)SelectObject(hdc, hFont);

    SetTextColor(hdc, RGB(255, 255, 255));
    _stprintf(buf, _T("玩家1: %d    玩家2: %d"), score1, score2);
    TextOut(hdc, TABLE_X, 35, buf, (int)_tcslen(buf));

    SetTextColor(hdc, currentPlayer == 1 ? RGB(255, 215, 0) : RGB(100, 200, 255));
    _stprintf(buf, _T("轮到玩家 %d"), currentPlayer);
    TextOut(hdc, TABLE_X + TABLE_W - 160, 35, buf, (int)_tcslen(buf));

    SetTextColor(hdc, RGB(220, 220, 220));
    HFONT hSmallFont = CreateFont(18, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
                                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
                                    DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
    SelectObject(hdc, hSmallFont);
    const TCHAR* target = (redPhase && needRed) ? _T("目标: 红球") : _T("目标: 彩球");
    TextOut(hdc, TABLE_X + 380, 42, target, (int)_tcslen(target));

    SetTextColor(hdc, RGB(160, 160, 160));
    TextOut(hdc, TABLE_X, TABLE_Y + TABLE_H + 45, _T("鼠标指向=击球方向 | 按住拖拽=力度 | 松开=击球 | R=重置 | ESC=退出"), 40);

    // 重置按钮
    HBRUSH hBtn = CreateSolidBrush(RGB(70, 70, 80));
    RECT rcBtn = {TABLE_X + TABLE_W - 110, TABLE_Y + TABLE_H + 38, TABLE_X + TABLE_W, TABLE_Y + TABLE_H + 70};
    FillRect(hdc, &rcBtn, hBtn);
    DeleteObject(hBtn);
    SetTextColor(hdc, RGB(255, 255, 255));
    TextOut(hdc, TABLE_X + TABLE_W - 95, TABLE_Y + TABLE_H + 46, _T("重置 (R)"), 8);

    // 游戏结束
    if (gameOver) {
        HBRUSH hOverlay = CreateSolidBrush(RGB(0, 0, 0));
        RECT rcOverlay = {0, 0, WIN_W, WIN_H};
        FillRect(hdc, &rcOverlay, hOverlay);
        DeleteObject(hOverlay);
        SetTextColor(hdc, RGB(255, 215, 0));
        HFONT hBigFont = CreateFont(60, 0, 0, 0, FW_BOLD, FALSE, FALSE, FALSE,
                                      DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
                                      DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
        SelectObject(hdc, hBigFont);
        TCHAR overMsg[64];
        if (winner == 0) _stprintf(overMsg, _T("平局!"));
        else _stprintf(overMsg, _T("玩家 %d 获胜!"), winner);
        TextOut(hdc, WIN_W / 2 - 150, WIN_H / 2 - 40, overMsg, (int)_tcslen(overMsg));
        DeleteObject(hBigFont);
        SelectObject(hdc, hSmallFont);
        SetTextColor(hdc, RGB(200, 200, 200));
        TextOut(hdc, WIN_W / 2 - 100, WIN_H / 2 + 40, _T("按 R 重新开始"), 9);
        DeleteObject(hSmallFont);
    }

    SelectObject(hdc, hOldFont);
    DeleteObject(hFont);
}

// ========== 窗口过程 ==========
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
    switch (msg) {
        case WM_CREATE:
            g_hWnd = hWnd;
            initBalls();
            SetTimer(hWnd, TIMER_ID, 12, NULL);
            break;

        case WM_TIMER:
            update();
            endShotCheck();
            InvalidateRect(hWnd, NULL, FALSE);
            break;

        case WM_PAINT: {
            PAINTSTRUCT ps;
            HDC hdc = BeginPaint(hWnd, &ps);
            drawGame(hdc);
            EndPaint(hWnd, &ps);
            break;
        }

        case WM_LBUTTONDOWN:
            if (allStopped() && !gameOver) {
                aiming = true;
                aimX = (double)(short)LOWORD(lParam);
                aimY = (double)(short)HIWORD(lParam);
            }
            break;

        case WM_MOUSEMOVE:
            if (aiming) {
                aimX = (double)(short)LOWORD(lParam);
                aimY = (double)(short)HIWORD(lParam);
            }
            break;

        case WM_LBUTTONUP:
            if (aiming && allStopped() && !gameOver) {
                aiming = false;
                Ball& cue = balls[0];
                double dx = aimX - cue.x;
                double dy = aimY - cue.y;
                double len = sqrt(dx * dx + dy * dy);
                if (len > 5) {
                    double power = min(len / 300.0, 1.0) * 16;
                    cue.vx = (dx / len) * power;
                    cue.vy = (dy / len) * power;
                    startShot();
                }
            }
            break;

        case WM_KEYDOWN:
            if (wParam == 'R' || wParam == 'r') {
                initBalls();
            }
            if (wParam == VK_ESCAPE) {
                DestroyWindow(hWnd);
            }
            break;

        case WM_DESTROY:
            KillTimer(hWnd, TIMER_ID);
            PostQuitMessage(0);
            break;

        default:
            return DefWindowProc(hWnd, msg, wParam, lParam);
    }
    return 0;
}

// ========== WinMain ==========
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    WNDCLASS wc = {0};
    wc.lpfnWndProc = WndProc;
    wc.hInstance = hInstance;
    wc.lpszClassName = _T("SnookerGame");
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    RegisterClass(&wc);

    RECT rc = {0, 0, WIN_W, WIN_H};
    AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

    HWND hWnd = CreateWindow(_T("SnookerGame"), _T("斯诺克台球 - 双人对战"),
                              WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX,
                              CW_USEDEFAULT, CW_USEDEFAULT,
                              rc.right - rc.left, rc.bottom - rc.top,
                              NULL, NULL, hInstance, NULL);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

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