Advertisement
alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: AI With Difficulty Modes Added V2

Apr 25th, 2025 (edited)
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 110.54 KB | Source Code | 0 0
  1. ==++ Here's the full source for (file 1/3 (No OOP-based)) "Pool-Game-Clone.cpp"::: ++==
  2. ```Pool-Game-Clone.cpp
  3. #define WIN32_LEAN_AND_MEAN
  4. #define NOMINMAX
  5. #include <windows.h>
  6. #include <d2d1.h>
  7. #include <dwrite.h>
  8. #include <vector>
  9. #include <cmath>
  10. #include <string>
  11. #include <sstream> // Required for wostringstream
  12. #include <algorithm> // Required for std::max, std::min
  13. #include <ctime>    // Required for srand, time
  14. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  15. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  16. #include "resource.h"
  17.  
  18. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  19. #pragma comment(lib, "d2d1.lib")
  20. #pragma comment(lib, "dwrite.lib")
  21.  
  22. // --- Constants ---
  23. const float PI = 3.1415926535f;
  24. const float BALL_RADIUS = 10.0f;
  25. const float TABLE_LEFT = 100.0f;
  26. const float TABLE_TOP = 100.0f;
  27. const float TABLE_WIDTH = 700.0f;
  28. const float TABLE_HEIGHT = 350.0f;
  29. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  30. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  31. const float CUSHION_THICKNESS = 20.0f;
  32. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  33. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS; // Make detection radius match visual size (or slightly larger)
  34. const float MAX_SHOT_POWER = 15.0f;
  35. const float FRICTION = 0.985f; // Friction factor per frame
  36. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  37. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  38. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  39. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  40. const UINT ID_TIMER = 1;
  41. const int TARGET_FPS = 60; // Target frames per second for timer
  42.  
  43. // --- Enums ---
  44. // --- MODIFIED/NEW Enums ---
  45. enum GameState {
  46.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  47.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  48.    BREAKING,           // Player is aiming/shooting the break shot
  49.    AIMING,             // Player is aiming
  50.    AI_THINKING,        // NEW: AI is calculating its move
  51.    SHOT_IN_PROGRESS,   // Balls are moving
  52.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  53.    PLAYER1_TURN,
  54.    PLAYER2_TURN,
  55.    BALL_IN_HAND_P1,
  56.    BALL_IN_HAND_P2,
  57.    GAME_OVER
  58. };
  59.  
  60. enum BallType {
  61.    NONE,
  62.    SOLID,  // Yellow (1-7)
  63.    STRIPE, // Red (9-15)
  64.    EIGHT_BALL, // Black (8)
  65.    CUE_BALL // White (0)
  66. };
  67.  
  68. // NEW Enums for Game Mode and AI Difficulty
  69. enum GameMode {
  70.    HUMAN_VS_HUMAN,
  71.    HUMAN_VS_AI
  72. };
  73.  
  74. enum AIDifficulty {
  75.    EASY,
  76.    MEDIUM,
  77.    HARD
  78. };
  79.  
  80. // --- Structs ---
  81. struct Ball {
  82.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  83.    BallType type;
  84.    float x, y;
  85.    float vx, vy;
  86.    D2D1_COLOR_F color;
  87.    bool isPocketed;
  88. };
  89.  
  90. struct PlayerInfo {
  91.    BallType assignedType;
  92.    int ballsPocketedCount;
  93.    std::wstring name;
  94. };
  95.  
  96. // --- Global Variables ---
  97.  
  98. // Direct2D & DirectWrite
  99. ID2D1Factory* pFactory = nullptr;
  100. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  101. IDWriteFactory* pDWriteFactory = nullptr;
  102. IDWriteTextFormat* pTextFormat = nullptr;
  103. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  104.  
  105. // Game State
  106. HWND hwndMain = nullptr;
  107. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  108. std::vector<Ball> balls;
  109. int currentPlayer = 1; // 1 or 2
  110. PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
  111. PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
  112. bool foulCommitted = false;
  113. std::wstring gameOverMessage = L"";
  114. bool firstBallPocketedAfterBreak = false;
  115. std::vector<int> pocketedThisTurn;
  116.  
  117. // NEW Game Mode/AI Globals
  118. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  119. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  120. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  121. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  122. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  123.  
  124. // Input & Aiming
  125. POINT ptMouse = { 0, 0 };
  126. bool isAiming = false;
  127. bool isDraggingCueBall = false;
  128. bool isSettingEnglish = false;
  129. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  130. float cueAngle = 0.0f;
  131. float shotPower = 0.0f;
  132. float cueSpinX = 0.0f; // Range -1 to 1
  133. float cueSpinY = 0.0f; // Range -1 to 1
  134.  
  135. // UI Element Positions
  136. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  137. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  138. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  139. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  140. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  141.  
  142. // Corrected Pocket Center Positions (aligned with table corners/edges)
  143. const D2D1_POINT_2F pocketPositions[6] = {
  144.    {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  145.    {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  146.    {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  147.    {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  148.    {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  149.    {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  150. };
  151.  
  152. // Colors
  153. const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.1f); // Darker Green
  154. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  155. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  156. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  157. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  158. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
  159. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red);   // Stripes = Red
  160. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  161. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  162. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  163. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  164. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  165.  
  166. // --- Forward Declarations ---
  167. HRESULT CreateDeviceResources();
  168. void DiscardDeviceResources();
  169. void OnPaint();
  170. void OnResize(UINT width, UINT height);
  171. void InitGame();
  172. void GameUpdate();
  173. void UpdatePhysics();
  174. void CheckCollisions();
  175. bool CheckPockets(); // Returns true if any ball was pocketed
  176. void ProcessShotResults();
  177. void ApplyShot(float power, float angle, float spinX, float spinY);
  178. void RespawnCueBall(bool behindHeadstring);
  179. bool AreBallsMoving();
  180. void SwitchTurns();
  181. void AssignPlayerBallTypes(BallType firstPocketedType);
  182. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  183. Ball* GetBallById(int id);
  184. Ball* GetCueBall();
  185.  
  186. // Drawing Functions
  187. void DrawScene(ID2D1RenderTarget* pRT);
  188. void DrawTable(ID2D1RenderTarget* pRT);
  189. void DrawBalls(ID2D1RenderTarget* pRT);
  190. void DrawCueStick(ID2D1RenderTarget* pRT);
  191. void DrawAimingAids(ID2D1RenderTarget* pRT);
  192. void DrawUI(ID2D1RenderTarget* pRT);
  193. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  194. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  195. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  196. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  197.  
  198. // Helper Functions
  199. float GetDistance(float x1, float y1, float x2, float y2);
  200. float GetDistanceSq(float x1, float y1, float x2, float y2);
  201. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  202. template <typename T> void SafeRelease(T** ppT);
  203.  
  204. // --- NEW Forward Declarations ---
  205.  
  206. // AI Related
  207. struct AIShotInfo; // Define below
  208. void TriggerAIMove();
  209. void AIMakeDecision();
  210. void AIPlaceCueBall();
  211. AIShotInfo AIFindBestShot();
  212. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  213. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  214. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  215. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  216. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  217. bool IsValidAIAimAngle(float angle); // Basic check
  218.  
  219. // Dialog Related
  220. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  221. void ShowNewGameDialog(HINSTANCE hInstance);
  222. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  223.  
  224. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  225. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  226.  
  227. // --- NEW Struct for AI Shot Evaluation ---
  228. struct AIShotInfo {
  229.    bool possible = false;          // Is this shot considered viable?
  230.    Ball* targetBall = nullptr;     // Which ball to hit
  231.    int pocketIndex = -1;           // Which pocket to aim for (0-5)
  232.    D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  233.    float angle = 0.0f;             // Calculated shot angle
  234.    float power = 0.0f;             // Calculated shot power
  235.    float score = -1.0f;            // Score for this shot (higher is better)
  236.    bool involves8Ball = false;     // Is the target the 8-ball?
  237. };
  238.  
  239. // --- NEW Dialog Procedure ---
  240. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  241.    switch (message) {
  242.    case WM_INITDIALOG:
  243.        // Set initial state based on current global settings (or defaults)
  244.        CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  245.  
  246.        CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  247.            (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  248.  
  249.        // Enable/Disable AI group based on initial mode
  250.        EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  251.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  252.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  253.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  254.  
  255.        return (INT_PTR)TRUE;
  256.  
  257.    case WM_COMMAND:
  258.        switch (LOWORD(wParam)) {
  259.        case IDC_RADIO_2P:
  260.        case IDC_RADIO_CPU:
  261.        {
  262.            bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  263.            // Enable/Disable AI group controls based on selection
  264.            EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  265.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  266.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  267.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  268.        }
  269.        return (INT_PTR)TRUE;
  270.  
  271.        case IDOK:
  272.            // Retrieve selected options and store in global variables
  273.            if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  274.                gameMode = HUMAN_VS_AI;
  275.                if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  276.                else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  277.                else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  278.            }
  279.            else {
  280.                gameMode = HUMAN_VS_HUMAN;
  281.            }
  282.            EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  283.            return (INT_PTR)TRUE;
  284.  
  285.        case IDCANCEL: // Handle Cancel or closing the dialog
  286.            EndDialog(hDlg, IDCANCEL);
  287.            return (INT_PTR)TRUE;
  288.        }
  289.        break; // End WM_COMMAND
  290.    }
  291.    return (INT_PTR)FALSE; // Default processing
  292. }
  293.  
  294. // --- NEW Helper to Show Dialog ---
  295. void ShowNewGameDialog(HINSTANCE hInstance) {
  296.    if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  297.        // User clicked Start, reset game with new settings
  298.        isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  299.        if (isPlayer2AI) {
  300.            switch (aiDifficulty) {
  301.            case EASY: player2Info.name = L"CPU (Easy)"; break;
  302.            case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  303.            case HARD: player2Info.name = L"CPU (Hard)"; break;
  304.            }
  305.        }
  306.        else {
  307.            player2Info.name = L"Player 2";
  308.        }
  309.        // Update window title
  310.        std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  311.        if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  312.        else windowTitle += L" (Human vs " + player2Info.name + L")";
  313.        SetWindowText(hwndMain, windowTitle.c_str());
  314.  
  315.        InitGame(); // Re-initialize game logic & board
  316.        InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  317.    }
  318.    else {
  319.        // User cancelled dialog - maybe just resume game? Or exit?
  320.        // For simplicity, we do nothing, game continues as it was.
  321.        // To exit on cancel from F2, would need more complex state management.
  322.    }
  323. }
  324.  
  325. // --- NEW Reset Game Function ---
  326. void ResetGame(HINSTANCE hInstance) {
  327.    // Call the helper function to show the dialog and re-init if OK clicked
  328.    ShowNewGameDialog(hInstance);
  329. }
  330.  
  331. // --- WinMain ---
  332. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  333.    if (FAILED(CoInitialize(NULL))) {
  334.        MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  335.        return -1;
  336.    }
  337.  
  338.    // --- NEW: Show configuration dialog FIRST ---
  339.    if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  340.        // User cancelled the dialog
  341.        CoUninitialize();
  342.        return 0; // Exit gracefully if dialog cancelled
  343.    }
  344.    // Global gameMode and aiDifficulty are now set by the DialogProc
  345.  
  346.    // Set AI flag based on game mode
  347.    isPlayer2AI = (gameMode == HUMAN_VS_AI);
  348.    if (isPlayer2AI) {
  349.        switch (aiDifficulty) {
  350.        case EASY: player2Info.name = L"CPU (Easy)"; break;
  351.        case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  352.        case HARD: player2Info.name = L"CPU (Hard)"; break;
  353.        }
  354.    }
  355.    else {
  356.        player2Info.name = L"Player 2";
  357.    }
  358.    // --- End of Dialog Logic ---
  359.  
  360.  
  361.    WNDCLASS wc = { };
  362.    wc.lpfnWndProc = WndProc;
  363.    wc.hInstance = hInstance;
  364.    wc.lpszClassName = L"Direct2D_8BallPool";
  365.    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  366.    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  367.    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  368.  
  369.    if (!RegisterClass(&wc)) {
  370.        MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  371.        CoUninitialize();
  372.        return -1;
  373.    }
  374.  
  375.    // --- Change Window Title based on mode ---
  376.    std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  377.    if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  378.    else windowTitle += L" (Human vs " + player2Info.name + L")";
  379.  
  380.  
  381.    hwndMain = CreateWindowEx(
  382.        0, L"Direct2D_8BallPool", windowTitle.c_str(), WS_OVERLAPPEDWINDOW,
  383.        CW_USEDEFAULT, CW_USEDEFAULT, 1000, 700,
  384.        NULL, NULL, hInstance, NULL
  385.    );
  386.  
  387.    if (!hwndMain) {
  388.        MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  389.        CoUninitialize();
  390.        return -1;
  391.    }
  392.  
  393.    // Initialize Direct2D Resources AFTER window creation
  394.    if (FAILED(CreateDeviceResources())) {
  395.        MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  396.        DestroyWindow(hwndMain);
  397.        CoUninitialize();
  398.        return -1;
  399.    }
  400.  
  401.    InitGame(); // Initialize game state AFTER resources are ready & mode is set
  402.  
  403.    ShowWindow(hwndMain, nCmdShow);
  404.    UpdateWindow(hwndMain);
  405.  
  406.    if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  407.        MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  408.        DestroyWindow(hwndMain);
  409.        CoUninitialize();
  410.        return -1;
  411.    }
  412.  
  413.    MSG msg = { };
  414.    // --- Modified Main Loop ---
  415.    // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  416.    // or gets reset to it via F2. The main loop runs normally once game starts.
  417.    while (GetMessage(&msg, NULL, 0, 0)) {
  418.        // We might need modeless dialog handling here if F2 shows dialog
  419.        // while window is active, but DialogBoxParam is modal.
  420.        // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  421.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  422.         TranslateMessage(&msg);
  423.         DispatchMessage(&msg);
  424.     }
  425.  
  426.  
  427.     KillTimer(hwndMain, ID_TIMER);
  428.     DiscardDeviceResources();
  429.     CoUninitialize();
  430.  
  431.     return (int)msg.wParam;
  432. }
  433.  
  434. // --- WndProc ---
  435. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  436.     switch (msg) {
  437.     case WM_CREATE:
  438.         // Resources are now created in WinMain after CreateWindowEx
  439.         return 0;
  440.  
  441.     case WM_PAINT:
  442.         OnPaint();
  443.         // Validate the entire window region after painting
  444.         ValidateRect(hwnd, NULL);
  445.         return 0;
  446.  
  447.     case WM_SIZE: {
  448.         UINT width = LOWORD(lParam);
  449.         UINT height = HIWORD(lParam);
  450.         OnResize(width, height);
  451.         return 0;
  452.     }
  453.  
  454.     case WM_TIMER:
  455.         if (wParam == ID_TIMER) {
  456.             GameUpdate(); // Update game logic and physics
  457.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  458.         }
  459.         return 0;
  460.  
  461.         // --- NEW: Handle F2 Key for Reset ---
  462.     case WM_KEYDOWN:
  463.         if (wParam == VK_F2) {
  464.             // Get HINSTANCE from the window handle
  465.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  466.             ResetGame(hInstance); // Call reset function
  467.         }
  468.         return 0; // Indicate key was processed
  469.  
  470.     case WM_MOUSEMOVE: {
  471.         ptMouse.x = LOWORD(lParam);
  472.         ptMouse.y = HIWORD(lParam);
  473.  
  474.         Ball* cueBall = GetCueBall();
  475.         if (!cueBall) return 0;
  476.  
  477.         if (isDraggingCueBall && (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)) {
  478.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  479.             if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  480.                 cueBall->x = (float)ptMouse.x;
  481.                 cueBall->y = (float)ptMouse.y;
  482.                 cueBall->vx = cueBall->vy = 0; // Ensure it's stopped
  483.             }
  484.         }
  485.         else if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  486.             float dx = (float)ptMouse.x - cueBall->x;
  487.             float dy = (float)ptMouse.y - cueBall->y;
  488.             cueAngle = atan2f(dy, dx);
  489.             // Calculate power based on distance pulled back from the initial click point (aimStartPoint)
  490.             float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  491.             shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER); // Scale power, clamp to max
  492.         }
  493.         else if (isSettingEnglish) {
  494.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  495.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  496.             float dist = GetDistance(dx, dy, 0, 0);
  497.             if (dist > spinIndicatorRadius) { // Clamp to edge
  498.                 dx *= spinIndicatorRadius / dist;
  499.                 dy *= spinIndicatorRadius / dist;
  500.             }
  501.             cueSpinX = dx / spinIndicatorRadius; // Normalize to -1 to 1
  502.             cueSpinY = dy / spinIndicatorRadius;
  503.         }
  504.         // No need to InvalidateRect here, the timer does it
  505.         return 0;
  506.     }
  507.  
  508.     case WM_LBUTTONDOWN: {
  509.         ptMouse.x = LOWORD(lParam);
  510.         ptMouse.y = HIWORD(lParam);
  511.  
  512.         // Check if clicking on Spin Indicator
  513.         float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  514.         if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius) {
  515.             isSettingEnglish = true;
  516.             // Update spin immediately on click
  517.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  518.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  519.             cueSpinX = dx / spinIndicatorRadius;
  520.             cueSpinY = dy / spinIndicatorRadius;
  521.             return 0; // Don't process other clicks if setting english
  522.         }
  523.  
  524.  
  525.         Ball* cueBall = GetCueBall();
  526.         if (!cueBall) return 0;
  527.  
  528.         if (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT) {
  529.             // Check if clicking on the cue ball to start dragging
  530.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  531.             if (distSq < BALL_RADIUS * BALL_RADIUS * 4) { // Allow clicking near the ball
  532.                 isDraggingCueBall = true;
  533.             }
  534.             else { // If clicking elsewhere on the table (and valid), place the ball
  535.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  536.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  537.                     cueBall->x = (float)ptMouse.x;
  538.                     cueBall->y = (float)ptMouse.y;
  539.                     cueBall->vx = cueBall->vy = 0;
  540.                     isDraggingCueBall = false; // Stop dragging if placed by click
  541.                     // Transition to aiming state
  542.                     if (currentGameState == PRE_BREAK_PLACEMENT) {
  543.                         currentGameState = BREAKING;
  544.                     }
  545.                     else if (currentGameState == BALL_IN_HAND_P1) {
  546.                         currentGameState = PLAYER1_TURN; // Or AIMING directly? Let's go to TURN first
  547.                     }
  548.                     else if (currentGameState == BALL_IN_HAND_P2) {
  549.                         currentGameState = PLAYER2_TURN;
  550.                     }
  551.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN; // Should transition to aiming on next click near ball
  552.                 }
  553.             }
  554.         }
  555.         else if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  556.             // Check if clicking near cue ball to start aiming
  557.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  558.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9) { // Click reasonably close to cue ball
  559.                 isAiming = true;
  560.                 aimStartPoint = { (float)ptMouse.x, (float)ptMouse.y }; // Store where aiming started
  561.                 shotPower = 0; // Reset power
  562.                 // Decide which state based on context
  563.                 currentGameState = (currentGameState == BREAKING) ? BREAKING : AIMING;
  564.             }
  565.         }
  566.         return 0;
  567.     }
  568.  
  569.     case WM_LBUTTONUP: {
  570.         ptMouse.x = LOWORD(lParam);
  571.         ptMouse.y = HIWORD(lParam);
  572.  
  573.         if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  574.             isAiming = false;
  575.             if (shotPower > 0.1f) { // Only shoot if power is applied
  576.                 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  577.                 currentGameState = SHOT_IN_PROGRESS;
  578.                 foulCommitted = false; // Reset foul flag for the new shot
  579.                 pocketedThisTurn.clear(); // Clear balls pocketed this specific shot
  580.             }
  581.             else {
  582.                 // If no power, revert state back
  583.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  584.                 if (GetBallById(0)->x < HEADSTRING_X && currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN) { // Simple check if it was likely a break attempt reset
  585.                     currentGameState = BREAKING;
  586.                 }
  587.             }
  588.             shotPower = 0; // Reset power indicator
  589.         }
  590.         if (isDraggingCueBall) {
  591.             isDraggingCueBall = false;
  592.             // After placing the ball, transition state if needed
  593.             if (currentGameState == PRE_BREAK_PLACEMENT) {
  594.                 currentGameState = BREAKING; // Ready to aim for break
  595.             }
  596.             else if (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2) {
  597.                 // Now ready to aim the shot after placing
  598.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  599.             }
  600.         }
  601.         if (isSettingEnglish) {
  602.             isSettingEnglish = false;
  603.             // Spin is already set during drag
  604.         }
  605.         return 0;
  606.     }
  607.  
  608.  
  609.     case WM_DESTROY:
  610.         PostQuitMessage(0);
  611.         return 0;
  612.  
  613.     default:
  614.         return DefWindowProc(hwnd, msg, wParam, lParam);
  615.     }
  616.     return 0;
  617. }
  618.  
  619. // --- Direct2D Resource Management ---
  620.  
  621. HRESULT CreateDeviceResources() {
  622.     HRESULT hr = S_OK;
  623.  
  624.     // Create Direct2D Factory
  625.     if (!pFactory) {
  626.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  627.         if (FAILED(hr)) return hr;
  628.     }
  629.  
  630.     // Create DirectWrite Factory
  631.     if (!pDWriteFactory) {
  632.         hr = DWriteCreateFactory(
  633.             DWRITE_FACTORY_TYPE_SHARED,
  634.             __uuidof(IDWriteFactory),
  635.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  636.         );
  637.         if (FAILED(hr)) return hr;
  638.     }
  639.  
  640.     // Create Text Formats
  641.     if (!pTextFormat && pDWriteFactory) {
  642.         hr = pDWriteFactory->CreateTextFormat(
  643.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  644.             16.0f, L"en-us", &pTextFormat
  645.         );
  646.         if (FAILED(hr)) return hr;
  647.         // Center align text
  648.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  649.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  650.     }
  651.     if (!pLargeTextFormat && pDWriteFactory) {
  652.         hr = pDWriteFactory->CreateTextFormat(
  653.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  654.             48.0f, L"en-us", &pLargeTextFormat
  655.         );
  656.         if (FAILED(hr)) return hr;
  657.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  658.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  659.     }
  660.  
  661.  
  662.     // Create Render Target (needs valid hwnd)
  663.     if (!pRenderTarget && hwndMain) {
  664.         RECT rc;
  665.         GetClientRect(hwndMain, &rc);
  666.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  667.  
  668.         hr = pFactory->CreateHwndRenderTarget(
  669.             D2D1::RenderTargetProperties(),
  670.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  671.             &pRenderTarget
  672.         );
  673.         if (FAILED(hr)) {
  674.             // If failed, release factories if they were created in this call
  675.             SafeRelease(&pTextFormat);
  676.             SafeRelease(&pLargeTextFormat);
  677.             SafeRelease(&pDWriteFactory);
  678.             SafeRelease(&pFactory);
  679.             pRenderTarget = nullptr; // Ensure it's null on failure
  680.             return hr;
  681.         }
  682.     }
  683.  
  684.     return hr;
  685. }
  686.  
  687. void DiscardDeviceResources() {
  688.     SafeRelease(&pRenderTarget);
  689.     SafeRelease(&pTextFormat);
  690.     SafeRelease(&pLargeTextFormat);
  691.     SafeRelease(&pDWriteFactory);
  692.     // Keep pFactory until application exit? Or release here too? Let's release.
  693.     SafeRelease(&pFactory);
  694. }
  695.  
  696. void OnResize(UINT width, UINT height) {
  697.     if (pRenderTarget) {
  698.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  699.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  700.     }
  701. }
  702.  
  703. // --- Game Initialization ---
  704. void InitGame() {
  705.     srand((unsigned int)time(NULL)); // Seed random number generator
  706.  
  707.     balls.clear();
  708.     pocketedThisTurn.clear();
  709.  
  710.     // Reset Players
  711.     player1Info = { BallType::NONE, 0, L"Player 1" };
  712.     player2Info = { BallType::NONE, 0, L"Player 2" };
  713.     currentPlayer = 1;
  714.     firstBallPocketedAfterBreak = false;
  715.     foulCommitted = false;
  716.     gameOverMessage = L"";
  717.  
  718.  
  719.     // Create Cue Ball (ID 0)
  720.     balls.push_back({ 0, BallType::CUE_BALL, HEADSTRING_X / 2.0f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  721.  
  722.     // Create 8-Ball (ID 8) - Will be placed correctly in the rack setup
  723.     // balls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  724.  
  725.     // Create Solid Balls (1-7, Yellow)
  726.     for (int i = 1; i <= 7; ++i) {
  727.         balls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  728.     }
  729.     // Create Stripe Balls (9-15, Red)
  730.     for (int i = 9; i <= 15; ++i) {
  731.         balls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  732.     }
  733.     // Add 8-ball (ID 8) now, it will be picked up by the racking algorithm
  734.     balls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  735.  
  736.  
  737.     // Arrange balls in a triangle rack
  738.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  739.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  740.     int ballIndex = 1; // Start placing from ball ID 1
  741.  
  742.     // Temp vector to hold balls for racking (excluding cue ball)
  743.     std::vector<Ball*> rackBalls;
  744.     for (size_t i = 0; i < balls.size(); ++i) {
  745.         if (balls[i].id != 0) {
  746.             rackBalls.push_back(&balls[i]);
  747.         }
  748.     }
  749.     // Simple shuffle (optional, but makes breaks more varied)
  750.     std::random_shuffle(rackBalls.begin(), rackBalls.end());
  751.  
  752.     // Find 8-ball and place it correctly if shuffled
  753.     Ball* eightBallPtr = nullptr;
  754.     int eightBallIdx = -1;
  755.     for (size_t i = 0; i < rackBalls.size(); ++i) {
  756.         if (rackBalls[i]->id == 8) {
  757.             eightBallPtr = rackBalls[i];
  758.             eightBallIdx = i;
  759.             break;
  760.         }
  761.     }
  762.  
  763.     int currentBall = 0;
  764.     for (int row = 0; row < 5; ++row) {
  765.         for (int col = 0; col <= row; ++col) {
  766.             if (currentBall >= rackBalls.size()) break; // Should not happen with 15 balls
  767.  
  768.             Ball* ballToPlace = rackBalls[currentBall];
  769.  
  770.             // Specific placement for 8-ball (center of 3rd row, index 4 if 0-based)
  771.             bool isEightBallPosition = (row == 2 && col == 1); // Center position in the triangle (0-based indexing)
  772.  
  773.             if (isEightBallPosition) {
  774.                 // If this is the 8-ball's spot, place the 8-ball here
  775.                 if (eightBallPtr) {
  776.                     ballToPlace = eightBallPtr;
  777.                     // If the 8-ball wasn't already at currentBall index due to shuffle, swap it
  778.                     if (rackBalls[currentBall]->id != 8) {
  779.                         std::swap(rackBalls[currentBall], rackBalls[eightBallIdx]);
  780.                         // Update eightBallIdx if it was swapped out
  781.                         eightBallIdx = currentBall;
  782.                     }
  783.                 }
  784.                 // If 8-ball wasn't found (error), just place whatever is here
  785.             }
  786.             else if (ballToPlace->id == 8) {
  787.                 // If we are about to place the 8-ball in a non-designated spot,
  788.                 // find a non-8-ball later in the list and swap with it.
  789.                 int swapIdx = -1;
  790.                 for (size_t k = currentBall + 1; k < rackBalls.size(); ++k) {
  791.                     // Find the next ball that *shouldn't* be the 8-ball and isn't the 8-ball spot
  792.                     bool kIsEightBallPosition = false; // Calculate if k corresponds to the 8-ball spot row/col
  793.                     int temp_row = 0, temp_col = 0, count = 0;
  794.                     for (int r = 0; r < 5; ++r) for (int c = 0; c <= r; ++c) { if (count == k) { temp_row = r; temp_col = c; } count++; }
  795.                     kIsEightBallPosition = (temp_row == 2 && temp_col == 1);
  796.  
  797.                     if (rackBalls[k]->id != 8 && !kIsEightBallPosition) {
  798.                         swapIdx = k;
  799.                         break;
  800.                     }
  801.                 }
  802.                 if (swapIdx != -1) {
  803.                     std::swap(rackBalls[currentBall], rackBalls[swapIdx]);
  804.                     ballToPlace = rackBalls[currentBall]; // Use the newly swapped ball
  805.                     // Update eightBallIdx if it was involved in the swap
  806.                     if (eightBallIdx == swapIdx) eightBallIdx = currentBall;
  807.                 }
  808.                 else {
  809.                     // Failsafe: if no suitable swap found (e.g., end of list),
  810.                     // place 8-ball here and hope for the best, or handle error.
  811.                     // This case should be rare with correct logic.
  812.                 }
  813.             }
  814.  
  815.  
  816.             float x = RACK_POS_X + row * spacingX;
  817.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  818.             ballToPlace->x = x;
  819.             ballToPlace->y = y;
  820.             ballToPlace->vx = 0;
  821.             ballToPlace->vy = 0;
  822.             ballToPlace->isPocketed = false;
  823.  
  824.             currentBall++;
  825.         }
  826.         if (currentBall >= rackBalls.size()) break;
  827.     }
  828.  
  829.     // Specific check for corner balls types after placing others (common rule: one solid, one stripe)
  830.     // Ball at index 0 (front) and indices 10, 14 (back corners)
  831.     Ball* frontBall = rackBalls[0];
  832.     Ball* corner1 = rackBalls[10]; // Bottom left corner of rack
  833.     Ball* corner2 = rackBalls[14]; // Bottom right corner of rack
  834.     if (corner1->type == corner2->type && corner1->id != 8 && corner2->id != 8) {
  835.         // Find a ball of the opposite type to swap with one corner
  836.         BallType typeNeeded = (corner1->type == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  837.         int swapIdx = -1;
  838.         for (size_t i = 1; i < rackBalls.size(); ++i) { // Start from 1 to avoid apex
  839.             // Don't swap with 8-ball or the other corner
  840.             if (rackBalls[i]->type == typeNeeded && rackBalls[i]->id != 8 && i != 10 && i != 14) {
  841.                 bool iIsEightBallPosition = false; // Check if this index is the 8-ball spot
  842.                 int temp_row = 0, temp_col = 0, count = 0;
  843.                 for (int r = 0; r < 5; ++r) for (int c = 0; c <= r; ++c) { if (count == i) { temp_row = r; temp_col = c; } count++; }
  844.                 iIsEightBallPosition = (temp_row == 2 && temp_col == 1);
  845.                 if (!iIsEightBallPosition) {
  846.                     swapIdx = i;
  847.                     break;
  848.                 }
  849.             }
  850.         }
  851.         if (swapIdx != -1) {
  852.             std::swap(rackBalls[10], rackBalls[swapIdx]); // Swap with one corner
  853.         }
  854.     }
  855.  
  856.  
  857.     // --- ADDITIONS FOR AI MODE ---
  858.     if (isPlayer2AI) {
  859.         // Already set name in ShowNewGameDialog / wWinMain
  860.         // player2Info.name = L"CPU"; // Or specific difficulty name set earlier
  861.  
  862.         // Randomly decide who breaks (50/50 chance)
  863.         if ((rand() % 2) == 0) {
  864.             // AI (Player 2) breaks
  865.             currentPlayer = 2;
  866.             // Need to handle cue ball placement for AI break?
  867.             // For now, AI will need ball-in-hand logic if it breaks first.
  868.             // Set state appropriate for AI break placement/shot
  869.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  870.             aiTurnPending = true; // Trigger AI logic immediately once placement done (or skip placement)
  871.         }
  872.         else {
  873.             // Player 1 breaks
  874.             currentPlayer = 1;
  875.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  876.             aiTurnPending = false;
  877.         }
  878.     }
  879.     else {
  880.         // Human vs Human, Player 1 always breaks currently
  881.         currentPlayer = 1;
  882.         currentGameState = PRE_BREAK_PLACEMENT;
  883.         aiTurnPending = false;
  884.     }
  885.  
  886.     // Reset other relevant state
  887.     foulCommitted = false;
  888.     gameOverMessage = L"";
  889.     firstBallPocketedAfterBreak = false;
  890.     pocketedThisTurn.clear();
  891.     // aiIsThinking = false; // Replaced by state
  892.     // Reset shot parameters
  893.     shotPower = 0.0f;
  894.     cueSpinX = 0.0f;
  895.     cueSpinY = 0.0f;
  896.     isAiming = false;
  897.     isDraggingCueBall = false;
  898.     isSettingEnglish = false;
  899. }
  900.  
  901.  
  902. // --- Game Loop ---
  903. void GameUpdate() {
  904.     if (currentGameState == SHOT_IN_PROGRESS) {
  905.         UpdatePhysics();
  906.         CheckCollisions();
  907.         bool pocketed = CheckPockets(); // Store if any ball was pocketed
  908.  
  909.         if (!AreBallsMoving()) {
  910.             ProcessShotResults(); // Determine next state based on what happened
  911.         }
  912.     }
  913.  
  914.     // --- NEW: Check if AI needs to act ---
  915.     else if (aiTurnPending && !AreBallsMoving()) {
  916.         // Check if it's genuinely AI's turn state and not mid-shot etc.
  917.         if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING || currentGameState == PRE_BREAK_PLACEMENT) {
  918.             // Only trigger if AI is P2, it's their turn/break, and balls stopped
  919.             if (isPlayer2AI && currentPlayer == 2) {
  920.                 // Transition state to show AI is thinking
  921.                 currentGameState = AI_THINKING;
  922.                 aiTurnPending = false; // Acknowledge the pending flag
  923.  
  924.                 // --- Trigger AI Decision Making ---
  925.                 // In a real game loop, you might start a timer here or background thread.
  926.                 // For simplicity here, we call it directly. This might pause rendering
  927.                 // briefly if AI calculation is slow.
  928.                 AIMakeDecision(); // AI calculates and applies shot
  929.  
  930.                 // AIMakeDecision should end by calling ApplyShot, which sets
  931.                 // currentGameState = SHOT_IN_PROGRESS
  932.                 // If AI fails to find a shot, need to handle that (e.g., pass turn - should be rare)
  933.             }
  934.             else {
  935.                 aiTurnPending = false; // Clear flag if conditions not met (e.g. P1's turn somehow)
  936.             }
  937.         }
  938.         else {
  939.             aiTurnPending = false; // Clear flag if not in a state where AI should shoot
  940.         }
  941.     }
  942.  
  943.     // Other states (AIMING, BALL_IN_HAND, etc.) are handled by input messages
  944. }
  945.  
  946. // --- Physics and Collision ---
  947. void UpdatePhysics() {
  948.     for (size_t i = 0; i < balls.size(); ++i) {
  949.         Ball& b = balls[i];
  950.         if (!b.isPocketed) {
  951.             b.x += b.vx;
  952.             b.y += b.vy;
  953.  
  954.             // Apply friction
  955.             b.vx *= FRICTION;
  956.             b.vy *= FRICTION;
  957.  
  958.             // Stop balls if velocity is very low
  959.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  960.                 b.vx = 0;
  961.                 b.vy = 0;
  962.             }
  963.         }
  964.     }
  965. }
  966.  
  967. void CheckCollisions() {
  968.     // --- Corrected Collision Boundaries ---
  969.     // These now represent the actual edges of the playable table surface
  970.     float left = TABLE_LEFT;
  971.     float right = TABLE_RIGHT;
  972.     float top = TABLE_TOP;
  973.     float bottom = TABLE_BOTTOM;
  974.  
  975.     // Define a radius around pocket centers to check if a ball is near a pocket mouth
  976.     // Use a value slightly larger than the pocket radius to prevent clipping the edge
  977.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f; // Check slightly larger area
  978.  
  979.     for (size_t i = 0; i < balls.size(); ++i) {
  980.         Ball& b1 = balls[i];
  981.         if (b1.isPocketed) continue; // Skip balls already pocketed
  982.  
  983.         // --- Pre-calculate proximity to pocket centers ---
  984.         // This avoids recalculating distances multiple times for wall checks
  985.         bool nearPocket[6];
  986.         for (int p = 0; p < 6; ++p) {
  987.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  988.         }
  989.         // Individual pocket proximity flags for clarity in wall checks
  990.         bool nearTopLeftPocket = nearPocket[0];
  991.         bool nearTopMidPocket = nearPocket[1];
  992.         bool nearTopRightPocket = nearPocket[2];
  993.         bool nearBottomLeftPocket = nearPocket[3];
  994.         bool nearBottomMidPocket = nearPocket[4];
  995.         bool nearBottomRightPocket = nearPocket[5];
  996.  
  997.  
  998.         // --- Ball-Wall Collisions (with Pocket Avoidance) ---
  999.         bool collidedWall = false; // Track if any wall collision happened for spin effects
  1000.  
  1001.         // Left Wall
  1002.         if (b1.x - BALL_RADIUS < left) {
  1003.             // Don't bounce if near top-left or bottom-left pocket mouths
  1004.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1005.                 b1.x = left + BALL_RADIUS;
  1006.                 b1.vx *= -1.0f;
  1007.                 collidedWall = true;
  1008.             } // else: Allow ball to continue towards pocket
  1009.         }
  1010.         // Right Wall
  1011.         if (b1.x + BALL_RADIUS > right) {
  1012.             // Don't bounce if near top-right or bottom-right pocket mouths
  1013.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1014.                 b1.x = right - BALL_RADIUS;
  1015.                 b1.vx *= -1.0f;
  1016.                 collidedWall = true;
  1017.             } // else: Allow ball to continue towards pocket
  1018.         }
  1019.         // Top Wall
  1020.         if (b1.y - BALL_RADIUS < top) {
  1021.             // Don't bounce if near top-left, top-mid, or top-right pocket mouths
  1022.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1023.                 b1.y = top + BALL_RADIUS;
  1024.                 b1.vy *= -1.0f;
  1025.                 collidedWall = true;
  1026.             } // else: Allow ball to continue towards pocket
  1027.         }
  1028.         // Bottom Wall
  1029.         if (b1.y + BALL_RADIUS > bottom) {
  1030.             // Don't bounce if near bottom-left, bottom-mid, or bottom-right pocket mouths
  1031.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1032.                 b1.y = bottom - BALL_RADIUS;
  1033.                 b1.vy *= -1.0f;
  1034.                 collidedWall = true;
  1035.             } // else: Allow ball to continue towards pocket
  1036.         }
  1037.  
  1038.         // Optional: Apply simplified spin effect on wall collision IF a bounce occurred
  1039.         if (collidedWall) {
  1040.             // Simple spin damping/effect (can be refined)
  1041.             // Side spin affects vertical velocity on horizontal collision & vice-versa
  1042.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { // Hit L/R wall
  1043.                 b1.vy += cueSpinX * b1.vx * 0.05f; // Apply small vertical impulse based on side spin and horizontal velocity
  1044.             }
  1045.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { // Hit T/B wall
  1046.                 b1.vx -= cueSpinY * b1.vy * 0.05f; // Apply small horizontal impulse based on top/bottom spin and vertical velocity
  1047.             }
  1048.             // Dampen spin after wall hit
  1049.             cueSpinX *= 0.7f; // Increase damping maybe
  1050.             cueSpinY *= 0.7f;
  1051.         }
  1052.  
  1053.  
  1054.         // --- Ball-Ball Collisions ---
  1055.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1056.             Ball& b2 = balls[j];
  1057.             if (b2.isPocketed) continue; // Skip pocketed balls
  1058.  
  1059.             float dx = b2.x - b1.x;
  1060.             float dy = b2.y - b1.y;
  1061.             float distSq = dx * dx + dy * dy;
  1062.             float minDist = BALL_RADIUS * 2.0f;
  1063.  
  1064.             if (distSq > 0 && distSq < minDist * minDist) { // Check distance squared first
  1065.                 float dist = sqrtf(distSq);
  1066.                 float overlap = minDist - dist;
  1067.  
  1068.                 // Normalize collision vector
  1069.                 float nx = dx / dist;
  1070.                 float ny = dy / dist;
  1071.  
  1072.                 // Separate balls to prevent sticking
  1073.                 // Move each ball half the overlap distance along the collision normal
  1074.                 b1.x -= overlap * 0.5f * nx;
  1075.                 b1.y -= overlap * 0.5f * ny;
  1076.                 b2.x += overlap * 0.5f * nx;
  1077.                 b2.y += overlap * 0.5f * ny;
  1078.  
  1079.                 // Relative velocity
  1080.                 float rvx = b1.vx - b2.vx;
  1081.                 float rvy = b1.vy - b2.vy;
  1082.  
  1083.                 // Dot product of relative velocity and collision normal
  1084.                 // This represents the component of relative velocity along the collision line
  1085.                 float velAlongNormal = rvx * nx + rvy * ny;
  1086.  
  1087.                 // Only resolve collision if balls are moving towards each other (dot product > 0)
  1088.                 if (velAlongNormal > 0) {
  1089.                     // Calculate impulse scalar (simplified - assumes equal mass, perfect elasticity=1.0)
  1090.                    // For perfect elastic collision, the impulse magnitude needed is velAlongNormal.
  1091.                    // Each ball gets half the impulse if masses are equal, but since we apply to both in opposite directions along the normal,
  1092.                    // the change in velocity for each along the normal is 'velAlongNormal'.
  1093.                     float impulse = velAlongNormal; // Simplified impulse magnitude along normal
  1094.  
  1095.                     // Apply impulse to velocities along the collision normal
  1096.                     b1.vx -= impulse * nx;
  1097.                     b1.vy -= impulse * ny;
  1098.                     b2.vx += impulse * nx;
  1099.                     b2.vy += impulse * ny;
  1100.  
  1101.                     // Apply spin transfer/effect (Very simplified)
  1102.                     if (b1.id == 0 || b2.id == 0) { // If cue ball involved
  1103.                         float spinEffectFactor = 0.08f; // Reduced factor maybe
  1104.                         // Simple model: Apply a small velocity change perpendicular to the normal based on spin
  1105.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor; // Spin effect
  1106.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor; // Spin effect (check signs/logic)
  1107.  
  1108.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1109.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1110.  
  1111.                         // Dampen spin after transfer
  1112.                         cueSpinX *= 0.85f;
  1113.                         cueSpinY *= 0.85f;
  1114.                     }
  1115.                 }
  1116.             }
  1117.         } // End ball-ball collision loop
  1118.     } // End loop through balls
  1119. } // End CheckCollisions
  1120.  
  1121.  
  1122. bool CheckPockets() {
  1123.     bool ballPocketed = false;
  1124.     for (size_t i = 0; i < balls.size(); ++i) {
  1125.         Ball& b = balls[i];
  1126.         if (!b.isPocketed) {
  1127.             for (int p = 0; p < 6; ++p) {
  1128.                 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
  1129.                 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
  1130.                     b.isPocketed = true;
  1131.                     b.vx = b.vy = 0;
  1132.                     pocketedThisTurn.push_back(b.id); // Record pocketed ball ID
  1133.                     ballPocketed = true;
  1134.                     break; // No need to check other pockets for this ball
  1135.                 }
  1136.             }
  1137.         }
  1138.     }
  1139.     return ballPocketed;
  1140. }
  1141.  
  1142. bool AreBallsMoving() {
  1143.     for (size_t i = 0; i < balls.size(); ++i) {
  1144.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1145.             return true;
  1146.         }
  1147.     }
  1148.     return false;
  1149. }
  1150.  
  1151. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1152.     Ball* cueBall = GetCueBall();
  1153.     if (cueBall) {
  1154.         // Reset position to a default (AI/Human might move it)
  1155.         cueBall->x = HEADSTRING_X * 0.5f;
  1156.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1157.         cueBall->vx = 0;
  1158.         cueBall->vy = 0;
  1159.         cueBall->isPocketed = false;
  1160.  
  1161.         // Set state based on who gets ball-in-hand
  1162.         if (currentPlayer == 1) { // Player 1 caused foul, Player 2 gets ball-in-hand
  1163.             if (isPlayer2AI) {
  1164.                 // AI gets ball-in-hand. Set state and trigger AI.
  1165.                 currentGameState = PLAYER2_TURN; // State remains P2 Turn
  1166.                 aiTurnPending = true; // AI will handle placement in its logic
  1167.             }
  1168.             else {
  1169.                 // Human Player 2 gets ball-in-hand
  1170.                 currentGameState = BALL_IN_HAND_P2;
  1171.             }
  1172.         }
  1173.         else { // Player 2 caused foul, Player 1 gets ball-in-hand
  1174.             currentGameState = BALL_IN_HAND_P1;
  1175.             aiTurnPending = false; // Ensure AI flag off if P1 gets ball-in-hand
  1176.         }
  1177.     }
  1178. }
  1179.  
  1180.  
  1181. // --- Game Logic ---
  1182.  
  1183. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1184.     Ball* cueBall = GetCueBall();
  1185.     if (cueBall) {
  1186.         cueBall->vx = cosf(angle) * power;
  1187.         cueBall->vy = sinf(angle) * power;
  1188.  
  1189.         // Apply English (Spin) - Simplified effect
  1190.         // Top/Bottom spin affects initial roll slightly
  1191.         cueBall->vx += sinf(angle) * spinY * 0.5f; // Small effect perpendicular to shot dir
  1192.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1193.         // Side spin affects initial direction slightly
  1194.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1195.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1196.  
  1197.         // Store spin for later use in collisions/cushions (could decay over time too)
  1198.         cueSpinX = spinX;
  1199.         cueSpinY = spinY;
  1200.     }
  1201. }
  1202.  
  1203.  
  1204. void ProcessShotResults() {
  1205.     bool cueBallPocketed = false;
  1206.     bool eightBallPocketed = false;
  1207.     bool legalBallPocketed = false; // Player's own ball type
  1208.     bool opponentBallPocketed = false; // Opponent's ball type
  1209.     bool anyNonCueBallPocketed = false;
  1210.     BallType firstPocketedType = BallType::NONE;
  1211.  
  1212.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1213.     PlayerInfo& opponentPlayerInfo = (currentPlayer == 1) ? player2Info : player1Info;
  1214.  
  1215.  
  1216.     // Analyze pocketed balls
  1217.     for (int pocketedId : pocketedThisTurn) {
  1218.         Ball* b = GetBallById(pocketedId);
  1219.         if (!b) continue;
  1220.  
  1221.         if (b->id == 0) {
  1222.             cueBallPocketed = true;
  1223.         }
  1224.         else if (b->id == 8) {
  1225.             eightBallPocketed = true;
  1226.         }
  1227.         else {
  1228.             anyNonCueBallPocketed = true;
  1229.             if (firstPocketedType == BallType::NONE) {
  1230.                 firstPocketedType = b->type; // Record type of first non-8 ball pocketed
  1231.             }
  1232.  
  1233.             // Check if ball matches player's assigned type (if assigned)
  1234.             if (currentPlayerInfo.assignedType != BallType::NONE) {
  1235.                 if (b->type == currentPlayerInfo.assignedType) {
  1236.                     legalBallPocketed = true;
  1237.                 }
  1238.                 else if (b->type == opponentPlayerInfo.assignedType) {
  1239.                     opponentBallPocketed = true; // Pocketed opponent's ball
  1240.                 }
  1241.             }
  1242.         }
  1243.     }
  1244.  
  1245.     // --- Game Over Checks ---
  1246.     if (eightBallPocketed) {
  1247.         CheckGameOverConditions(eightBallPocketed, cueBallPocketed);
  1248.         if (currentGameState == GAME_OVER) return; // Stop processing if game ended
  1249.     }
  1250.  
  1251.     // --- Foul Checks ---
  1252.     bool turnFoul = false;
  1253.     if (cueBallPocketed) {
  1254.         foulCommitted = true;
  1255.         turnFoul = true;
  1256.     }
  1257.     // Add other foul conditions here (e.g., no ball hit cushion after contact, first ball hit wasn't legal)
  1258.     // For simplicity, only scratch and wrong ball pocketed first are fouls here.
  1259.     // If player pockets opponent ball BEFORE their own, it can be a foul in some rulesets.
  1260.     // Let's simplify: Pocketing opponent ball is only a foul if NO own balls pocketed.
  1261.     if (opponentBallPocketed && !legalBallPocketed && currentPlayerInfo.assignedType != BallType::NONE) {
  1262.         //foulCommitted = true; // Optional rule: fouling by pocketing only opponent ball
  1263.         //turnFoul = true;
  1264.     }
  1265.  
  1266.  
  1267.     // --- State Transitions ---
  1268.  
  1269.     // 1. Break Shot Results (Assigning Colors)
  1270.     if (player1Info.assignedType == BallType::NONE && anyNonCueBallPocketed && !cueBallPocketed) {
  1271.         AssignPlayerBallTypes(firstPocketedType);
  1272.         // Update ball counts for newly assigned types
  1273.         player1Info.ballsPocketedCount = 0;
  1274.         player2Info.ballsPocketedCount = 0;
  1275.         for (int id : pocketedThisTurn) {
  1276.             Ball* b = GetBallById(id);
  1277.             if (b && b->id != 0 && b->id != 8) {
  1278.                 if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  1279.                 else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  1280.             }
  1281.         }
  1282.  
  1283.         // Did the current player pocket their *newly assigned* type?
  1284.         bool pocketedOwnTypeOnBreakAssign = false;
  1285.         if (firstPocketedType == currentPlayerInfo.assignedType) {
  1286.             pocketedOwnTypeOnBreakAssign = true;
  1287.         }
  1288.  
  1289.         if (pocketedOwnTypeOnBreakAssign) {
  1290.             // Continue turn
  1291.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1292.         }
  1293.         else {
  1294.             // Switch turns
  1295.             SwitchTurns();
  1296.         }
  1297.     }
  1298.     // 2. Normal Play Results
  1299.     else {
  1300.         // Update pocketed counts
  1301.         for (int id : pocketedThisTurn) {
  1302.             Ball* b = GetBallById(id);
  1303.             if (!b || b->id == 0 || b->id == 8) continue;
  1304.             if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  1305.             else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  1306.         }
  1307.  
  1308.         if (turnFoul) {
  1309.             SwitchTurns();
  1310.             RespawnCueBall(false); // Ball in hand for opponent
  1311.             // State already set in RespawnCueBall
  1312.         }
  1313.         else if (legalBallPocketed) {
  1314.             // Player legally pocketed their own ball, continue turn
  1315.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1316.         }
  1317.         else {
  1318.             // No legal ball pocketed (missed or only opponent ball)
  1319.             SwitchTurns();
  1320.         }
  1321.     }
  1322.  
  1323.     // Clear pocketed list for the next shot
  1324.     pocketedThisTurn.clear();
  1325.  
  1326.     // If a foul occurred but wasn't a scratch, maybe still switch turn?
  1327.     // Current logic handles scratch = foul = switch + ball-in-hand.
  1328.     // Other fouls could just mean switch turn.
  1329. }
  1330.  
  1331.  
  1332. void AssignPlayerBallTypes(BallType firstPocketedType) {
  1333.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  1334.         if (currentPlayer == 1) {
  1335.             player1Info.assignedType = firstPocketedType;
  1336.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1337.         }
  1338.         else {
  1339.             player2Info.assignedType = firstPocketedType;
  1340.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1341.         }
  1342.     }
  1343.     // If 8-ball was first (illegal on break generally), rules vary.
  1344.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  1345.     // Or assign based on what *else* was pocketed, if anything.
  1346.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  1347. }
  1348.  
  1349. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  1350.     if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
  1351.  
  1352.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1353.     bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
  1354.  
  1355.     // Loss Conditions:
  1356.     // 1. Pocket 8-ball AND scratch (pocket cue ball)
  1357.     // 2. Pocket 8-ball before clearing own color group
  1358.     if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
  1359.         gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
  1360.         currentGameState = GAME_OVER;
  1361.     }
  1362.     // Win Condition:
  1363.     // 1. Pocket 8-ball legally after clearing own color group
  1364.     else if (playerClearedBalls) {
  1365.         gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
  1366.         currentGameState = GAME_OVER;
  1367.     }
  1368.     // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
  1369.     // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
  1370.     else if (player1Info.assignedType == BallType::NONE) {
  1371.         Ball* eightBall = GetBallById(8);
  1372.         if (eightBall) {
  1373.             eightBall->isPocketed = false;
  1374.             // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
  1375.             eightBall->x = RACK_POS_X;
  1376.             eightBall->y = RACK_POS_Y;
  1377.             eightBall->vx = eightBall->vy = 0;
  1378.             // Check overlap and nudge if necessary (simplified)
  1379.         }
  1380.         // Apply foul rules if cue ball was also pocketed
  1381.         if (cueBallPocketed) {
  1382.             foulCommitted = true;
  1383.             // Don't switch turns on break scratch + 8ball pocket? Rules vary.
  1384.             // Let's make it a foul, switch turns, ball in hand.
  1385.             SwitchTurns();
  1386.             RespawnCueBall(false); // Ball in hand for opponent
  1387.         }
  1388.         else {
  1389.             // Just respawned 8ball, continue turn or switch based on other balls pocketed.
  1390.             // Let ProcessShotResults handle turn logic based on other pocketed balls.
  1391.         }
  1392.         // Prevent immediate game over message by returning here
  1393.         return;
  1394.     }
  1395.  
  1396.  
  1397. }
  1398.  
  1399.  
  1400. void SwitchTurns() {
  1401.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  1402.     // Reset aiming state for the new player
  1403.     isAiming = false;
  1404.     shotPower = 0;
  1405.     // Reset foul flag before new turn *really* starts (AI might take over)
  1406.     // Foul flag is mainly for display, gets cleared before human/AI shot
  1407.     // foulCommitted = false; // Probably better to clear before ApplyShot
  1408.  
  1409.     // Set the correct state based on who's turn it is
  1410.     if (currentPlayer == 1) {
  1411.         currentGameState = PLAYER1_TURN;
  1412.         aiTurnPending = false; // Ensure AI flag is off for P1
  1413.     }
  1414.     else { // Player 2's turn
  1415.         if (isPlayer2AI) {
  1416.             currentGameState = PLAYER2_TURN; // State indicates it's P2's turn
  1417.             aiTurnPending = true;           // Set flag for GameUpdate to trigger AI
  1418.             // AI will handle Ball-in-Hand logic if necessary within its decision making
  1419.         }
  1420.         else {
  1421.             currentGameState = PLAYER2_TURN; // Human P2
  1422.             aiTurnPending = false;
  1423.         }
  1424.     }
  1425. }
  1426.  
  1427. // --- Helper Functions ---
  1428.  
  1429. Ball* GetBallById(int id) {
  1430.     for (size_t i = 0; i < balls.size(); ++i) {
  1431.         if (balls[i].id == id) {
  1432.             return &balls[i];
  1433.         }
  1434.     }
  1435.     return nullptr;
  1436. }
  1437.  
  1438. Ball* GetCueBall() {
  1439.     return GetBallById(0);
  1440. }
  1441.  
  1442. float GetDistance(float x1, float y1, float x2, float y2) {
  1443.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  1444. }
  1445.  
  1446. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  1447.     float dx = x2 - x1;
  1448.     float dy = y2 - y1;
  1449.     return dx * dx + dy * dy;
  1450. }
  1451.  
  1452. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  1453.     // Basic bounds check (inside cushions)
  1454.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  1455.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  1456.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  1457.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  1458.  
  1459.     if (x < left || x > right || y < top || y > bottom) {
  1460.         return false;
  1461.     }
  1462.  
  1463.     // Check headstring restriction if needed
  1464.     if (checkHeadstring && x >= HEADSTRING_X) {
  1465.         return false;
  1466.     }
  1467.  
  1468.     // Check overlap with other balls
  1469.     for (size_t i = 0; i < balls.size(); ++i) {
  1470.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  1471.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  1472.                 return false; // Overlapping another ball
  1473.             }
  1474.         }
  1475.     }
  1476.  
  1477.     return true;
  1478. }
  1479.  
  1480.  
  1481. template <typename T>
  1482. void SafeRelease(T** ppT) {
  1483.     if (*ppT) {
  1484.         (*ppT)->Release();
  1485.         *ppT = nullptr;
  1486.     }
  1487. }
  1488.  
  1489. // --- NEW AI Implementation Functions ---
  1490.  
  1491. // Main entry point for AI turn
  1492. void AIMakeDecision() {
  1493.     Ball* cueBall = GetCueBall();
  1494.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return; // Safety checks
  1495.  
  1496.     // Handle Ball-in-Hand placement first if necessary
  1497.     if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BALL_IN_HAND_P2) {
  1498.         AIPlaceCueBall();
  1499.         // After placement, state should transition to PLAYER2_TURN or BREAKING
  1500.         currentGameState = (player1Info.assignedType == BallType::NONE) ? BREAKING : PLAYER2_TURN;
  1501.     }
  1502.  
  1503.     // Now find the best shot from the current position
  1504.     AIShotInfo bestShot = AIFindBestShot();
  1505.  
  1506.     if (bestShot.possible) {
  1507.         // Add slight delay maybe? For now, shoot immediately.
  1508.         // Apply calculated shot
  1509.         ApplyShot(bestShot.power, bestShot.angle, 0.0f, 0.0f); // AI doesn't use spin yet
  1510.  
  1511.         // Set state to shot in progress (ApplyShot might do this already)
  1512.         currentGameState = SHOT_IN_PROGRESS;
  1513.         foulCommitted = false; // Reset foul flag for AI shot
  1514.         pocketedThisTurn.clear(); // Clear previous pockets
  1515.     }
  1516.     else {
  1517.         // AI couldn't find any shot (highly unlikely with simple logic, but possible)
  1518.         // Safety shot? Push cue ball gently? Forfeit turn?
  1519.         // Simplest: Just tap the cue ball gently forward as a safety/pass.
  1520.         ApplyShot(MAX_SHOT_POWER * 0.1f, 0.0f, 0.0f, 0.0f); // Gentle tap forward
  1521.         currentGameState = SHOT_IN_PROGRESS;
  1522.         foulCommitted = false;
  1523.         pocketedThisTurn.clear();
  1524.         // NOTE: This might cause a foul if no ball is hit. Harder AI would handle this better.
  1525.     }
  1526.     aiTurnPending = false; // Ensure flag is off after decision
  1527. }
  1528.  
  1529. // AI logic for placing cue ball during ball-in-hand
  1530. void AIPlaceCueBall() {
  1531.     Ball* cueBall = GetCueBall();
  1532.     if (!cueBall) return;
  1533.  
  1534.     // Simple Strategy: Find the easiest possible shot for the AI's ball type
  1535.     // Place the cue ball directly behind that target ball, aiming straight at a pocket.
  1536.     // (More advanced: find spot offering multiple options or safety)
  1537.  
  1538.     AIShotInfo bestPlacementShot = { false };
  1539.     D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
  1540.  
  1541.     BallType targetType = player2Info.assignedType;
  1542.     bool canTargetAnyPlacement = false; // Local scope variable for placement logic
  1543.     if (targetType == BallType::NONE) {
  1544.         canTargetAnyPlacement = true;
  1545.     }
  1546.     bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1547.     if (target8Ball) targetType = BallType::EIGHT_BALL;
  1548.  
  1549.  
  1550.     for (auto& targetBall : balls) {
  1551.         if (targetBall.isPocketed || targetBall.id == 0) continue;
  1552.  
  1553.         // Determine if current ball is a valid target for placement consideration
  1554.         bool currentBallIsValidTarget = false;
  1555.         if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
  1556.         else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
  1557.         else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
  1558.  
  1559.         if (!currentBallIsValidTarget) continue; // Skip if not a valid target
  1560.  
  1561.         for (int p = 0; p < 6; ++p) {
  1562.             // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
  1563.             float targetToPocketX = pocketPositions[p].x - targetBall.x;
  1564.             float targetToPocketY = pocketPositions[p].y - targetBall.y;
  1565.             float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1566.             if (dist < 1.0f) continue; // Avoid division by zero
  1567.  
  1568.             float idealAngle = atan2f(targetToPocketY, targetToPocketX);
  1569.             // Place cue ball slightly behind target ball along this line
  1570.             float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
  1571.             D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
  1572.                 targetBall.x - cosf(idealAngle) * placeDist,
  1573.                 targetBall.y - sinf(idealAngle) * placeDist
  1574.             );
  1575.  
  1576.             // Check if this placement is valid (on table, behind headstring if break, not overlapping)
  1577.             bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);
  1578.             if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
  1579.                 // Is path from potentialPlacePos to targetBall clear?
  1580.                 // Use D2D1::Point2F() factory function here
  1581.                 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
  1582.                     // Is path from targetBall to pocket clear?
  1583.                     // Use D2D1::Point2F() factory function here
  1584.                     if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
  1585.                         // This seems like a good potential placement. Score it?
  1586.                         // Easy AI: Just take the first valid one found.
  1587.                         bestPlacePos = potentialPlacePos;
  1588.                         goto placement_found; // Use goto for simplicity in non-OOP structure
  1589.                     }
  1590.                 }
  1591.             }
  1592.         }
  1593.     }
  1594.  
  1595. placement_found:
  1596.     // Place the cue ball at the best found position (or default if none found)
  1597.     cueBall->x = bestPlacePos.x;
  1598.     cueBall->y = bestPlacePos.y;
  1599.     cueBall->vx = 0;
  1600.     cueBall->vy = 0;
  1601. }
  1602.  
  1603.  
  1604. // AI finds the best shot available on the table
  1605. AIShotInfo AIFindBestShot() {
  1606.     AIShotInfo bestShotOverall = { false };
  1607.     Ball* cueBall = GetCueBall();
  1608.     if (!cueBall) return bestShotOverall;
  1609.  
  1610.     // Determine target ball type for AI (Player 2)
  1611.     BallType targetType = player2Info.assignedType;
  1612.     bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
  1613.     if (targetType == BallType::NONE) {
  1614.         // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
  1615.         // Or, more simply, treat any ball as a potential target to make *a* pocket
  1616.         canTargetAny = true; // Simplification: allow targeting any non-8 ball.
  1617.         // A better rule is hit lowest numbered ball first on break follow-up.
  1618.     }
  1619.  
  1620.     // Check if AI needs to shoot the 8-ball
  1621.     bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1622.  
  1623.  
  1624.     // Iterate through all potential target balls
  1625.     for (auto& potentialTarget : balls) {
  1626.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
  1627.  
  1628.         // Check if this ball is a valid target
  1629.         bool isValidTarget = false;
  1630.         if (target8Ball) {
  1631.             isValidTarget = (potentialTarget.id == 8);
  1632.         }
  1633.         else if (canTargetAny) {
  1634.             isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
  1635.         }
  1636.         else { // Colors assigned, not yet shooting 8-ball
  1637.             isValidTarget = (potentialTarget.type == targetType);
  1638.         }
  1639.  
  1640.         if (!isValidTarget) continue; // Skip if not a valid target for this turn
  1641.  
  1642.         // Now, check all pockets for this target ball
  1643.         for (int p = 0; p < 6; ++p) {
  1644.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  1645.             currentShot.involves8Ball = (potentialTarget.id == 8);
  1646.  
  1647.             if (currentShot.possible) {
  1648.                 // Compare scores to find the best shot
  1649.                 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  1650.                     bestShotOverall = currentShot;
  1651.                 }
  1652.             }
  1653.         }
  1654.     } // End loop through potential target balls
  1655.  
  1656.     // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
  1657.     // need a safety strategy. Current simple AI just takes best found or taps cue ball.
  1658.  
  1659.     return bestShotOverall;
  1660. }
  1661.  
  1662.  
  1663. // Evaluate a potential shot at a specific target ball towards a specific pocket
  1664. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  1665.     AIShotInfo shotInfo;
  1666.     shotInfo.possible = false; // Assume not possible initially
  1667.     shotInfo.targetBall = targetBall;
  1668.     shotInfo.pocketIndex = pocketIndex;
  1669.  
  1670.     Ball* cueBall = GetCueBall();
  1671.     if (!cueBall || !targetBall) return shotInfo;
  1672.  
  1673.     // --- Define local state variables needed for legality checks ---
  1674.     BallType aiAssignedType = player2Info.assignedType;
  1675.     bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
  1676.     bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1677.     // ---
  1678.  
  1679.     // 1. Calculate Ghost Ball position
  1680.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  1681.  
  1682.     // 2. Calculate Angle from Cue Ball to Ghost Ball
  1683.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  1684.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  1685.     if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
  1686.     shotInfo.angle = atan2f(dy, dx);
  1687.  
  1688.     // Basic angle validity check (optional)
  1689.     if (!IsValidAIAimAngle(shotInfo.angle)) {
  1690.         // Maybe log this or handle edge cases
  1691.     }
  1692.  
  1693.     // 3. Check Path: Cue Ball -> Ghost Ball Position
  1694.     // Use D2D1::Point2F() factory function here
  1695.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  1696.         return shotInfo; // Path blocked
  1697.     }
  1698.  
  1699.     // 4. Check Path: Target Ball -> Pocket
  1700.     // Use D2D1::Point2F() factory function here
  1701.     if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
  1702.         return shotInfo; // Path blocked
  1703.     }
  1704.  
  1705.     // 5. Check First Ball Hit Legality
  1706.     float firstHitDistSq = -1.0f;
  1707.     // Use D2D1::Point2F() factory function here
  1708.     Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
  1709.  
  1710.     if (!firstHit) {
  1711.         return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
  1712.     }
  1713.  
  1714.     // Check if the first ball hit is the intended target ball
  1715.     if (firstHit->id != targetBall->id) {
  1716.         // Allow hitting slightly off target if it's very close to ghost ball pos
  1717.         float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
  1718.         // Allow a tolerance roughly half the ball radius squared
  1719.         if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
  1720.             // First hit is significantly different from the target point.
  1721.             // This shot path leads to hitting the wrong ball first.
  1722.             return shotInfo; // Foul or unintended shot
  1723.         }
  1724.         // If first hit is not target, but very close, allow it for now (might still be foul based on type).
  1725.     }
  1726.  
  1727.     // Check legality of the *first ball actually hit* based on game rules
  1728.     if (!canTargetAny) { // Colors are assigned (or should be)
  1729.         if (mustTarget8Ball) { // Must hit 8-ball first
  1730.             if (firstHit->id != 8) {
  1731.                 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
  1732.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1733.             }
  1734.         }
  1735.         else { // Must hit own ball type first
  1736.             if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
  1737.                 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
  1738.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1739.             }
  1740.             else if (firstHit->id == 8) {
  1741.                 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
  1742.                 // Keep shot possible for now
  1743.             }
  1744.         }
  1745.     }
  1746.     // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
  1747.  
  1748.  
  1749.     // 6. Calculate Score & Power (Difficulty affects this)
  1750.     shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
  1751.  
  1752.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  1753.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  1754.  
  1755.     // Simple Score: Shorter shots are better, straighter shots are slightly better.
  1756.     float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
  1757.  
  1758.     // Angle Score: Calculate cut angle
  1759.     // Vector Cue -> Ghost
  1760.     float v1x = shotInfo.ghostBallPos.x - cueBall->x;
  1761.     float v1y = shotInfo.ghostBallPos.y - cueBall->y;
  1762.     // Vector Target -> Pocket
  1763.     float v2x = pocketPositions[pocketIndex].x - targetBall->x;
  1764.     float v2y = pocketPositions[pocketIndex].y - targetBall->y;
  1765.     // Normalize vectors
  1766.     float mag1 = sqrtf(v1x * v1x + v1y * v1y);
  1767.     float mag2 = sqrtf(v2x * v2x + v2y * v2y);
  1768.     float angleScoreFactor = 0.5f; // Default if vectors are zero len
  1769.     if (mag1 > 0.1f && mag2 > 0.1f) {
  1770.         v1x /= mag1; v1y /= mag1;
  1771.         v2x /= mag2; v2y /= mag2;
  1772.         // Dot product gives cosine of angle between cue ball path and target ball path
  1773.         float dotProduct = v1x * v2x + v1y * v2y;
  1774.         // Straighter shot (dot product closer to 1) gets higher score
  1775.         angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
  1776.     }
  1777.     angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
  1778.  
  1779.     shotInfo.score = distanceScore * angleScoreFactor;
  1780.  
  1781.     // Bonus for pocketing 8-ball legally
  1782.     if (mustTarget8Ball && targetBall->id == 8) {
  1783.         shotInfo.score *= 10.0; // Strongly prefer the winning shot
  1784.     }
  1785.  
  1786.     // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
  1787.  
  1788.     // 7. Calculate Power
  1789.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  1790.  
  1791.     // 8. Add Inaccuracy based on Difficulty (same as before)
  1792.     float angleError = 0.0f;
  1793.     float powerErrorFactor = 1.0f;
  1794.  
  1795.     switch (aiDifficulty) {
  1796.     case EASY:
  1797.         angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
  1798.         powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
  1799.         shotInfo.power *= 0.8f;
  1800.         break;
  1801.     case MEDIUM:
  1802.         angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
  1803.         powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
  1804.         break;
  1805.     case HARD:
  1806.         angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
  1807.         powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
  1808.         break;
  1809.     }
  1810.     shotInfo.angle += angleError;
  1811.     shotInfo.power *= powerErrorFactor;
  1812.     shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
  1813.  
  1814.     return shotInfo;
  1815. }
  1816.  
  1817.  
  1818. // Calculates required power (simplified)
  1819. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  1820.     // Basic model: Power needed increases with total distance the balls need to travel.
  1821.     // Need enough power for cue ball to reach target AND target to reach pocket.
  1822.     float totalDist = cueToGhostDist + targetToPocketDist;
  1823.  
  1824.     // Map distance to power (needs tuning)
  1825.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  1826.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  1827.  
  1828.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  1829.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  1830.  
  1831.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  1832.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  1833. }
  1834.  
  1835. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  1836. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  1837.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  1838.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  1839.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1840.  
  1841.     if (dist < 1.0f) { // Target is basically in the pocket
  1842.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  1843.         // For simplicity, return a point slightly behind center along the reverse line.
  1844.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  1845.     }
  1846.  
  1847.     // Normalize direction vector from target to pocket
  1848.     float nx = targetToPocketX / dist;
  1849.     float ny = targetToPocketY / dist;
  1850.  
  1851.     // Ghost ball position is diameter distance *behind* the target ball along this line
  1852.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  1853.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  1854.  
  1855.     return D2D1::Point2F(ghostX, ghostY);
  1856. }
  1857.  
  1858. // Checks if line segment is clear of obstructing balls
  1859. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  1860.     float dx = end.x - start.x;
  1861.     float dy = end.y - start.y;
  1862.     float segmentLenSq = dx * dx + dy * dy;
  1863.  
  1864.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  1865.  
  1866.     for (const auto& ball : balls) {
  1867.         if (ball.isPocketed) continue;
  1868.         if (ball.id == ignoredBallId1) continue;
  1869.         if (ball.id == ignoredBallId2) continue;
  1870.  
  1871.         // Check distance from ball center to the line segment
  1872.         float ballToStartX = ball.x - start.x;
  1873.         float ballToStartY = ball.y - start.y;
  1874.  
  1875.         // Project ball center onto the line defined by the segment
  1876.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  1877.  
  1878.         D2D1_POINT_2F closestPointOnLine;
  1879.         if (dot < 0) { // Closest point is start point
  1880.             closestPointOnLine = start;
  1881.         }
  1882.         else if (dot > 1) { // Closest point is end point
  1883.             closestPointOnLine = end;
  1884.         }
  1885.         else { // Closest point is along the segment
  1886.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  1887.         }
  1888.  
  1889.         // Check if the closest point is within collision distance (ball radius + path radius)
  1890.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  1891.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  1892.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  1893.             return false; // Path is blocked
  1894.         }
  1895.     }
  1896.     return true; // No obstructions found
  1897. }
  1898.  
  1899. // Finds the first ball hit along a path (simplified)
  1900. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  1901.     Ball* hitBall = nullptr;
  1902.     hitDistSq = -1.0f; // Initialize hit distance squared
  1903.     float minCollisionDistSq = -1.0f;
  1904.  
  1905.     float cosA = cosf(angle);
  1906.     float sinA = sinf(angle);
  1907.  
  1908.     for (auto& ball : balls) {
  1909.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  1910.  
  1911.         float dx = ball.x - start.x;
  1912.         float dy = ball.y - start.y;
  1913.  
  1914.         // Project vector from start->ball onto the aim direction vector
  1915.         float dot = dx * cosA + dy * sinA;
  1916.  
  1917.         if (dot > 0) { // Ball is generally in front
  1918.             // Find closest point on aim line to the ball's center
  1919.             float closestPointX = start.x + dot * cosA;
  1920.             float closestPointY = start.y + dot * sinA;
  1921.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  1922.  
  1923.             // Check if the aim line passes within the ball's radius
  1924.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  1925.                 // Calculate distance from start to the collision point on the ball's circumference
  1926.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  1927.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  1928.  
  1929.                 if (collisionDist > 0) { // Ensure collision is in front
  1930.                     float collisionDistSq = collisionDist * collisionDist;
  1931.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  1932.                         minCollisionDistSq = collisionDistSq;
  1933.                         hitBall = &ball; // Found a closer hit ball
  1934.                     }
  1935.                 }
  1936.             }
  1937.         }
  1938.     }
  1939.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  1940.     return hitBall;
  1941. }
  1942.  
  1943. // Basic check for reasonable AI aim angles (optional)
  1944. bool IsValidAIAimAngle(float angle) {
  1945.     // Placeholder - could check for NaN or infinity if calculations go wrong
  1946.     return isfinite(angle);
  1947. }
  1948.  
  1949. // --- Drawing Functions ---
  1950.  
  1951. void OnPaint() {
  1952.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  1953.  
  1954.     if (SUCCEEDED(hr)) {
  1955.         pRenderTarget->BeginDraw();
  1956.         DrawScene(pRenderTarget); // Pass render target
  1957.         hr = pRenderTarget->EndDraw();
  1958.  
  1959.         if (hr == D2DERR_RECREATE_TARGET) {
  1960.             DiscardDeviceResources();
  1961.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  1962.             // But the timer loop will trigger redraw anyway.
  1963.         }
  1964.     }
  1965.     // If CreateDeviceResources failed, EndDraw might not be called.
  1966.     // Consider handling this more robustly if needed.
  1967. }
  1968.  
  1969. void DrawScene(ID2D1RenderTarget* pRT) {
  1970.     if (!pRT) return;
  1971.  
  1972.     pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  1973.  
  1974.     DrawTable(pRT);
  1975.     DrawBalls(pRT);
  1976.     DrawAimingAids(pRT); // Includes cue stick if aiming
  1977.     DrawUI(pRT);
  1978.     DrawPowerMeter(pRT);
  1979.     DrawSpinIndicator(pRT);
  1980.     DrawPocketedBallsIndicator(pRT);
  1981.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  1982.  
  1983.      // Draw Game Over Message
  1984.     if (currentGameState == GAME_OVER && pTextFormat) {
  1985.         ID2D1SolidColorBrush* pBrush = nullptr;
  1986.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  1987.         if (pBrush) {
  1988.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  1989.             pRT->DrawText(
  1990.                 gameOverMessage.c_str(),
  1991.                 (UINT32)gameOverMessage.length(),
  1992.                 pTextFormat, // Use large format maybe?
  1993.                 &layoutRect,
  1994.                 pBrush
  1995.             );
  1996.             SafeRelease(&pBrush);
  1997.         }
  1998.     }
  1999.  
  2000. }
  2001.  
  2002. void DrawTable(ID2D1RenderTarget* pRT) {
  2003.     ID2D1SolidColorBrush* pBrush = nullptr;
  2004.  
  2005.     // Draw Table Bed (Green Felt)
  2006.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  2007.     if (!pBrush) return;
  2008.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  2009.     pRT->FillRectangle(&tableRect, pBrush);
  2010.     SafeRelease(&pBrush);
  2011.  
  2012.     // Draw Cushions (Red Border)
  2013.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  2014.     if (!pBrush) return;
  2015.     // Top Cushion (split by middle pocket)
  2016.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  2017.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  2018.     // Bottom Cushion (split by middle pocket)
  2019.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  2020.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  2021.     // Left Cushion
  2022.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2023.     // Right Cushion
  2024.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2025.     SafeRelease(&pBrush);
  2026.  
  2027.  
  2028.     // Draw Pockets (Black Circles)
  2029.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  2030.     if (!pBrush) return;
  2031.     for (int i = 0; i < 6; ++i) {
  2032.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  2033.         pRT->FillEllipse(&ellipse, pBrush);
  2034.     }
  2035.     SafeRelease(&pBrush);
  2036.  
  2037.     // Draw Headstring Line (White)
  2038.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush);
  2039.     if (!pBrush) return;
  2040.     pRT->DrawLine(
  2041.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  2042.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  2043.         pBrush,
  2044.         1.0f // Line thickness
  2045.     );
  2046.     SafeRelease(&pBrush);
  2047. }
  2048.  
  2049.  
  2050. void DrawBalls(ID2D1RenderTarget* pRT) {
  2051.     ID2D1SolidColorBrush* pBrush = nullptr;
  2052.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  2053.  
  2054.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  2055.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  2056.  
  2057.     if (!pBrush || !pStripeBrush) {
  2058.         SafeRelease(&pBrush);
  2059.         SafeRelease(&pStripeBrush);
  2060.         return;
  2061.     }
  2062.  
  2063.  
  2064.     for (size_t i = 0; i < balls.size(); ++i) {
  2065.         const Ball& b = balls[i];
  2066.         if (!b.isPocketed) {
  2067.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  2068.  
  2069.             // Set main ball color
  2070.             pBrush->SetColor(b.color);
  2071.             pRT->FillEllipse(&ellipse, pBrush);
  2072.  
  2073.             // Draw Stripe if applicable
  2074.             if (b.type == BallType::STRIPE) {
  2075.                 // Draw a white band across the middle (simplified stripe)
  2076.                 D2D1_RECT_F stripeRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS * 0.4f, b.x + BALL_RADIUS, b.y + BALL_RADIUS * 0.4f);
  2077.                 // Need to clip this rectangle to the ellipse bounds - complex!
  2078.                 // Alternative: Draw two colored arcs leaving a white band.
  2079.                 // Simplest: Draw a white circle inside, slightly smaller.
  2080.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  2081.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  2082.                 pBrush->SetColor(b.color); // Set back to stripe color
  2083.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  2084.  
  2085.                 // Let's try drawing a thick white line across
  2086.                 // This doesn't look great. Just drawing solid red for stripes for now.
  2087.             }
  2088.  
  2089.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  2090.             // if (b.id != 0 && pTextFormat) {
  2091.             //     std::wstring numStr = std::to_wstring(b.id);
  2092.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  2093.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  2094.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  2095.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  2096.             //     // Create a smaller text format...
  2097.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  2098.             //     SafeRelease(&pNumBrush);
  2099.             // }
  2100.         }
  2101.     }
  2102.  
  2103.     SafeRelease(&pBrush);
  2104.     SafeRelease(&pStripeBrush);
  2105. }
  2106.  
  2107.  
  2108. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  2109.     // --- Modified Condition ---
  2110.     // Draw aiming aids whenever it's a player's turn to aim or shoot, or during the break setup/aim.
  2111.     if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  2112.         currentGameState != BREAKING && currentGameState != AIMING &&
  2113.         currentGameState != PRE_BREAK_PLACEMENT) // Also show direction during initial placement maybe? Let's stick to active turns/aiming for now.
  2114.     {
  2115.         // Let's refine: show only when player can actually shoot or is aiming
  2116.         if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  2117.             currentGameState != BREAKING && currentGameState != AIMING)
  2118.         {
  2119.             return;
  2120.         }
  2121.     }
  2122.  
  2123.     Ball* cueBall = GetCueBall();
  2124.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  2125.  
  2126.     ID2D1SolidColorBrush* pBrush = nullptr;
  2127.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2128.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  2129.     ID2D1SolidColorBrush* pCueBrush = nullptr; // Moved cue brush here
  2130.  
  2131.     // Ensure render target is valid
  2132.     if (!pRT) return;
  2133.  
  2134.     // Create Brushes and Styles (check for failures)
  2135.     HRESULT hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  2136.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  2137.  
  2138.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush); // Semi-transparent white
  2139.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  2140.  
  2141.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush); // Brownish cue stick
  2142.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  2143.  
  2144.  
  2145.     // Create dashed line style (Only if needed - Check Factory first)
  2146.     if (pFactory) {
  2147.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  2148.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  2149.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  2150.         // Don't exit entirely if dashed style fails, just draw solid lines later maybe?
  2151.         if FAILED(hr) { pDashedStyle = nullptr; } // Ensure it's null if failed
  2152.     }
  2153.  
  2154.  
  2155.     // --- Aiming Line & Cue Stick ---
  2156.     float stickLength = 150.0f;
  2157.     float stickAngle = cueAngle + PI; // Stick points opposite to aim direction
  2158.  
  2159.     // --- Modified Power Offset ---
  2160.     // Only apply pullback visual if actively aiming (dragging)
  2161.     float powerOffset = 0.0f;
  2162.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2163.         powerOffset = shotPower * 5.0f; // Pull back based on power
  2164.     }
  2165.  
  2166.     D2D1_POINT_2F cueStickEnd = { cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset) };
  2167.     // Tip starts closer when not pulled back, further when pulled back
  2168.     D2D1_POINT_2F cueStickTip = { cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f) }; // Start tip slightly away from ball center
  2169.  
  2170.  
  2171.     // Draw Cue Stick (simple line) - Always draw if in correct state
  2172.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, 4.0f); // Thickness 4
  2173.  
  2174.  
  2175.     // --- Projection Lines ---
  2176.     float projectionLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure line is long enough
  2177.     D2D1_POINT_2F aimEndPoint = { cueBall->x + cosf(cueAngle) * projectionLength, cueBall->y + sinf(cueAngle) * projectionLength };
  2178.  
  2179.     // Find the first ball hit by the aiming line (logic remains the same)
  2180.     Ball* hitBall = nullptr;
  2181.     float minDistSq = -1.0f;
  2182.     D2D1_POINT_2F collisionPoint = { 0, 0 };
  2183.  
  2184.     for (size_t i = 0; i < balls.size(); ++i) {
  2185.         Ball& b = balls[i];
  2186.         if (b.id == 0 || b.isPocketed) continue; // Skip cue ball and pocketed balls
  2187.  
  2188.         float dx = b.x - cueBall->x;
  2189.         float dy = b.y - cueBall->y;
  2190.         float dot = dx * cosf(cueAngle) + dy * sinf(cueAngle);
  2191.  
  2192.         if (dot > 0) {
  2193.             float closestPointX = cueBall->x + dot * cosf(cueAngle);
  2194.             float closestPointY = cueBall->y + dot * sinf(cueAngle);
  2195.             float distSq = GetDistanceSq(b.x, b.y, closestPointX, closestPointY);
  2196.             float combinedRadiusSq = (BALL_RADIUS + BALL_RADIUS) * (BALL_RADIUS + BALL_RADIUS); // Check against combined radius
  2197.  
  2198.             // More accurate check: does the line segment from cue ball intersect ball radius?
  2199.             // And is the distance along the line less than current min hit distance?
  2200.             if (distSq < BALL_RADIUS * BALL_RADIUS) { // Aim line passes *through* the ball radius zone
  2201.                // Distance from cue ball center to the point on aim line closest to target ball center
  2202.                 float distToClosestPointOnLine = dot;
  2203.                 // Distance from target ball center to that closest point
  2204.                 float distFromTargetCenterToLine = sqrtf(distSq);
  2205.                 // Distance along aim line from closest point back to collision point on cue path circumference
  2206.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq)); // Clamp to 0
  2207.                 float collisionDist = distToClosestPointOnLine - backDist; // Distance from cue ball center to collision point
  2208.  
  2209.                 if (collisionDist > 0 && (hitBall == nullptr || collisionDist * collisionDist < minDistSq)) {
  2210.                     minDistSq = collisionDist * collisionDist;
  2211.                     hitBall = &b;
  2212.                     // The actual collision point (where cue surface hits target surface) is slightly further
  2213.                     collisionPoint = { cueBall->x + collisionDist * cosf(cueAngle), cueBall->y + collisionDist * sinf(cueAngle) };
  2214.                 }
  2215.             }
  2216.         }
  2217.     }
  2218.  
  2219.  
  2220.     // Draw Aiming Line (dashed up to the first hit ball or full length)
  2221.     D2D1_POINT_2F lineEnd = hitBall ? collisionPoint : aimEndPoint;
  2222.     // Use dashed style if available, otherwise solid
  2223.     pRT->DrawLine(D2D1::Point2F(cueBall->x, cueBall->y), lineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2224.  
  2225.     // Draw Target Circle at end of line
  2226.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(lineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  2227.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  2228.  
  2229.     // If a ball is hit, draw projection lines
  2230.     if (hitBall) {
  2231.         // Draw Ghost Cue Ball at collision point
  2232.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(collisionPoint, BALL_RADIUS, BALL_RADIUS);
  2233.         // Use dashed style if available
  2234.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2235.  
  2236.         // Draw Target Ball Projection Line
  2237.         float hitAngle = atan2f(hitBall->y - collisionPoint.y, hitBall->x - collisionPoint.x);
  2238.         D2D1_POINT_2F targetStartPoint = { hitBall->x, hitBall->y }; // Start from ball center
  2239.         // Extend line from collision point through ball center? No, from ball center along hitAngle.
  2240.         D2D1_POINT_2F targetProjectionEnd = { hitBall->x + cosf(hitAngle) * 50.0f, hitBall->y + sinf(hitAngle) * 50.0f }; // Short projection line
  2241.         // Use solid line for projection
  2242.         pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  2243.  
  2244.         // Optional: Draw Cue Ball Projection Line (after collision) - requires physics model
  2245.     }
  2246.  
  2247.     // Release resources
  2248.     SafeRelease(&pBrush);
  2249.     SafeRelease(&pGhostBrush);
  2250.     SafeRelease(&pCueBrush);
  2251.     SafeRelease(&pDashedStyle);
  2252. }
  2253.  
  2254.  
  2255. void DrawUI(ID2D1RenderTarget* pRT) {
  2256.     if (!pTextFormat || !pLargeTextFormat) return;
  2257.  
  2258.     ID2D1SolidColorBrush* pBrush = nullptr;
  2259.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  2260.     if (!pBrush) return;
  2261.  
  2262.     // Player Info Area (Top Left/Right)
  2263.     float uiTop = TABLE_TOP - 80;
  2264.     float uiHeight = 60;
  2265.     float p1Left = TABLE_LEFT;
  2266.     float p1Width = 150;
  2267.     float p2Left = TABLE_RIGHT - p1Width;
  2268.  
  2269.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  2270.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  2271.  
  2272.     // Player 1 Info
  2273.     std::wostringstream oss1;
  2274.     oss1 << player1Info.name.c_str() << L"\n";
  2275.     if (player1Info.assignedType != BallType::NONE) {
  2276.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2277.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  2278.     }
  2279.     else {
  2280.         oss1 << L"(Undecided)";
  2281.     }
  2282.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  2283.  
  2284.     // Player 2 Info
  2285.     std::wostringstream oss2;
  2286.     oss2 << player2Info.name.c_str() << L"\n";
  2287.     if (player2Info.assignedType != BallType::NONE) {
  2288.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2289.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  2290.     }
  2291.     else {
  2292.         oss2 << L"(Undecided)";
  2293.     }
  2294.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  2295.  
  2296.     // Current Turn Arrow (Blue)
  2297.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  2298.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  2299.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS) {
  2300.         float arrowX = (currentPlayer == 1) ? p1Rect.left + p1Width / 2.0f : p2Rect.left + p1Width / 2.0f;
  2301.         float arrowY = uiTop - 15; // Above the text box
  2302.         // Draw a simple triangle arrow
  2303.         ID2D1PathGeometry* pPath = nullptr;
  2304.         pFactory->CreatePathGeometry(&pPath);
  2305.         if (pPath) {
  2306.             ID2D1GeometrySink* pSink = nullptr;
  2307.             pPath->Open(&pSink);
  2308.             if (pSink) {
  2309.                 pSink->BeginFigure(D2D1::Point2F(arrowX, arrowY), D2D1_FIGURE_BEGIN_FILLED);
  2310.                 pSink->AddLine(D2D1::Point2F(arrowX - 8, arrowY - 12));
  2311.                 pSink->AddLine(D2D1::Point2F(arrowX + 8, arrowY - 12));
  2312.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  2313.                 pSink->Close();
  2314.                 SafeRelease(&pSink);
  2315.                 pRT->FillGeometry(pPath, pArrowBrush);
  2316.             }
  2317.             SafeRelease(&pPath);
  2318.         }
  2319.         SafeRelease(&pArrowBrush);
  2320.     }
  2321.  
  2322.  
  2323.     // Foul Text (Large Red)
  2324.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) { // Show foul until next shot starts
  2325.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  2326.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  2327.         if (pFoulBrush) {
  2328.             D2D1_RECT_F foulRect = D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS - 150, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_LEFT - CUSHION_THICKNESS - 10, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  2329.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  2330.             SafeRelease(&pFoulBrush);
  2331.         }
  2332.     }
  2333.  
  2334.     // --- NEW: Show AI Thinking State ---
  2335.     if (currentGameState == AI_THINKING && pTextFormat) {
  2336.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  2337.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  2338.         if (pThinkingBrush) {
  2339.             // Display somewhere noticeable, maybe near Player 2's info box?
  2340.             D2D1_RECT_F thinkingRect = p2Rect; // Reuse P2 rect area
  2341.             thinkingRect.top += 20; // Move down slightly within the box
  2342.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  2343.             SafeRelease(&pThinkingBrush);
  2344.         }
  2345.     }
  2346.  
  2347.     SafeRelease(&pBrush);
  2348. }
  2349.  
  2350. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  2351.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  2352.     ID2D1SolidColorBrush* pFillBrush = nullptr;
  2353.  
  2354.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  2355.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LimeGreen), &pFillBrush);
  2356.  
  2357.     if (!pBorderBrush || !pFillBrush) {
  2358.         SafeRelease(&pBorderBrush);
  2359.         SafeRelease(&pFillBrush);
  2360.         return;
  2361.     }
  2362.  
  2363.     // Draw Border
  2364.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 1.0f);
  2365.  
  2366.     // Calculate Fill Height
  2367.     float fillRatio = 0;
  2368.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2369.         fillRatio = shotPower / MAX_SHOT_POWER;
  2370.     }
  2371.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  2372.     D2D1_RECT_F fillRect = D2D1::RectF(
  2373.         powerMeterRect.left, powerMeterRect.bottom - fillHeight,
  2374.         powerMeterRect.right, powerMeterRect.bottom
  2375.     );
  2376.  
  2377.     // Draw Fill
  2378.     pRT->FillRectangle(&fillRect, pFillBrush);
  2379.  
  2380.     SafeRelease(&pBorderBrush);
  2381.     SafeRelease(&pFillBrush);
  2382. }
  2383.  
  2384. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  2385.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  2386.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  2387.  
  2388.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  2389.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  2390.  
  2391.     if (!pWhiteBrush || !pRedBrush) {
  2392.         SafeRelease(&pWhiteBrush);
  2393.         SafeRelease(&pRedBrush);
  2394.         return;
  2395.     }
  2396.  
  2397.     // Draw White Ball Background
  2398.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  2399.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  2400.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  2401.  
  2402.  
  2403.     // Draw Red Dot for Spin Position
  2404.     float dotRadius = 4.0f;
  2405.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  2406.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  2407.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  2408.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  2409.  
  2410.     SafeRelease(&pWhiteBrush);
  2411.     SafeRelease(&pRedBrush);
  2412. }
  2413.  
  2414.  
  2415. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  2416.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  2417.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  2418.  
  2419.     // Ensure render target is valid before proceeding
  2420.     if (!pRT) return;
  2421.  
  2422.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  2423.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  2424.  
  2425.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  2426.     if (FAILED(hr)) {
  2427.         SafeRelease(&pBgBrush);
  2428.         SafeRelease(&pBallBrush);
  2429.         return; // Exit if brush creation fails
  2430.     }
  2431.  
  2432.     // Draw the background bar (rounded rect)
  2433.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  2434.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  2435.  
  2436.     // --- Draw small circles for pocketed balls inside the bar ---
  2437.  
  2438.     // Calculate dimensions based on the bar's height for better scaling
  2439.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  2440.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  2441.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  2442.     float padding = spacing * 0.75f; // Add padding from the edges
  2443.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  2444.  
  2445.     // Starting X positions with padding
  2446.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  2447.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  2448.  
  2449.     int p1DrawnCount = 0;
  2450.     int p2DrawnCount = 0;
  2451.     const int maxBallsToShow = 7; // Max balls per player in the bar
  2452.  
  2453.     for (const auto& b : balls) {
  2454.         if (b.isPocketed) {
  2455.             // Skip cue ball and 8-ball in this indicator
  2456.             if (b.id == 0 || b.id == 8) continue;
  2457.  
  2458.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  2459.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  2460.  
  2461.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  2462.                 pBallBrush->SetColor(b.color);
  2463.                 // Draw P1 balls from left to right
  2464.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2465.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2466.                 p1DrawnCount++;
  2467.             }
  2468.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  2469.                 pBallBrush->SetColor(b.color);
  2470.                 // Draw P2 balls from right to left
  2471.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2472.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2473.                 p2DrawnCount++;
  2474.             }
  2475.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  2476.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  2477.         }
  2478.     }
  2479.  
  2480.     SafeRelease(&pBgBrush);
  2481.     SafeRelease(&pBallBrush);
  2482. }
  2483.  
  2484. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  2485.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  2486.         return; // Only show when placing/dragging
  2487.     }
  2488.  
  2489.     Ball* cueBall = GetCueBall();
  2490.     if (!cueBall) return;
  2491.  
  2492.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2493.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  2494.  
  2495.     if (pGhostBrush) {
  2496.         D2D1_POINT_2F drawPos;
  2497.         if (isDraggingCueBall) {
  2498.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2499.         }
  2500.         else {
  2501.             // If not dragging but in placement state, show at current ball pos
  2502.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  2503.         }
  2504.  
  2505.         // Check if the placement is valid before drawing differently?
  2506.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2507.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  2508.  
  2509.         if (!isValid) {
  2510.             // Maybe draw red outline if invalid placement?
  2511.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  2512.         }
  2513.  
  2514.  
  2515.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  2516.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  2517.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  2518.  
  2519.         SafeRelease(&pGhostBrush);
  2520.     }
  2521. }
  2522. ```
  2523.  
  2524. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  2525. ```resource.h
  2526. //{{NO_DEPENDENCIES}}
  2527. // Microsoft Visual C++ generated include file.
  2528. // Used by Yahoo-8Ball-Pool-Clone.rc
  2529. //
  2530. #define IDI_ICON1                       101
  2531. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  2532. #define IDD_NEWGAMEDLG 106
  2533. #define IDC_RADIO_2P   1003
  2534. #define IDC_RADIO_CPU  1005
  2535. #define IDC_GROUP_AI   1006
  2536. #define IDC_RADIO_EASY 1007
  2537. #define IDC_RADIO_MEDIUM 1008
  2538. #define IDC_RADIO_HARD 1009
  2539. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  2540.  
  2541. // Next default values for new objects
  2542. //
  2543. #ifdef APSTUDIO_INVOKED
  2544. #ifndef APSTUDIO_READONLY_SYMBOLS
  2545. #define _APS_NEXT_RESOURCE_VALUE        102
  2546. #define _APS_NEXT_COMMAND_VALUE         40001
  2547. #define _APS_NEXT_CONTROL_VALUE         1001
  2548. #define _APS_NEXT_SYMED_VALUE           101
  2549. #endif
  2550. #endif
  2551.  
  2552. ```
  2553.  
  2554. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  2555. ```Yahoo-8Ball-Pool-Clone.rc
  2556. // Microsoft Visual C++ generated resource script.
  2557. //
  2558. #include "resource.h"
  2559.  
  2560. #define APSTUDIO_READONLY_SYMBOLS
  2561. /////////////////////////////////////////////////////////////////////////////
  2562. //
  2563. // Generated from the TEXTINCLUDE 2 resource.
  2564. //
  2565. #include "winres.h"
  2566.  
  2567. /////////////////////////////////////////////////////////////////////////////
  2568. #undef APSTUDIO_READONLY_SYMBOLS
  2569.  
  2570. /////////////////////////////////////////////////////////////////////////////
  2571. // English (United States) resources
  2572.  
  2573. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  2574. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  2575. #pragma code_page(1252)
  2576.  
  2577. #ifdef APSTUDIO_INVOKED
  2578. /////////////////////////////////////////////////////////////////////////////
  2579. //
  2580. // TEXTINCLUDE
  2581. //
  2582.  
  2583. 1 TEXTINCLUDE
  2584. BEGIN
  2585.     "resource.h\0"
  2586. END
  2587.  
  2588. 2 TEXTINCLUDE
  2589. BEGIN
  2590.     "#include ""winres.h""\r\n"
  2591.     "\0"
  2592. END
  2593.  
  2594. 3 TEXTINCLUDE
  2595. BEGIN
  2596.     "\r\n"
  2597.     "\0"
  2598. END
  2599.  
  2600. #endif    // APSTUDIO_INVOKED
  2601.  
  2602.  
  2603. /////////////////////////////////////////////////////////////////////////////
  2604. //
  2605. // Icon
  2606. //
  2607.  
  2608. // Icon with lowest ID value placed first to ensure application icon
  2609. // remains consistent on all systems.
  2610. IDI_ICON1               ICON                    "D:\\Download\\cpp-projekt\\FuzenOp_SiloTest\\icons\\shell32_277.ico"
  2611.  
  2612. #endif    // English (United States) resources
  2613. /////////////////////////////////////////////////////////////////////////////
  2614.  
  2615.  
  2616.  
  2617. #ifndef APSTUDIO_INVOKED
  2618. /////////////////////////////////////////////////////////////////////////////
  2619. //
  2620. // Generated from the TEXTINCLUDE 3 resource.
  2621. //
  2622.  
  2623.  
  2624. /////////////////////////////////////////////////////////////////////////////
  2625. #endif    // not APSTUDIO_INVOKED
  2626.  
  2627. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  2628.  
  2629. /////////////////////////////////////////////////////////////////////////////
  2630. //
  2631. // Dialog
  2632. //
  2633.  
  2634. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 130 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs)
  2635. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  2636. CAPTION "New 8-Ball Game"
  2637. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  2638. BEGIN
  2639. // --- Game Mode Selection ---
  2640. // Group Box for Game Mode (Optional visually, but helps structure)
  2641. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  2642.  
  2643. // "2 Player" Radio Button (First in this group)
  2644. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  2645. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  2646.  
  2647. // "Human vs CPU" Radio Button
  2648. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  2649. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  2650.  
  2651.  
  2652. // --- AI Difficulty Selection (Inside its own Group Box) ---
  2653. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  2654.  
  2655. // "Easy" Radio Button (First in the AI group)
  2656. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  2657. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  2658.  
  2659. // "Medium" Radio Button
  2660. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  2661. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  2662.  
  2663. // "Hard" Radio Button
  2664. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  2665. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  2666.  
  2667.  
  2668. // --- Standard Buttons ---
  2669. DEFPUSHBUTTON   "Start", IDOK, 55, 105, 50, 14 // Default button (Enter key)
  2670. PUSHBUTTON      "Cancel", IDCANCEL, 115, 105, 50, 14
  2671. END
  2672. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement