Advertisement
alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: AimTrajectory For TableRails+HardAngles TipShots Inaccurate V4

Apr 25th, 2025 (edited)
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 118.04 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.         // Logic for dragging cue ball during ball-in-hand (unchanged)
  478.         if (isDraggingCueBall && (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)) {
  479.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  480.             if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  481.                 cueBall->x = (float)ptMouse.x;
  482.                 cueBall->y = (float)ptMouse.y;
  483.                 cueBall->vx = cueBall->vy = 0; // Ensure it's stopped
  484.             }
  485.         }
  486.         // Logic for aiming drag (unchanged math, just context)
  487.         else if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  488.             float dx = (float)ptMouse.x - cueBall->x;
  489.             float dy = (float)ptMouse.y - cueBall->y;
  490.             // Prevent setting angle if mouse is exactly on cue ball center
  491.             if (dx != 0 || dy != 0) {
  492.                 cueAngle = atan2f(dy, dx);
  493.             }
  494.             // Calculate power based on distance pulled back from the initial click point (aimStartPoint)
  495.             float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  496.             // Scale power more aggressively, maybe? Or keep scale factor 10.0
  497.             shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER); // Scale power, clamp to max
  498.         }
  499.         // Logic for setting english (unchanged)
  500.         else if (isSettingEnglish) {
  501.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  502.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  503.             float dist = GetDistance(dx, dy, 0, 0);
  504.             if (dist > spinIndicatorRadius) { // Clamp to edge
  505.                 dx *= spinIndicatorRadius / dist;
  506.                 dy *= spinIndicatorRadius / dist;
  507.             }
  508.             cueSpinX = dx / spinIndicatorRadius; // Normalize to -1 to 1
  509.             cueSpinY = dy / spinIndicatorRadius;
  510.         }
  511.         // InvalidateRect is handled by WM_TIMER
  512.         return 0;
  513.     }
  514.  
  515.     case WM_LBUTTONDOWN: {
  516.         ptMouse.x = LOWORD(lParam);
  517.         ptMouse.y = HIWORD(lParam);
  518.  
  519.         // Check if clicking on Spin Indicator (unchanged)
  520.         float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  521.         if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius) {
  522.             isSettingEnglish = true;
  523.             // Update spin immediately on click
  524.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  525.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  526.             cueSpinX = dx / spinIndicatorRadius;
  527.             cueSpinY = dy / spinIndicatorRadius;
  528.             return 0; // Don't process other clicks if setting english
  529.         }
  530.  
  531.  
  532.         Ball* cueBall = GetCueBall();
  533.         if (!cueBall) return 0;
  534.  
  535.         // Logic for Ball-in-Hand placement click (unchanged)
  536.         if (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT) {
  537.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  538.             if (distSq < BALL_RADIUS * BALL_RADIUS * 4) { // Allow clicking near the ball to start drag
  539.                 isDraggingCueBall = true;
  540.             }
  541.             else { // If clicking elsewhere on the table (and valid), place the ball
  542.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  543.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  544.                     cueBall->x = (float)ptMouse.x;
  545.                     cueBall->y = (float)ptMouse.y;
  546.                     cueBall->vx = cueBall->vy = 0;
  547.                     isDraggingCueBall = false;
  548.                     // Transition state appropriate to ending placement
  549.                     if (currentGameState == PRE_BREAK_PLACEMENT) {
  550.                         // Depends on who is breaking
  551.                         currentGameState = BREAKING;
  552.                         // If AI was breaking, aiTurnPending should still be true
  553.                     }
  554.                     else if (currentGameState == BALL_IN_HAND_P1) {
  555.                         currentGameState = PLAYER1_TURN;
  556.                     }
  557.                     else if (currentGameState == BALL_IN_HAND_P2) {
  558.                         // If AI placed ball, AIMakeDecision should have been called? Or trigger now?
  559.                         // Assuming SwitchTurns/Respawn set aiTurnPending correctly earlier
  560.                         currentGameState = PLAYER2_TURN; // Ready for AI/Human P2 to aim
  561.                     }
  562.                 }
  563.             }
  564.         }
  565.         // --- MODIFIED: Logic for starting aim ---
  566.         else if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  567.             // Allow initiating aim by clicking in a larger radius around the cue ball
  568.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  569.             // Increased radius check (e.g., 5x ball radius squared)
  570.             if (distSq < BALL_RADIUS * BALL_RADIUS * 25) { // Click somewhat close to cue ball
  571.                 isAiming = true;
  572.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Store where aiming drag started
  573.                 shotPower = 0; // Reset power
  574.                 // Transition to AIMING state (if not already BREAKING)
  575.                 if (currentGameState != BREAKING) {
  576.                     currentGameState = AIMING;
  577.                 }
  578.                 // Set initial cueAngle based on click relative to ball, for immediate feedback
  579.                 float dx = (float)ptMouse.x - cueBall->x;
  580.                 float dy = (float)ptMouse.y - cueBall->y;
  581.                 if (dx != 0 || dy != 0) {
  582.                     cueAngle = atan2f(dy, dx);
  583.                     // If starting aim by clicking, maybe point stick towards mouse initially?
  584.                     // Current logic updates angle on MOUSEMOVE anyway.
  585.                 }
  586.             }
  587.         }
  588.         return 0;
  589.     }
  590.  
  591.     case WM_LBUTTONUP: {
  592.         ptMouse.x = LOWORD(lParam);
  593.         ptMouse.y = HIWORD(lParam);
  594.  
  595.         if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  596.             isAiming = false; // Stop the aiming drag visual state
  597.  
  598.             // --- MODIFIED: Increased threshold for taking shot ---
  599.             if (shotPower > 0.15f) { // Only shoot if power is significant enough
  600.                 // Prevent player from shooting if it's AI's turn calculation phase
  601.                 if (currentGameState != AI_THINKING) {
  602.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  603.                     currentGameState = SHOT_IN_PROGRESS;
  604.                     foulCommitted = false; // Reset foul flag for the new shot
  605.                     pocketedThisTurn.clear();
  606.                 }
  607.             }
  608.             // If shotPower is too low, reset state back to player's turn
  609.             else if (currentGameState != AI_THINKING) {
  610.                 // If no power, revert state back without shooting
  611.                 if (currentGameState == BREAKING) {
  612.                     // Still breaking state if power was too low
  613.                 }
  614.                 else {
  615.                     // Revert to appropriate player turn state
  616.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  617.                     // Clear pending AI turn flag if it somehow got set during a zero-power human shot attempt
  618.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  619.                 }
  620.             }
  621.             shotPower = 0; // Reset power indicator regardless of shot taken
  622.         }
  623.  
  624.         // Logic for releasing cue ball after dragging (unchanged)
  625.         if (isDraggingCueBall) {
  626.             isDraggingCueBall = false;
  627.             // After placing the ball, transition state if needed (state might already be set by click placement)
  628.             if (currentGameState == PRE_BREAK_PLACEMENT) {
  629.                 currentGameState = BREAKING;
  630.             }
  631.             else if (currentGameState == BALL_IN_HAND_P1) {
  632.                 currentGameState = PLAYER1_TURN;
  633.             }
  634.             else if (currentGameState == BALL_IN_HAND_P2) {
  635.                 currentGameState = PLAYER2_TURN;
  636.                 // If AI placed, aiTurnPending should trigger AI on next GameUpdate
  637.             }
  638.         }
  639.         // Logic for releasing english setting (unchanged)
  640.         if (isSettingEnglish) {
  641.             isSettingEnglish = false;
  642.         }
  643.         return 0;
  644.     }
  645.  
  646.     case WM_DESTROY:
  647.         PostQuitMessage(0);
  648.         return 0;
  649.  
  650.     default:
  651.         return DefWindowProc(hwnd, msg, wParam, lParam);
  652.     }
  653.     return 0;
  654. }
  655.  
  656. // --- Direct2D Resource Management ---
  657.  
  658. HRESULT CreateDeviceResources() {
  659.     HRESULT hr = S_OK;
  660.  
  661.     // Create Direct2D Factory
  662.     if (!pFactory) {
  663.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  664.         if (FAILED(hr)) return hr;
  665.     }
  666.  
  667.     // Create DirectWrite Factory
  668.     if (!pDWriteFactory) {
  669.         hr = DWriteCreateFactory(
  670.             DWRITE_FACTORY_TYPE_SHARED,
  671.             __uuidof(IDWriteFactory),
  672.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  673.         );
  674.         if (FAILED(hr)) return hr;
  675.     }
  676.  
  677.     // Create Text Formats
  678.     if (!pTextFormat && pDWriteFactory) {
  679.         hr = pDWriteFactory->CreateTextFormat(
  680.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  681.             16.0f, L"en-us", &pTextFormat
  682.         );
  683.         if (FAILED(hr)) return hr;
  684.         // Center align text
  685.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  686.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  687.     }
  688.     if (!pLargeTextFormat && pDWriteFactory) {
  689.         hr = pDWriteFactory->CreateTextFormat(
  690.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  691.             48.0f, L"en-us", &pLargeTextFormat
  692.         );
  693.         if (FAILED(hr)) return hr;
  694.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  695.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  696.     }
  697.  
  698.  
  699.     // Create Render Target (needs valid hwnd)
  700.     if (!pRenderTarget && hwndMain) {
  701.         RECT rc;
  702.         GetClientRect(hwndMain, &rc);
  703.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  704.  
  705.         hr = pFactory->CreateHwndRenderTarget(
  706.             D2D1::RenderTargetProperties(),
  707.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  708.             &pRenderTarget
  709.         );
  710.         if (FAILED(hr)) {
  711.             // If failed, release factories if they were created in this call
  712.             SafeRelease(&pTextFormat);
  713.             SafeRelease(&pLargeTextFormat);
  714.             SafeRelease(&pDWriteFactory);
  715.             SafeRelease(&pFactory);
  716.             pRenderTarget = nullptr; // Ensure it's null on failure
  717.             return hr;
  718.         }
  719.     }
  720.  
  721.     return hr;
  722. }
  723.  
  724. void DiscardDeviceResources() {
  725.     SafeRelease(&pRenderTarget);
  726.     SafeRelease(&pTextFormat);
  727.     SafeRelease(&pLargeTextFormat);
  728.     SafeRelease(&pDWriteFactory);
  729.     // Keep pFactory until application exit? Or release here too? Let's release.
  730.     SafeRelease(&pFactory);
  731. }
  732.  
  733. void OnResize(UINT width, UINT height) {
  734.     if (pRenderTarget) {
  735.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  736.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  737.     }
  738. }
  739.  
  740. // --- Game Initialization ---
  741. void InitGame() {
  742.     srand((unsigned int)time(NULL)); // Seed random number generator
  743.  
  744.     // --- Ensure pocketed list is clear from the absolute start ---
  745.     pocketedThisTurn.clear();
  746.  
  747.     balls.clear(); // Clear existing balls
  748.  
  749.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  750.     player1Info.assignedType = BallType::NONE;
  751.     player1Info.ballsPocketedCount = 0;
  752.     // Player 1 Name usually remains "Player 1"
  753.     player2Info.assignedType = BallType::NONE;
  754.     player2Info.ballsPocketedCount = 0;
  755.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  756.  
  757.     // Create Cue Ball (ID 0)
  758.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  759.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  760.  
  761.     // --- Create Object Balls (Temporary List) ---
  762.     std::vector<Ball> objectBalls;
  763.     // Solids (1-7, Yellow)
  764.     for (int i = 1; i <= 7; ++i) {
  765.         objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  766.     }
  767.     // Stripes (9-15, Red)
  768.     for (int i = 9; i <= 15; ++i) {
  769.         objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  770.     }
  771.     // 8-Ball (ID 8) - Add it to the list to be placed
  772.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  773.  
  774.  
  775.     // --- Racking Logic (Improved) ---
  776.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  777.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  778.  
  779.     // Define rack positions (0-14 indices corresponding to triangle spots)
  780.     D2D1_POINT_2F rackPositions[15];
  781.     int rackIndex = 0;
  782.     for (int row = 0; row < 5; ++row) {
  783.         for (int col = 0; col <= row; ++col) {
  784.             if (rackIndex >= 15) break;
  785.             float x = RACK_POS_X + row * spacingX;
  786.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  787.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  788.         }
  789.     }
  790.  
  791.     // Separate 8-ball
  792.     Ball eightBall;
  793.     std::vector<Ball> otherBalls; // Solids and Stripes
  794.     bool eightBallFound = false;
  795.     for (const auto& ball : objectBalls) {
  796.         if (ball.id == 8) {
  797.             eightBall = ball;
  798.             eightBallFound = true;
  799.         }
  800.         else {
  801.             otherBalls.push_back(ball);
  802.         }
  803.     }
  804.     // Ensure 8 ball was actually created (should always be true)
  805.     if (!eightBallFound) {
  806.         // Handle error - perhaps recreate it? For now, proceed.
  807.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  808.     }
  809.  
  810.  
  811.     // Shuffle the other 14 balls
  812.     // Use std::shuffle if available (C++11 and later) for better randomness
  813.     // std::random_device rd;
  814.     // std::mt19937 g(rd());
  815.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  816.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  817.  
  818.     // --- Place balls into the main 'balls' vector in rack order ---
  819.     // Important: Add the cue ball (already created) first.
  820.     // (Cue ball added at the start of the function now)
  821.  
  822.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  823.     int eightBallRackIndex = 4;
  824.     eightBall.x = rackPositions[eightBallRackIndex].x;
  825.     eightBall.y = rackPositions[eightBallRackIndex].y;
  826.     eightBall.vx = 0;
  827.     eightBall.vy = 0;
  828.     eightBall.isPocketed = false;
  829.     balls.push_back(eightBall); // Add 8 ball to the main vector
  830.  
  831.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  832.     int otherBallIdx = 0;
  833.     for (int i = 0; i < 15; ++i) {
  834.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  835.  
  836.         if (otherBallIdx < otherBalls.size()) {
  837.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  838.             ballToPlace.x = rackPositions[i].x;
  839.             ballToPlace.y = rackPositions[i].y;
  840.             ballToPlace.vx = 0;
  841.             ballToPlace.vy = 0;
  842.             ballToPlace.isPocketed = false;
  843.             balls.push_back(ballToPlace); // Add to the main game vector
  844.         }
  845.     }
  846.     // --- End Racking Logic ---
  847.  
  848.  
  849.     // --- Determine Who Breaks and Initial State ---
  850.     if (isPlayer2AI) {
  851.         // AI Mode: Randomly decide who breaks
  852.         if ((rand() % 2) == 0) {
  853.             // AI (Player 2) breaks
  854.             currentPlayer = 2;
  855.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  856.             aiTurnPending = true; // Trigger AI logic
  857.         }
  858.         else {
  859.             // Player 1 (Human) breaks
  860.             currentPlayer = 1;
  861.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  862.             aiTurnPending = false;
  863.         }
  864.     }
  865.     else {
  866.         // Human vs Human, Player 1 breaks
  867.         currentPlayer = 1;
  868.         currentGameState = PRE_BREAK_PLACEMENT;
  869.         aiTurnPending = false; // No AI involved
  870.     }
  871.  
  872.     // Reset other relevant game state variables
  873.     foulCommitted = false;
  874.     gameOverMessage = L"";
  875.     firstBallPocketedAfterBreak = false;
  876.     // pocketedThisTurn cleared at start
  877.     // Reset shot parameters and input flags
  878.     shotPower = 0.0f;
  879.     cueSpinX = 0.0f;
  880.     cueSpinY = 0.0f;
  881.     isAiming = false;
  882.     isDraggingCueBall = false;
  883.     isSettingEnglish = false;
  884.     cueAngle = 0.0f; // Reset aim angle
  885. }
  886.  
  887.  
  888. // --- Game Loop ---
  889. void GameUpdate() {
  890.     if (currentGameState == SHOT_IN_PROGRESS) {
  891.         UpdatePhysics();
  892.         CheckCollisions();
  893.         bool pocketed = CheckPockets(); // Store if any ball was pocketed
  894.  
  895.         if (!AreBallsMoving()) {
  896.             ProcessShotResults(); // Determine next state based on what happened
  897.         }
  898.     }
  899.  
  900.     // --- NEW: Check if AI needs to act ---
  901.     else if (aiTurnPending && !AreBallsMoving()) {
  902.         // Check if it's genuinely AI's turn state and not mid-shot etc.
  903.         if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING || currentGameState == PRE_BREAK_PLACEMENT) {
  904.             // Only trigger if AI is P2, it's their turn/break, and balls stopped
  905.             if (isPlayer2AI && currentPlayer == 2) {
  906.                 // Transition state to show AI is thinking
  907.                 currentGameState = AI_THINKING;
  908.                 aiTurnPending = false; // Acknowledge the pending flag
  909.  
  910.                 // --- Trigger AI Decision Making ---
  911.                 // In a real game loop, you might start a timer here or background thread.
  912.                 // For simplicity here, we call it directly. This might pause rendering
  913.                 // briefly if AI calculation is slow.
  914.                 AIMakeDecision(); // AI calculates and applies shot
  915.  
  916.                 // AIMakeDecision should end by calling ApplyShot, which sets
  917.                 // currentGameState = SHOT_IN_PROGRESS
  918.                 // If AI fails to find a shot, need to handle that (e.g., pass turn - should be rare)
  919.             }
  920.             else {
  921.                 aiTurnPending = false; // Clear flag if conditions not met (e.g. P1's turn somehow)
  922.             }
  923.         }
  924.         else {
  925.             aiTurnPending = false; // Clear flag if not in a state where AI should shoot
  926.         }
  927.     }
  928.  
  929.     // Other states (AIMING, BALL_IN_HAND, etc.) are handled by input messages
  930. }
  931.  
  932. // --- Physics and Collision ---
  933. void UpdatePhysics() {
  934.     for (size_t i = 0; i < balls.size(); ++i) {
  935.         Ball& b = balls[i];
  936.         if (!b.isPocketed) {
  937.             b.x += b.vx;
  938.             b.y += b.vy;
  939.  
  940.             // Apply friction
  941.             b.vx *= FRICTION;
  942.             b.vy *= FRICTION;
  943.  
  944.             // Stop balls if velocity is very low
  945.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  946.                 b.vx = 0;
  947.                 b.vy = 0;
  948.             }
  949.         }
  950.     }
  951. }
  952.  
  953. void CheckCollisions() {
  954.     // --- Corrected Collision Boundaries ---
  955.     // These now represent the actual edges of the playable table surface
  956.     float left = TABLE_LEFT;
  957.     float right = TABLE_RIGHT;
  958.     float top = TABLE_TOP;
  959.     float bottom = TABLE_BOTTOM;
  960.  
  961.     // Define a radius around pocket centers to check if a ball is near a pocket mouth
  962.     // Use a value slightly larger than the pocket radius to prevent clipping the edge
  963.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f; // Check slightly larger area
  964.  
  965.     for (size_t i = 0; i < balls.size(); ++i) {
  966.         Ball& b1 = balls[i];
  967.         if (b1.isPocketed) continue; // Skip balls already pocketed
  968.  
  969.         // --- Pre-calculate proximity to pocket centers ---
  970.         // This avoids recalculating distances multiple times for wall checks
  971.         bool nearPocket[6];
  972.         for (int p = 0; p < 6; ++p) {
  973.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  974.         }
  975.         // Individual pocket proximity flags for clarity in wall checks
  976.         bool nearTopLeftPocket = nearPocket[0];
  977.         bool nearTopMidPocket = nearPocket[1];
  978.         bool nearTopRightPocket = nearPocket[2];
  979.         bool nearBottomLeftPocket = nearPocket[3];
  980.         bool nearBottomMidPocket = nearPocket[4];
  981.         bool nearBottomRightPocket = nearPocket[5];
  982.  
  983.  
  984.         // --- Ball-Wall Collisions (with Pocket Avoidance) ---
  985.         bool collidedWall = false; // Track if any wall collision happened for spin effects
  986.  
  987.         // Left Wall
  988.         if (b1.x - BALL_RADIUS < left) {
  989.             // Don't bounce if near top-left or bottom-left pocket mouths
  990.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  991.                 b1.x = left + BALL_RADIUS;
  992.                 b1.vx *= -1.0f;
  993.                 collidedWall = true;
  994.             } // else: Allow ball to continue towards pocket
  995.         }
  996.         // Right Wall
  997.         if (b1.x + BALL_RADIUS > right) {
  998.             // Don't bounce if near top-right or bottom-right pocket mouths
  999.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1000.                 b1.x = right - BALL_RADIUS;
  1001.                 b1.vx *= -1.0f;
  1002.                 collidedWall = true;
  1003.             } // else: Allow ball to continue towards pocket
  1004.         }
  1005.         // Top Wall
  1006.         if (b1.y - BALL_RADIUS < top) {
  1007.             // Don't bounce if near top-left, top-mid, or top-right pocket mouths
  1008.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1009.                 b1.y = top + BALL_RADIUS;
  1010.                 b1.vy *= -1.0f;
  1011.                 collidedWall = true;
  1012.             } // else: Allow ball to continue towards pocket
  1013.         }
  1014.         // Bottom Wall
  1015.         if (b1.y + BALL_RADIUS > bottom) {
  1016.             // Don't bounce if near bottom-left, bottom-mid, or bottom-right pocket mouths
  1017.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1018.                 b1.y = bottom - BALL_RADIUS;
  1019.                 b1.vy *= -1.0f;
  1020.                 collidedWall = true;
  1021.             } // else: Allow ball to continue towards pocket
  1022.         }
  1023.  
  1024.         // Optional: Apply simplified spin effect on wall collision IF a bounce occurred
  1025.         if (collidedWall) {
  1026.             // Simple spin damping/effect (can be refined)
  1027.             // Side spin affects vertical velocity on horizontal collision & vice-versa
  1028.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { // Hit L/R wall
  1029.                 b1.vy += cueSpinX * b1.vx * 0.05f; // Apply small vertical impulse based on side spin and horizontal velocity
  1030.             }
  1031.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { // Hit T/B wall
  1032.                 b1.vx -= cueSpinY * b1.vy * 0.05f; // Apply small horizontal impulse based on top/bottom spin and vertical velocity
  1033.             }
  1034.             // Dampen spin after wall hit
  1035.             cueSpinX *= 0.7f; // Increase damping maybe
  1036.             cueSpinY *= 0.7f;
  1037.         }
  1038.  
  1039.  
  1040.         // --- Ball-Ball Collisions ---
  1041.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1042.             Ball& b2 = balls[j];
  1043.             if (b2.isPocketed) continue; // Skip pocketed balls
  1044.  
  1045.             float dx = b2.x - b1.x;
  1046.             float dy = b2.y - b1.y;
  1047.             float distSq = dx * dx + dy * dy;
  1048.             float minDist = BALL_RADIUS * 2.0f;
  1049.  
  1050.             if (distSq > 0 && distSq < minDist * minDist) { // Check distance squared first
  1051.                 float dist = sqrtf(distSq);
  1052.                 float overlap = minDist - dist;
  1053.  
  1054.                 // Normalize collision vector
  1055.                 float nx = dx / dist;
  1056.                 float ny = dy / dist;
  1057.  
  1058.                 // Separate balls to prevent sticking
  1059.                 // Move each ball half the overlap distance along the collision normal
  1060.                 b1.x -= overlap * 0.5f * nx;
  1061.                 b1.y -= overlap * 0.5f * ny;
  1062.                 b2.x += overlap * 0.5f * nx;
  1063.                 b2.y += overlap * 0.5f * ny;
  1064.  
  1065.                 // Relative velocity
  1066.                 float rvx = b1.vx - b2.vx;
  1067.                 float rvy = b1.vy - b2.vy;
  1068.  
  1069.                 // Dot product of relative velocity and collision normal
  1070.                 // This represents the component of relative velocity along the collision line
  1071.                 float velAlongNormal = rvx * nx + rvy * ny;
  1072.  
  1073.                 // Only resolve collision if balls are moving towards each other (dot product > 0)
  1074.                 if (velAlongNormal > 0) {
  1075.                     // Calculate impulse scalar (simplified - assumes equal mass, perfect elasticity=1.0)
  1076.                    // For perfect elastic collision, the impulse magnitude needed is velAlongNormal.
  1077.                    // Each ball gets half the impulse if masses are equal, but since we apply to both in opposite directions along the normal,
  1078.                    // the change in velocity for each along the normal is 'velAlongNormal'.
  1079.                     float impulse = velAlongNormal; // Simplified impulse magnitude along normal
  1080.  
  1081.                     // Apply impulse to velocities along the collision normal
  1082.                     b1.vx -= impulse * nx;
  1083.                     b1.vy -= impulse * ny;
  1084.                     b2.vx += impulse * nx;
  1085.                     b2.vy += impulse * ny;
  1086.  
  1087.                     // Apply spin transfer/effect (Very simplified)
  1088.                     if (b1.id == 0 || b2.id == 0) { // If cue ball involved
  1089.                         float spinEffectFactor = 0.08f; // Reduced factor maybe
  1090.                         // Simple model: Apply a small velocity change perpendicular to the normal based on spin
  1091.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor; // Spin effect
  1092.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor; // Spin effect (check signs/logic)
  1093.  
  1094.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1095.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1096.  
  1097.                         // Dampen spin after transfer
  1098.                         cueSpinX *= 0.85f;
  1099.                         cueSpinY *= 0.85f;
  1100.                     }
  1101.                 }
  1102.             }
  1103.         } // End ball-ball collision loop
  1104.     } // End loop through balls
  1105. } // End CheckCollisions
  1106.  
  1107.  
  1108. bool CheckPockets() {
  1109.     bool ballPocketed = false;
  1110.     for (size_t i = 0; i < balls.size(); ++i) {
  1111.         Ball& b = balls[i];
  1112.         if (!b.isPocketed) {
  1113.             for (int p = 0; p < 6; ++p) {
  1114.                 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
  1115.                 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
  1116.                     b.isPocketed = true;
  1117.                     b.vx = b.vy = 0;
  1118.                     pocketedThisTurn.push_back(b.id); // Record pocketed ball ID
  1119.                     ballPocketed = true;
  1120.                     break; // No need to check other pockets for this ball
  1121.                 }
  1122.             }
  1123.         }
  1124.     }
  1125.     return ballPocketed;
  1126. }
  1127.  
  1128. bool AreBallsMoving() {
  1129.     for (size_t i = 0; i < balls.size(); ++i) {
  1130.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1131.             return true;
  1132.         }
  1133.     }
  1134.     return false;
  1135. }
  1136.  
  1137. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1138.     Ball* cueBall = GetCueBall();
  1139.     if (cueBall) {
  1140.         // Reset position to a default (AI/Human might move it)
  1141.         cueBall->x = HEADSTRING_X * 0.5f;
  1142.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1143.         cueBall->vx = 0;
  1144.         cueBall->vy = 0;
  1145.         cueBall->isPocketed = false;
  1146.  
  1147.         // Set state based on who gets ball-in-hand
  1148.         if (currentPlayer == 1) { // Player 1 caused foul, Player 2 gets ball-in-hand
  1149.             if (isPlayer2AI) {
  1150.                 // AI gets ball-in-hand. Set state and trigger AI.
  1151.                 currentGameState = PLAYER2_TURN; // State remains P2 Turn
  1152.                 aiTurnPending = true; // AI will handle placement in its logic
  1153.             }
  1154.             else {
  1155.                 // Human Player 2 gets ball-in-hand
  1156.                 currentGameState = BALL_IN_HAND_P2;
  1157.             }
  1158.         }
  1159.         else { // Player 2 caused foul, Player 1 gets ball-in-hand
  1160.             currentGameState = BALL_IN_HAND_P1;
  1161.             aiTurnPending = false; // Ensure AI flag off if P1 gets ball-in-hand
  1162.         }
  1163.     }
  1164. }
  1165.  
  1166.  
  1167. // --- Game Logic ---
  1168.  
  1169. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1170.     Ball* cueBall = GetCueBall();
  1171.     if (cueBall) {
  1172.         cueBall->vx = cosf(angle) * power;
  1173.         cueBall->vy = sinf(angle) * power;
  1174.  
  1175.         // Apply English (Spin) - Simplified effect
  1176.         // Top/Bottom spin affects initial roll slightly
  1177.         cueBall->vx += sinf(angle) * spinY * 0.5f; // Small effect perpendicular to shot dir
  1178.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1179.         // Side spin affects initial direction slightly
  1180.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1181.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1182.  
  1183.         // Store spin for later use in collisions/cushions (could decay over time too)
  1184.         cueSpinX = spinX;
  1185.         cueSpinY = spinY;
  1186.     }
  1187. }
  1188.  
  1189.  
  1190. void ProcessShotResults() {
  1191.     bool cueBallPocketed = false;
  1192.     bool eightBallPocketed = false;
  1193.     bool legalBallPocketed = false; // Player's own ball type
  1194.     bool opponentBallPocketed = false; // Opponent's ball type
  1195.     bool anyNonCueBallPocketed = false;
  1196.     BallType firstPocketedType = BallType::NONE; // Type of the first object ball pocketed
  1197.     int firstPocketedId = -1; // ID of the first object ball pocketed
  1198.  
  1199.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1200.     PlayerInfo& opponentPlayerInfo = (currentPlayer == 1) ? player2Info : player1Info;
  1201.  
  1202.     // Analyze pocketed balls from this shot sequence
  1203.     for (int pocketedId : pocketedThisTurn) {
  1204.         Ball* b = GetBallById(pocketedId);
  1205.         if (!b) continue; // Should not happen
  1206.  
  1207.         if (b->id == 0) {
  1208.             cueBallPocketed = true;
  1209.         }
  1210.         else if (b->id == 8) {
  1211.             eightBallPocketed = true;
  1212.         }
  1213.         else {
  1214.             anyNonCueBallPocketed = true;
  1215.             // Record the FIRST object ball pocketed in this turn
  1216.             if (firstPocketedId == -1) {
  1217.                 firstPocketedId = b->id;
  1218.                 firstPocketedType = b->type;
  1219.             }
  1220.  
  1221.             // Check if ball matches player's assigned type (if already assigned)
  1222.             if (currentPlayerInfo.assignedType != BallType::NONE) {
  1223.                 if (b->type == currentPlayerInfo.assignedType) {
  1224.                     legalBallPocketed = true;
  1225.                 }
  1226.                 else if (b->type == opponentPlayerInfo.assignedType) {
  1227.                     opponentBallPocketed = true; // Pocketed opponent's ball
  1228.                 }
  1229.             }
  1230.         }
  1231.     }
  1232.  
  1233.     // --- Game Over Checks --- (Unchanged)
  1234.     if (eightBallPocketed) {
  1235.         CheckGameOverConditions(eightBallPocketed, cueBallPocketed);
  1236.         if (currentGameState == GAME_OVER) return; // Stop processing if game ended
  1237.     }
  1238.  
  1239.     // --- Foul Checks --- (Unchanged)
  1240.     bool turnFoul = false;
  1241.     if (cueBallPocketed) {
  1242.         foulCommitted = true;
  1243.         turnFoul = true;
  1244.     }
  1245.     // (Other foul checks like wrong ball first, no rail after contact, etc. could be added here)
  1246.  
  1247.  
  1248.     // --- State Transitions ---
  1249.  
  1250.     // 1. Break Shot Results (Assigning Colors)
  1251.     //    Condition: Colors not assigned AND at least one object ball pocketed AND no scratch
  1252.     if (player1Info.assignedType == BallType::NONE && anyNonCueBallPocketed && !cueBallPocketed)
  1253.     {
  1254.         // --- Added Safeguard ---
  1255.         // Ensure the recorded 'firstPocketedType' corresponds to an actual pocketed ball ID this turn.
  1256.         bool firstTypeVerified = false;
  1257.         for (int id : pocketedThisTurn) {
  1258.             if (id == firstPocketedId) {
  1259.                 firstTypeVerified = true;
  1260.                 break;
  1261.             }
  1262.         }
  1263.  
  1264.         // Only assign types if the first recorded pocketed ball type is valid and verified
  1265.         if (firstTypeVerified && (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE))
  1266.         {
  1267.             AssignPlayerBallTypes(firstPocketedType);
  1268.  
  1269.             // Update ball counts based on ALL balls pocketed this turn after assignment
  1270.             player1Info.ballsPocketedCount = 0;
  1271.             player2Info.ballsPocketedCount = 0;
  1272.             for (int id : pocketedThisTurn) {
  1273.                 Ball* b = GetBallById(id);
  1274.                 if (b && b->id != 0 && b->id != 8) { // Ignore cue and 8-ball for counts
  1275.                     if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  1276.                     else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  1277.                 }
  1278.             }
  1279.  
  1280.             // Determine if player continues turn: Did they pocket their *newly assigned* type?
  1281.             bool pocketedOwnAssignedType = false;
  1282.             for (int id : pocketedThisTurn) {
  1283.                 Ball* b = GetBallById(id);
  1284.                 if (b && b->id != 0 && b->id != 8 && b->type == currentPlayerInfo.assignedType) {
  1285.                     pocketedOwnAssignedType = true;
  1286.                     break;
  1287.                 }
  1288.             }
  1289.  
  1290.             if (pocketedOwnAssignedType) {
  1291.                 // Continue turn
  1292.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1293.                 // If AI's turn, ensure flag is set to trigger next move
  1294.                 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  1295.             }
  1296.             else {
  1297.                 // Switch turns if they didn't pocket their assigned type on the assigning shot
  1298.                 SwitchTurns();
  1299.             }
  1300.         }
  1301.         else {
  1302.             // If only 8-ball was pocketed on break (and no scratch), or something went wrong.
  1303.             // Re-spot 8-ball was handled in CheckGameOverConditions.
  1304.             // Treat as end of turn, switch players.
  1305.             SwitchTurns();
  1306.         }
  1307.  
  1308.     }
  1309.     // 2. Normal Play Results (Colors already assigned)
  1310.     else {
  1311.         // Update pocketed counts for assigned types
  1312.         // (Do this even if foul, as balls are off the table)
  1313.         int p1NewlyPocketed = 0;
  1314.         int p2NewlyPocketed = 0;
  1315.         for (int id : pocketedThisTurn) {
  1316.             Ball* b = GetBallById(id);
  1317.             if (!b || b->id == 0 || b->id == 8) continue;
  1318.             if (b->type == player1Info.assignedType) p1NewlyPocketed++;
  1319.             else if (b->type == player2Info.assignedType) p2NewlyPocketed++;
  1320.         }
  1321.         // Only update counts if not already game over state (prevents double counting on winning 8ball shot)
  1322.         if (currentGameState != GAME_OVER) {
  1323.             player1Info.ballsPocketedCount += p1NewlyPocketed;
  1324.             player2Info.ballsPocketedCount += p2NewlyPocketed;
  1325.         }
  1326.  
  1327.  
  1328.         // Decide next turn based on foul or legal pocket
  1329.         if (turnFoul) {
  1330.             // Pass turn, give opponent ball-in-hand
  1331.             SwitchTurns();
  1332.             RespawnCueBall(false); // Ball in hand for opponent
  1333.         }
  1334.         else if (legalBallPocketed) {
  1335.             // Player legally pocketed their own ball, continue turn
  1336.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1337.             // If AI's turn, make sure it knows to go again
  1338.             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  1339.         }
  1340.         else {
  1341.             // No legal ball pocketed or only opponent ball pocketed without foul.
  1342.             SwitchTurns();
  1343.         }
  1344.     }
  1345.  
  1346.     // --- Cleanup for next shot ---
  1347.     // Clear the list of balls pocketed *in this specific shot sequence*
  1348.     pocketedThisTurn.clear();
  1349. }
  1350.  
  1351. void AssignPlayerBallTypes(BallType firstPocketedType) {
  1352.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  1353.         if (currentPlayer == 1) {
  1354.             player1Info.assignedType = firstPocketedType;
  1355.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1356.         }
  1357.         else {
  1358.             player2Info.assignedType = firstPocketedType;
  1359.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1360.         }
  1361.     }
  1362.     // If 8-ball was first (illegal on break generally), rules vary.
  1363.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  1364.     // Or assign based on what *else* was pocketed, if anything.
  1365.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  1366. }
  1367.  
  1368. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  1369.     if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
  1370.  
  1371.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1372.     bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
  1373.  
  1374.     // Loss Conditions:
  1375.     // 1. Pocket 8-ball AND scratch (pocket cue ball)
  1376.     // 2. Pocket 8-ball before clearing own color group
  1377.     if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
  1378.         gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
  1379.         currentGameState = GAME_OVER;
  1380.     }
  1381.     // Win Condition:
  1382.     // 1. Pocket 8-ball legally after clearing own color group
  1383.     else if (playerClearedBalls) {
  1384.         gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
  1385.         currentGameState = GAME_OVER;
  1386.     }
  1387.     // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
  1388.     // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
  1389.     else if (player1Info.assignedType == BallType::NONE) {
  1390.         Ball* eightBall = GetBallById(8);
  1391.         if (eightBall) {
  1392.             eightBall->isPocketed = false;
  1393.             // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
  1394.             eightBall->x = RACK_POS_X;
  1395.             eightBall->y = RACK_POS_Y;
  1396.             eightBall->vx = eightBall->vy = 0;
  1397.             // Check overlap and nudge if necessary (simplified)
  1398.         }
  1399.         // Apply foul rules if cue ball was also pocketed
  1400.         if (cueBallPocketed) {
  1401.             foulCommitted = true;
  1402.             // Don't switch turns on break scratch + 8ball pocket? Rules vary.
  1403.             // Let's make it a foul, switch turns, ball in hand.
  1404.             SwitchTurns();
  1405.             RespawnCueBall(false); // Ball in hand for opponent
  1406.         }
  1407.         else {
  1408.             // Just respawned 8ball, continue turn or switch based on other balls pocketed.
  1409.             // Let ProcessShotResults handle turn logic based on other pocketed balls.
  1410.         }
  1411.         // Prevent immediate game over message by returning here
  1412.         return;
  1413.     }
  1414.  
  1415.  
  1416. }
  1417.  
  1418.  
  1419. void SwitchTurns() {
  1420.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  1421.     // Reset aiming state for the new player
  1422.     isAiming = false;
  1423.     shotPower = 0;
  1424.     // Reset foul flag before new turn *really* starts (AI might take over)
  1425.     // Foul flag is mainly for display, gets cleared before human/AI shot
  1426.     // foulCommitted = false; // Probably better to clear before ApplyShot
  1427.  
  1428.     // Set the correct state based on who's turn it is
  1429.     if (currentPlayer == 1) {
  1430.         currentGameState = PLAYER1_TURN;
  1431.         aiTurnPending = false; // Ensure AI flag is off for P1
  1432.     }
  1433.     else { // Player 2's turn
  1434.         if (isPlayer2AI) {
  1435.             currentGameState = PLAYER2_TURN; // State indicates it's P2's turn
  1436.             aiTurnPending = true;           // Set flag for GameUpdate to trigger AI
  1437.             // AI will handle Ball-in-Hand logic if necessary within its decision making
  1438.         }
  1439.         else {
  1440.             currentGameState = PLAYER2_TURN; // Human P2
  1441.             aiTurnPending = false;
  1442.         }
  1443.     }
  1444. }
  1445.  
  1446. // --- Helper Functions ---
  1447.  
  1448. Ball* GetBallById(int id) {
  1449.     for (size_t i = 0; i < balls.size(); ++i) {
  1450.         if (balls[i].id == id) {
  1451.             return &balls[i];
  1452.         }
  1453.     }
  1454.     return nullptr;
  1455. }
  1456.  
  1457. Ball* GetCueBall() {
  1458.     return GetBallById(0);
  1459. }
  1460.  
  1461. float GetDistance(float x1, float y1, float x2, float y2) {
  1462.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  1463. }
  1464.  
  1465. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  1466.     float dx = x2 - x1;
  1467.     float dy = y2 - y1;
  1468.     return dx * dx + dy * dy;
  1469. }
  1470.  
  1471. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  1472.     // Basic bounds check (inside cushions)
  1473.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  1474.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  1475.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  1476.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  1477.  
  1478.     if (x < left || x > right || y < top || y > bottom) {
  1479.         return false;
  1480.     }
  1481.  
  1482.     // Check headstring restriction if needed
  1483.     if (checkHeadstring && x >= HEADSTRING_X) {
  1484.         return false;
  1485.     }
  1486.  
  1487.     // Check overlap with other balls
  1488.     for (size_t i = 0; i < balls.size(); ++i) {
  1489.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  1490.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  1491.                 return false; // Overlapping another ball
  1492.             }
  1493.         }
  1494.     }
  1495.  
  1496.     return true;
  1497. }
  1498.  
  1499.  
  1500. template <typename T>
  1501. void SafeRelease(T** ppT) {
  1502.     if (*ppT) {
  1503.         (*ppT)->Release();
  1504.         *ppT = nullptr;
  1505.     }
  1506. }
  1507.  
  1508. // --- Helper Function for Line Segment Intersection ---
  1509. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  1510. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  1511. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  1512. {
  1513.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  1514.  
  1515.     // Check if lines are parallel or collinear
  1516.     if (fabs(denominator) < 1e-6) {
  1517.         return false;
  1518.     }
  1519.  
  1520.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  1521.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  1522.  
  1523.     // Check if intersection point lies on both segments
  1524.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  1525.         intersection.x = p1.x + ua * (p2.x - p1.x);
  1526.         intersection.y = p1.y + ua * (p2.y - p1.y);
  1527.         return true;
  1528.     }
  1529.  
  1530.     return false;
  1531. }
  1532.  
  1533. // --- NEW AI Implementation Functions ---
  1534.  
  1535. // Main entry point for AI turn
  1536. void AIMakeDecision() {
  1537.     Ball* cueBall = GetCueBall();
  1538.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return; // Safety checks
  1539.  
  1540.     // Handle Ball-in-Hand placement first if necessary
  1541.     if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BALL_IN_HAND_P2) {
  1542.         AIPlaceCueBall();
  1543.         // After placement, state should transition to PLAYER2_TURN or BREAKING
  1544.         currentGameState = (player1Info.assignedType == BallType::NONE) ? BREAKING : PLAYER2_TURN;
  1545.     }
  1546.  
  1547.     // Now find the best shot from the current position
  1548.     AIShotInfo bestShot = AIFindBestShot();
  1549.  
  1550.     if (bestShot.possible) {
  1551.         // Add slight delay maybe? For now, shoot immediately.
  1552.         // Apply calculated shot
  1553.         ApplyShot(bestShot.power, bestShot.angle, 0.0f, 0.0f); // AI doesn't use spin yet
  1554.  
  1555.         // Set state to shot in progress (ApplyShot might do this already)
  1556.         currentGameState = SHOT_IN_PROGRESS;
  1557.         foulCommitted = false; // Reset foul flag for AI shot
  1558.         pocketedThisTurn.clear(); // Clear previous pockets
  1559.     }
  1560.     else {
  1561.         // AI couldn't find any shot (highly unlikely with simple logic, but possible)
  1562.         // Safety shot? Push cue ball gently? Forfeit turn?
  1563.         // Simplest: Just tap the cue ball gently forward as a safety/pass.
  1564.         ApplyShot(MAX_SHOT_POWER * 0.1f, 0.0f, 0.0f, 0.0f); // Gentle tap forward
  1565.         currentGameState = SHOT_IN_PROGRESS;
  1566.         foulCommitted = false;
  1567.         pocketedThisTurn.clear();
  1568.         // NOTE: This might cause a foul if no ball is hit. Harder AI would handle this better.
  1569.     }
  1570.     aiTurnPending = false; // Ensure flag is off after decision
  1571. }
  1572.  
  1573. // AI logic for placing cue ball during ball-in-hand
  1574. void AIPlaceCueBall() {
  1575.     Ball* cueBall = GetCueBall();
  1576.     if (!cueBall) return;
  1577.  
  1578.     // Simple Strategy: Find the easiest possible shot for the AI's ball type
  1579.     // Place the cue ball directly behind that target ball, aiming straight at a pocket.
  1580.     // (More advanced: find spot offering multiple options or safety)
  1581.  
  1582.     AIShotInfo bestPlacementShot = { false };
  1583.     D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
  1584.  
  1585.     BallType targetType = player2Info.assignedType;
  1586.     bool canTargetAnyPlacement = false; // Local scope variable for placement logic
  1587.     if (targetType == BallType::NONE) {
  1588.         canTargetAnyPlacement = true;
  1589.     }
  1590.     bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1591.     if (target8Ball) targetType = BallType::EIGHT_BALL;
  1592.  
  1593.  
  1594.     for (auto& targetBall : balls) {
  1595.         if (targetBall.isPocketed || targetBall.id == 0) continue;
  1596.  
  1597.         // Determine if current ball is a valid target for placement consideration
  1598.         bool currentBallIsValidTarget = false;
  1599.         if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
  1600.         else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
  1601.         else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
  1602.  
  1603.         if (!currentBallIsValidTarget) continue; // Skip if not a valid target
  1604.  
  1605.         for (int p = 0; p < 6; ++p) {
  1606.             // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
  1607.             float targetToPocketX = pocketPositions[p].x - targetBall.x;
  1608.             float targetToPocketY = pocketPositions[p].y - targetBall.y;
  1609.             float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1610.             if (dist < 1.0f) continue; // Avoid division by zero
  1611.  
  1612.             float idealAngle = atan2f(targetToPocketY, targetToPocketX);
  1613.             // Place cue ball slightly behind target ball along this line
  1614.             float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
  1615.             D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
  1616.                 targetBall.x - cosf(idealAngle) * placeDist,
  1617.                 targetBall.y - sinf(idealAngle) * placeDist
  1618.             );
  1619.  
  1620.             // Check if this placement is valid (on table, behind headstring if break, not overlapping)
  1621.             bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);
  1622.             if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
  1623.                 // Is path from potentialPlacePos to targetBall clear?
  1624.                 // Use D2D1::Point2F() factory function here
  1625.                 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
  1626.                     // Is path from targetBall to pocket clear?
  1627.                     // Use D2D1::Point2F() factory function here
  1628.                     if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
  1629.                         // This seems like a good potential placement. Score it?
  1630.                         // Easy AI: Just take the first valid one found.
  1631.                         bestPlacePos = potentialPlacePos;
  1632.                         goto placement_found; // Use goto for simplicity in non-OOP structure
  1633.                     }
  1634.                 }
  1635.             }
  1636.         }
  1637.     }
  1638.  
  1639. placement_found:
  1640.     // Place the cue ball at the best found position (or default if none found)
  1641.     cueBall->x = bestPlacePos.x;
  1642.     cueBall->y = bestPlacePos.y;
  1643.     cueBall->vx = 0;
  1644.     cueBall->vy = 0;
  1645. }
  1646.  
  1647.  
  1648. // AI finds the best shot available on the table
  1649. AIShotInfo AIFindBestShot() {
  1650.     AIShotInfo bestShotOverall = { false };
  1651.     Ball* cueBall = GetCueBall();
  1652.     if (!cueBall) return bestShotOverall;
  1653.  
  1654.     // Determine target ball type for AI (Player 2)
  1655.     BallType targetType = player2Info.assignedType;
  1656.     bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
  1657.     if (targetType == BallType::NONE) {
  1658.         // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
  1659.         // Or, more simply, treat any ball as a potential target to make *a* pocket
  1660.         canTargetAny = true; // Simplification: allow targeting any non-8 ball.
  1661.         // A better rule is hit lowest numbered ball first on break follow-up.
  1662.     }
  1663.  
  1664.     // Check if AI needs to shoot the 8-ball
  1665.     bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1666.  
  1667.  
  1668.     // Iterate through all potential target balls
  1669.     for (auto& potentialTarget : balls) {
  1670.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
  1671.  
  1672.         // Check if this ball is a valid target
  1673.         bool isValidTarget = false;
  1674.         if (target8Ball) {
  1675.             isValidTarget = (potentialTarget.id == 8);
  1676.         }
  1677.         else if (canTargetAny) {
  1678.             isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
  1679.         }
  1680.         else { // Colors assigned, not yet shooting 8-ball
  1681.             isValidTarget = (potentialTarget.type == targetType);
  1682.         }
  1683.  
  1684.         if (!isValidTarget) continue; // Skip if not a valid target for this turn
  1685.  
  1686.         // Now, check all pockets for this target ball
  1687.         for (int p = 0; p < 6; ++p) {
  1688.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  1689.             currentShot.involves8Ball = (potentialTarget.id == 8);
  1690.  
  1691.             if (currentShot.possible) {
  1692.                 // Compare scores to find the best shot
  1693.                 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  1694.                     bestShotOverall = currentShot;
  1695.                 }
  1696.             }
  1697.         }
  1698.     } // End loop through potential target balls
  1699.  
  1700.     // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
  1701.     // need a safety strategy. Current simple AI just takes best found or taps cue ball.
  1702.  
  1703.     return bestShotOverall;
  1704. }
  1705.  
  1706.  
  1707. // Evaluate a potential shot at a specific target ball towards a specific pocket
  1708. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  1709.     AIShotInfo shotInfo;
  1710.     shotInfo.possible = false; // Assume not possible initially
  1711.     shotInfo.targetBall = targetBall;
  1712.     shotInfo.pocketIndex = pocketIndex;
  1713.  
  1714.     Ball* cueBall = GetCueBall();
  1715.     if (!cueBall || !targetBall) return shotInfo;
  1716.  
  1717.     // --- Define local state variables needed for legality checks ---
  1718.     BallType aiAssignedType = player2Info.assignedType;
  1719.     bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
  1720.     bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1721.     // ---
  1722.  
  1723.     // 1. Calculate Ghost Ball position
  1724.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  1725.  
  1726.     // 2. Calculate Angle from Cue Ball to Ghost Ball
  1727.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  1728.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  1729.     if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
  1730.     shotInfo.angle = atan2f(dy, dx);
  1731.  
  1732.     // Basic angle validity check (optional)
  1733.     if (!IsValidAIAimAngle(shotInfo.angle)) {
  1734.         // Maybe log this or handle edge cases
  1735.     }
  1736.  
  1737.     // 3. Check Path: Cue Ball -> Ghost Ball Position
  1738.     // Use D2D1::Point2F() factory function here
  1739.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  1740.         return shotInfo; // Path blocked
  1741.     }
  1742.  
  1743.     // 4. Check Path: Target Ball -> Pocket
  1744.     // Use D2D1::Point2F() factory function here
  1745.     if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
  1746.         return shotInfo; // Path blocked
  1747.     }
  1748.  
  1749.     // 5. Check First Ball Hit Legality
  1750.     float firstHitDistSq = -1.0f;
  1751.     // Use D2D1::Point2F() factory function here
  1752.     Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
  1753.  
  1754.     if (!firstHit) {
  1755.         return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
  1756.     }
  1757.  
  1758.     // Check if the first ball hit is the intended target ball
  1759.     if (firstHit->id != targetBall->id) {
  1760.         // Allow hitting slightly off target if it's very close to ghost ball pos
  1761.         float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
  1762.         // Allow a tolerance roughly half the ball radius squared
  1763.         if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
  1764.             // First hit is significantly different from the target point.
  1765.             // This shot path leads to hitting the wrong ball first.
  1766.             return shotInfo; // Foul or unintended shot
  1767.         }
  1768.         // If first hit is not target, but very close, allow it for now (might still be foul based on type).
  1769.     }
  1770.  
  1771.     // Check legality of the *first ball actually hit* based on game rules
  1772.     if (!canTargetAny) { // Colors are assigned (or should be)
  1773.         if (mustTarget8Ball) { // Must hit 8-ball first
  1774.             if (firstHit->id != 8) {
  1775.                 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
  1776.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1777.             }
  1778.         }
  1779.         else { // Must hit own ball type first
  1780.             if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
  1781.                 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
  1782.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1783.             }
  1784.             else if (firstHit->id == 8) {
  1785.                 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
  1786.                 // Keep shot possible for now
  1787.             }
  1788.         }
  1789.     }
  1790.     // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
  1791.  
  1792.  
  1793.     // 6. Calculate Score & Power (Difficulty affects this)
  1794.     shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
  1795.  
  1796.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  1797.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  1798.  
  1799.     // Simple Score: Shorter shots are better, straighter shots are slightly better.
  1800.     float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
  1801.  
  1802.     // Angle Score: Calculate cut angle
  1803.     // Vector Cue -> Ghost
  1804.     float v1x = shotInfo.ghostBallPos.x - cueBall->x;
  1805.     float v1y = shotInfo.ghostBallPos.y - cueBall->y;
  1806.     // Vector Target -> Pocket
  1807.     float v2x = pocketPositions[pocketIndex].x - targetBall->x;
  1808.     float v2y = pocketPositions[pocketIndex].y - targetBall->y;
  1809.     // Normalize vectors
  1810.     float mag1 = sqrtf(v1x * v1x + v1y * v1y);
  1811.     float mag2 = sqrtf(v2x * v2x + v2y * v2y);
  1812.     float angleScoreFactor = 0.5f; // Default if vectors are zero len
  1813.     if (mag1 > 0.1f && mag2 > 0.1f) {
  1814.         v1x /= mag1; v1y /= mag1;
  1815.         v2x /= mag2; v2y /= mag2;
  1816.         // Dot product gives cosine of angle between cue ball path and target ball path
  1817.         float dotProduct = v1x * v2x + v1y * v2y;
  1818.         // Straighter shot (dot product closer to 1) gets higher score
  1819.         angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
  1820.     }
  1821.     angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
  1822.  
  1823.     shotInfo.score = distanceScore * angleScoreFactor;
  1824.  
  1825.     // Bonus for pocketing 8-ball legally
  1826.     if (mustTarget8Ball && targetBall->id == 8) {
  1827.         shotInfo.score *= 10.0; // Strongly prefer the winning shot
  1828.     }
  1829.  
  1830.     // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
  1831.  
  1832.     // 7. Calculate Power
  1833.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  1834.  
  1835.     // 8. Add Inaccuracy based on Difficulty (same as before)
  1836.     float angleError = 0.0f;
  1837.     float powerErrorFactor = 1.0f;
  1838.  
  1839.     switch (aiDifficulty) {
  1840.     case EASY:
  1841.         angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
  1842.         powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
  1843.         shotInfo.power *= 0.8f;
  1844.         break;
  1845.     case MEDIUM:
  1846.         angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
  1847.         powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
  1848.         break;
  1849.     case HARD:
  1850.         angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
  1851.         powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
  1852.         break;
  1853.     }
  1854.     shotInfo.angle += angleError;
  1855.     shotInfo.power *= powerErrorFactor;
  1856.     shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
  1857.  
  1858.     return shotInfo;
  1859. }
  1860.  
  1861.  
  1862. // Calculates required power (simplified)
  1863. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  1864.     // Basic model: Power needed increases with total distance the balls need to travel.
  1865.     // Need enough power for cue ball to reach target AND target to reach pocket.
  1866.     float totalDist = cueToGhostDist + targetToPocketDist;
  1867.  
  1868.     // Map distance to power (needs tuning)
  1869.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  1870.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  1871.  
  1872.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  1873.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  1874.  
  1875.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  1876.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  1877. }
  1878.  
  1879. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  1880. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  1881.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  1882.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  1883.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1884.  
  1885.     if (dist < 1.0f) { // Target is basically in the pocket
  1886.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  1887.         // For simplicity, return a point slightly behind center along the reverse line.
  1888.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  1889.     }
  1890.  
  1891.     // Normalize direction vector from target to pocket
  1892.     float nx = targetToPocketX / dist;
  1893.     float ny = targetToPocketY / dist;
  1894.  
  1895.     // Ghost ball position is diameter distance *behind* the target ball along this line
  1896.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  1897.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  1898.  
  1899.     return D2D1::Point2F(ghostX, ghostY);
  1900. }
  1901.  
  1902. // Checks if line segment is clear of obstructing balls
  1903. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  1904.     float dx = end.x - start.x;
  1905.     float dy = end.y - start.y;
  1906.     float segmentLenSq = dx * dx + dy * dy;
  1907.  
  1908.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  1909.  
  1910.     for (const auto& ball : balls) {
  1911.         if (ball.isPocketed) continue;
  1912.         if (ball.id == ignoredBallId1) continue;
  1913.         if (ball.id == ignoredBallId2) continue;
  1914.  
  1915.         // Check distance from ball center to the line segment
  1916.         float ballToStartX = ball.x - start.x;
  1917.         float ballToStartY = ball.y - start.y;
  1918.  
  1919.         // Project ball center onto the line defined by the segment
  1920.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  1921.  
  1922.         D2D1_POINT_2F closestPointOnLine;
  1923.         if (dot < 0) { // Closest point is start point
  1924.             closestPointOnLine = start;
  1925.         }
  1926.         else if (dot > 1) { // Closest point is end point
  1927.             closestPointOnLine = end;
  1928.         }
  1929.         else { // Closest point is along the segment
  1930.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  1931.         }
  1932.  
  1933.         // Check if the closest point is within collision distance (ball radius + path radius)
  1934.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  1935.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  1936.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  1937.             return false; // Path is blocked
  1938.         }
  1939.     }
  1940.     return true; // No obstructions found
  1941. }
  1942.  
  1943. // Finds the first ball hit along a path (simplified)
  1944. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  1945.     Ball* hitBall = nullptr;
  1946.     hitDistSq = -1.0f; // Initialize hit distance squared
  1947.     float minCollisionDistSq = -1.0f;
  1948.  
  1949.     float cosA = cosf(angle);
  1950.     float sinA = sinf(angle);
  1951.  
  1952.     for (auto& ball : balls) {
  1953.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  1954.  
  1955.         float dx = ball.x - start.x;
  1956.         float dy = ball.y - start.y;
  1957.  
  1958.         // Project vector from start->ball onto the aim direction vector
  1959.         float dot = dx * cosA + dy * sinA;
  1960.  
  1961.         if (dot > 0) { // Ball is generally in front
  1962.             // Find closest point on aim line to the ball's center
  1963.             float closestPointX = start.x + dot * cosA;
  1964.             float closestPointY = start.y + dot * sinA;
  1965.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  1966.  
  1967.             // Check if the aim line passes within the ball's radius
  1968.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  1969.                 // Calculate distance from start to the collision point on the ball's circumference
  1970.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  1971.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  1972.  
  1973.                 if (collisionDist > 0) { // Ensure collision is in front
  1974.                     float collisionDistSq = collisionDist * collisionDist;
  1975.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  1976.                         minCollisionDistSq = collisionDistSq;
  1977.                         hitBall = &ball; // Found a closer hit ball
  1978.                     }
  1979.                 }
  1980.             }
  1981.         }
  1982.     }
  1983.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  1984.     return hitBall;
  1985. }
  1986.  
  1987. // Basic check for reasonable AI aim angles (optional)
  1988. bool IsValidAIAimAngle(float angle) {
  1989.     // Placeholder - could check for NaN or infinity if calculations go wrong
  1990.     return isfinite(angle);
  1991. }
  1992.  
  1993. // --- Drawing Functions ---
  1994.  
  1995. void OnPaint() {
  1996.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  1997.  
  1998.     if (SUCCEEDED(hr)) {
  1999.         pRenderTarget->BeginDraw();
  2000.         DrawScene(pRenderTarget); // Pass render target
  2001.         hr = pRenderTarget->EndDraw();
  2002.  
  2003.         if (hr == D2DERR_RECREATE_TARGET) {
  2004.             DiscardDeviceResources();
  2005.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  2006.             // But the timer loop will trigger redraw anyway.
  2007.         }
  2008.     }
  2009.     // If CreateDeviceResources failed, EndDraw might not be called.
  2010.     // Consider handling this more robustly if needed.
  2011. }
  2012.  
  2013. void DrawScene(ID2D1RenderTarget* pRT) {
  2014.     if (!pRT) return;
  2015.  
  2016.     pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  2017.  
  2018.     DrawTable(pRT);
  2019.     DrawBalls(pRT);
  2020.     DrawAimingAids(pRT); // Includes cue stick if aiming
  2021.     DrawUI(pRT);
  2022.     DrawPowerMeter(pRT);
  2023.     DrawSpinIndicator(pRT);
  2024.     DrawPocketedBallsIndicator(pRT);
  2025.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  2026.  
  2027.      // Draw Game Over Message
  2028.     if (currentGameState == GAME_OVER && pTextFormat) {
  2029.         ID2D1SolidColorBrush* pBrush = nullptr;
  2030.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  2031.         if (pBrush) {
  2032.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  2033.             pRT->DrawText(
  2034.                 gameOverMessage.c_str(),
  2035.                 (UINT32)gameOverMessage.length(),
  2036.                 pTextFormat, // Use large format maybe?
  2037.                 &layoutRect,
  2038.                 pBrush
  2039.             );
  2040.             SafeRelease(&pBrush);
  2041.         }
  2042.     }
  2043.  
  2044. }
  2045.  
  2046. void DrawTable(ID2D1RenderTarget* pRT) {
  2047.     ID2D1SolidColorBrush* pBrush = nullptr;
  2048.  
  2049.     // Draw Table Bed (Green Felt)
  2050.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  2051.     if (!pBrush) return;
  2052.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  2053.     pRT->FillRectangle(&tableRect, pBrush);
  2054.     SafeRelease(&pBrush);
  2055.  
  2056.     // Draw Cushions (Red Border)
  2057.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  2058.     if (!pBrush) return;
  2059.     // Top Cushion (split by middle pocket)
  2060.     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);
  2061.     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);
  2062.     // Bottom Cushion (split by middle pocket)
  2063.     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);
  2064.     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);
  2065.     // Left Cushion
  2066.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2067.     // Right Cushion
  2068.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2069.     SafeRelease(&pBrush);
  2070.  
  2071.  
  2072.     // Draw Pockets (Black Circles)
  2073.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  2074.     if (!pBrush) return;
  2075.     for (int i = 0; i < 6; ++i) {
  2076.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  2077.         pRT->FillEllipse(&ellipse, pBrush);
  2078.     }
  2079.     SafeRelease(&pBrush);
  2080.  
  2081.     // Draw Headstring Line (White)
  2082.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush);
  2083.     if (!pBrush) return;
  2084.     pRT->DrawLine(
  2085.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  2086.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  2087.         pBrush,
  2088.         1.0f // Line thickness
  2089.     );
  2090.     SafeRelease(&pBrush);
  2091. }
  2092.  
  2093.  
  2094. void DrawBalls(ID2D1RenderTarget* pRT) {
  2095.     ID2D1SolidColorBrush* pBrush = nullptr;
  2096.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  2097.  
  2098.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  2099.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  2100.  
  2101.     if (!pBrush || !pStripeBrush) {
  2102.         SafeRelease(&pBrush);
  2103.         SafeRelease(&pStripeBrush);
  2104.         return;
  2105.     }
  2106.  
  2107.  
  2108.     for (size_t i = 0; i < balls.size(); ++i) {
  2109.         const Ball& b = balls[i];
  2110.         if (!b.isPocketed) {
  2111.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  2112.  
  2113.             // Set main ball color
  2114.             pBrush->SetColor(b.color);
  2115.             pRT->FillEllipse(&ellipse, pBrush);
  2116.  
  2117.             // Draw Stripe if applicable
  2118.             if (b.type == BallType::STRIPE) {
  2119.                 // Draw a white band across the middle (simplified stripe)
  2120.                 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);
  2121.                 // Need to clip this rectangle to the ellipse bounds - complex!
  2122.                 // Alternative: Draw two colored arcs leaving a white band.
  2123.                 // Simplest: Draw a white circle inside, slightly smaller.
  2124.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  2125.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  2126.                 pBrush->SetColor(b.color); // Set back to stripe color
  2127.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  2128.  
  2129.                 // Let's try drawing a thick white line across
  2130.                 // This doesn't look great. Just drawing solid red for stripes for now.
  2131.             }
  2132.  
  2133.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  2134.             // if (b.id != 0 && pTextFormat) {
  2135.             //     std::wstring numStr = std::to_wstring(b.id);
  2136.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  2137.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  2138.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  2139.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  2140.             //     // Create a smaller text format...
  2141.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  2142.             //     SafeRelease(&pNumBrush);
  2143.             // }
  2144.         }
  2145.     }
  2146.  
  2147.     SafeRelease(&pBrush);
  2148.     SafeRelease(&pStripeBrush);
  2149. }
  2150.  
  2151.  
  2152. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  2153.     // Condition check at start (Unchanged)
  2154.     if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  2155.         currentGameState != BREAKING && currentGameState != AIMING)
  2156.     {
  2157.         return;
  2158.     }
  2159.  
  2160.     Ball* cueBall = GetCueBall();
  2161.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  2162.  
  2163.     ID2D1SolidColorBrush* pBrush = nullptr;
  2164.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2165.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  2166.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  2167.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  2168.  
  2169.     // Ensure render target is valid
  2170.     if (!pRT) return;
  2171.  
  2172.     // Create Brushes and Styles (check for failures)
  2173.     HRESULT hr;
  2174.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  2175.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  2176.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  2177.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  2178.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  2179.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  2180.     // Create reflection brush (e.g., lighter shade or different color)
  2181.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  2182.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  2183.  
  2184.     if (pFactory) {
  2185.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  2186.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  2187.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  2188.         if FAILED(hr) { pDashedStyle = nullptr; }
  2189.     }
  2190.  
  2191.  
  2192.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  2193.     const float baseStickLength = 150.0f;
  2194.     const float baseStickThickness = 4.0f;
  2195.     float stickLength = baseStickLength * 1.4f;
  2196.     float stickThickness = baseStickThickness * 1.5f;
  2197.     float stickAngle = cueAngle + PI;
  2198.     float powerOffset = 0.0f;
  2199.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2200.         powerOffset = shotPower * 5.0f;
  2201.     }
  2202.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  2203.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  2204.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  2205.  
  2206.  
  2207.     // --- Projection Line Calculation ---
  2208.     float cosA = cosf(cueAngle);
  2209.     float sinA = sinf(cueAngle);
  2210.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  2211.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  2212.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  2213.  
  2214.     // Find the first ball hit by the aiming ray
  2215.     Ball* hitBall = nullptr;
  2216.     float firstHitDistSq = -1.0f;
  2217.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  2218.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  2219.  
  2220.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  2221.     if (hitBall) {
  2222.         // Calculate the point on the target ball's circumference
  2223.         float collisionDist = sqrtf(firstHitDistSq);
  2224.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  2225.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  2226.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  2227.     }
  2228.  
  2229.     // Find the first rail hit by the aiming ray
  2230.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  2231.     float minRailDistSq = rayLength * rayLength;
  2232.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  2233.  
  2234.     // Define table edge segments for intersection checks
  2235.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  2236.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  2237.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  2238.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  2239.  
  2240.     D2D1_POINT_2F currentIntersection;
  2241.  
  2242.     // Check Left Rail
  2243.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  2244.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  2245.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  2246.     }
  2247.     // Check Right Rail
  2248.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  2249.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  2250.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  2251.     }
  2252.     // Check Top Rail
  2253.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  2254.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  2255.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  2256.     }
  2257.     // Check Bottom Rail
  2258.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  2259.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  2260.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  2261.     }
  2262.  
  2263.  
  2264.     // --- Determine final aim line end point ---
  2265.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  2266.     bool aimingAtRail = true;
  2267.  
  2268.     if (hitBall && firstHitDistSq < minRailDistSq) {
  2269.         // Ball collision is closer than rail collision
  2270.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  2271.         aimingAtRail = false;
  2272.     }
  2273.  
  2274.     // --- Draw Primary Aiming Line ---
  2275.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2276.  
  2277.     // --- Draw Target Circle/Indicator ---
  2278.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  2279.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  2280.  
  2281.     // --- Draw Projection/Reflection Lines ---
  2282.     if (!aimingAtRail && hitBall) {
  2283.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  2284.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  2285.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2286.  
  2287.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  2288.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  2289.         // Clamp angle calculation if distance is tiny
  2290.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  2291.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  2292.         }
  2293.  
  2294.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  2295.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  2296.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  2297.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  2298.         );
  2299.         // Draw solid line for target projection
  2300.         pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  2301.  
  2302.         // -- Cue Ball Path after collision (Optional, requires physics) --
  2303.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  2304.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  2305.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  2306.         // D2D1_POINT_2F cueProjectionEnd = ...
  2307.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2308.  
  2309.         // --- Accuracy Comment ---
  2310.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  2311.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  2312.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  2313.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  2314.  
  2315.     }
  2316.     else if (aimingAtRail && hitRailIndex != -1) {
  2317.         // Aiming at a rail: Draw reflection line
  2318.         float reflectAngle = cueAngle;
  2319.         // Reflect angle based on which rail was hit
  2320.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  2321.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  2322.         }
  2323.         else { // Top or Bottom rail
  2324.             reflectAngle = -cueAngle; // Reflect vertical component
  2325.         }
  2326.         // Normalize angle if needed (atan2 usually handles this)
  2327.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  2328.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  2329.  
  2330.  
  2331.         float reflectionLength = 60.0f; // Length of the reflection line
  2332.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  2333.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  2334.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  2335.         );
  2336.  
  2337.         // Draw the reflection line (e.g., using a different color/style)
  2338.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2339.     }
  2340.  
  2341.     // Release resources
  2342.     SafeRelease(&pBrush);
  2343.     SafeRelease(&pGhostBrush);
  2344.     SafeRelease(&pCueBrush);
  2345.     SafeRelease(&pReflectBrush); // Release new brush
  2346.     SafeRelease(&pDashedStyle);
  2347. }
  2348.  
  2349. void DrawUI(ID2D1RenderTarget* pRT) {
  2350.     if (!pTextFormat || !pLargeTextFormat) return;
  2351.  
  2352.     ID2D1SolidColorBrush* pBrush = nullptr;
  2353.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  2354.     if (!pBrush) return;
  2355.  
  2356.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  2357.     float uiTop = TABLE_TOP - 80;
  2358.     float uiHeight = 60;
  2359.     float p1Left = TABLE_LEFT;
  2360.     float p1Width = 150;
  2361.     float p2Left = TABLE_RIGHT - p1Width;
  2362.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  2363.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  2364.  
  2365.     // Player 1 Info Text (Unchanged)
  2366.     std::wostringstream oss1;
  2367.     oss1 << player1Info.name.c_str() << L"\n";
  2368.     if (player1Info.assignedType != BallType::NONE) {
  2369.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2370.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  2371.     }
  2372.     else {
  2373.         oss1 << L"(Undecided)";
  2374.     }
  2375.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  2376.  
  2377.     // Player 2 Info Text (Unchanged)
  2378.     std::wostringstream oss2;
  2379.     oss2 << player2Info.name.c_str() << L"\n";
  2380.     if (player2Info.assignedType != BallType::NONE) {
  2381.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2382.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  2383.     }
  2384.     else {
  2385.         oss2 << L"(Undecided)";
  2386.     }
  2387.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  2388.  
  2389.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  2390.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  2391.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  2392.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2393.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  2394.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  2395.         float arrowTipX, arrowBackX;
  2396.  
  2397.         if (currentPlayer == 1) {
  2398.             // Player 1: Arrow left of P1 box, pointing right
  2399.             arrowBackX = p1Rect.left - 15.0f; // Position left of the box
  2400.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  2401.             // Define points for right-pointing arrow
  2402.             D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  2403.             D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  2404.             D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  2405.  
  2406.             ID2D1PathGeometry* pPath = nullptr;
  2407.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  2408.                 ID2D1GeometrySink* pSink = nullptr;
  2409.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  2410.                     pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  2411.                     pSink->AddLine(pt2);
  2412.                     pSink->AddLine(pt3);
  2413.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  2414.                     pSink->Close();
  2415.                     SafeRelease(&pSink);
  2416.                     pRT->FillGeometry(pPath, pArrowBrush);
  2417.                 }
  2418.                 SafeRelease(&pPath);
  2419.             }
  2420.         }
  2421.         else { // Player 2
  2422.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  2423.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  2424.             arrowBackX = p2Rect.left - 15.0f; // Position left of the box
  2425.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  2426.             // Define points for right-pointing arrow
  2427.             D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  2428.             D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  2429.             D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  2430.  
  2431.             ID2D1PathGeometry* pPath = nullptr;
  2432.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  2433.                 ID2D1GeometrySink* pSink = nullptr;
  2434.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  2435.                     pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  2436.                     pSink->AddLine(pt2);
  2437.                     pSink->AddLine(pt3);
  2438.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  2439.                     pSink->Close();
  2440.                     SafeRelease(&pSink);
  2441.                     pRT->FillGeometry(pPath, pArrowBrush);
  2442.                 }
  2443.                 SafeRelease(&pPath);
  2444.             }
  2445.         }
  2446.         SafeRelease(&pArrowBrush);
  2447.     }
  2448.  
  2449.  
  2450.     // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  2451.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  2452.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  2453.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  2454.         if (pFoulBrush && pLargeTextFormat) {
  2455.             // Calculate Rect for bottom-middle area
  2456.             float foulWidth = 200.0f; // Adjust width as needed
  2457.             float foulHeight = 60.0f;
  2458.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  2459.             // Position below the pocketed balls bar
  2460.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  2461.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  2462.  
  2463.             // --- Set text alignment to center for foul text ---
  2464.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2465.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2466.  
  2467.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  2468.  
  2469.             // --- Restore default alignment for large text if needed elsewhere ---
  2470.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  2471.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2472.  
  2473.             SafeRelease(&pFoulBrush);
  2474.         }
  2475.     }
  2476.  
  2477.     // Show AI Thinking State (Unchanged from previous step)
  2478.     if (currentGameState == AI_THINKING && pTextFormat) {
  2479.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  2480.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  2481.         if (pThinkingBrush) {
  2482.             D2D1_RECT_F thinkingRect = p2Rect;
  2483.             thinkingRect.top += 20; // Offset within P2 box
  2484.             // Ensure default text alignment for this
  2485.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2486.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2487.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  2488.             SafeRelease(&pThinkingBrush);
  2489.         }
  2490.     }
  2491.  
  2492.     SafeRelease(&pBrush);
  2493. }
  2494.  
  2495. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  2496.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  2497.     ID2D1SolidColorBrush* pFillBrush = nullptr;
  2498.  
  2499.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  2500.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LimeGreen), &pFillBrush);
  2501.  
  2502.     if (!pBorderBrush || !pFillBrush) {
  2503.         SafeRelease(&pBorderBrush);
  2504.         SafeRelease(&pFillBrush);
  2505.         return;
  2506.     }
  2507.  
  2508.     // Draw Border
  2509.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 1.0f);
  2510.  
  2511.     // Calculate Fill Height
  2512.     float fillRatio = 0;
  2513.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2514.         fillRatio = shotPower / MAX_SHOT_POWER;
  2515.     }
  2516.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  2517.     D2D1_RECT_F fillRect = D2D1::RectF(
  2518.         powerMeterRect.left, powerMeterRect.bottom - fillHeight,
  2519.         powerMeterRect.right, powerMeterRect.bottom
  2520.     );
  2521.  
  2522.     // Draw Fill
  2523.     pRT->FillRectangle(&fillRect, pFillBrush);
  2524.  
  2525.     SafeRelease(&pBorderBrush);
  2526.     SafeRelease(&pFillBrush);
  2527. }
  2528.  
  2529. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  2530.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  2531.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  2532.  
  2533.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  2534.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  2535.  
  2536.     if (!pWhiteBrush || !pRedBrush) {
  2537.         SafeRelease(&pWhiteBrush);
  2538.         SafeRelease(&pRedBrush);
  2539.         return;
  2540.     }
  2541.  
  2542.     // Draw White Ball Background
  2543.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  2544.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  2545.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  2546.  
  2547.  
  2548.     // Draw Red Dot for Spin Position
  2549.     float dotRadius = 4.0f;
  2550.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  2551.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  2552.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  2553.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  2554.  
  2555.     SafeRelease(&pWhiteBrush);
  2556.     SafeRelease(&pRedBrush);
  2557. }
  2558.  
  2559.  
  2560. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  2561.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  2562.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  2563.  
  2564.     // Ensure render target is valid before proceeding
  2565.     if (!pRT) return;
  2566.  
  2567.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  2568.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  2569.  
  2570.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  2571.     if (FAILED(hr)) {
  2572.         SafeRelease(&pBgBrush);
  2573.         SafeRelease(&pBallBrush);
  2574.         return; // Exit if brush creation fails
  2575.     }
  2576.  
  2577.     // Draw the background bar (rounded rect)
  2578.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  2579.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  2580.  
  2581.     // --- Draw small circles for pocketed balls inside the bar ---
  2582.  
  2583.     // Calculate dimensions based on the bar's height for better scaling
  2584.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  2585.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  2586.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  2587.     float padding = spacing * 0.75f; // Add padding from the edges
  2588.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  2589.  
  2590.     // Starting X positions with padding
  2591.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  2592.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  2593.  
  2594.     int p1DrawnCount = 0;
  2595.     int p2DrawnCount = 0;
  2596.     const int maxBallsToShow = 7; // Max balls per player in the bar
  2597.  
  2598.     for (const auto& b : balls) {
  2599.         if (b.isPocketed) {
  2600.             // Skip cue ball and 8-ball in this indicator
  2601.             if (b.id == 0 || b.id == 8) continue;
  2602.  
  2603.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  2604.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  2605.  
  2606.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  2607.                 pBallBrush->SetColor(b.color);
  2608.                 // Draw P1 balls from left to right
  2609.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2610.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2611.                 p1DrawnCount++;
  2612.             }
  2613.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  2614.                 pBallBrush->SetColor(b.color);
  2615.                 // Draw P2 balls from right to left
  2616.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2617.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2618.                 p2DrawnCount++;
  2619.             }
  2620.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  2621.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  2622.         }
  2623.     }
  2624.  
  2625.     SafeRelease(&pBgBrush);
  2626.     SafeRelease(&pBallBrush);
  2627. }
  2628.  
  2629. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  2630.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  2631.         return; // Only show when placing/dragging
  2632.     }
  2633.  
  2634.     Ball* cueBall = GetCueBall();
  2635.     if (!cueBall) return;
  2636.  
  2637.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2638.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  2639.  
  2640.     if (pGhostBrush) {
  2641.         D2D1_POINT_2F drawPos;
  2642.         if (isDraggingCueBall) {
  2643.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2644.         }
  2645.         else {
  2646.             // If not dragging but in placement state, show at current ball pos
  2647.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  2648.         }
  2649.  
  2650.         // Check if the placement is valid before drawing differently?
  2651.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2652.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  2653.  
  2654.         if (!isValid) {
  2655.             // Maybe draw red outline if invalid placement?
  2656.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  2657.         }
  2658.  
  2659.  
  2660.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  2661.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  2662.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  2663.  
  2664.         SafeRelease(&pGhostBrush);
  2665.     }
  2666. }
  2667. ```
  2668.  
  2669. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  2670. ```resource.h
  2671. //{{NO_DEPENDENCIES}}
  2672. // Microsoft Visual C++ generated include file.
  2673. // Used by Yahoo-8Ball-Pool-Clone.rc
  2674. //
  2675. #define IDI_ICON1                       101
  2676. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  2677. #define IDD_NEWGAMEDLG 106
  2678. #define IDC_RADIO_2P   1003
  2679. #define IDC_RADIO_CPU  1005
  2680. #define IDC_GROUP_AI   1006
  2681. #define IDC_RADIO_EASY 1007
  2682. #define IDC_RADIO_MEDIUM 1008
  2683. #define IDC_RADIO_HARD 1009
  2684. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  2685.  
  2686. // Next default values for new objects
  2687. //
  2688. #ifdef APSTUDIO_INVOKED
  2689. #ifndef APSTUDIO_READONLY_SYMBOLS
  2690. #define _APS_NEXT_RESOURCE_VALUE        102
  2691. #define _APS_NEXT_COMMAND_VALUE         40001
  2692. #define _APS_NEXT_CONTROL_VALUE         1001
  2693. #define _APS_NEXT_SYMED_VALUE           101
  2694. #endif
  2695. #endif
  2696.  
  2697. ```
  2698.  
  2699. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  2700. ```Yahoo-8Ball-Pool-Clone.rc
  2701. // Microsoft Visual C++ generated resource script.
  2702. //
  2703. #include "resource.h"
  2704.  
  2705. #define APSTUDIO_READONLY_SYMBOLS
  2706. /////////////////////////////////////////////////////////////////////////////
  2707. //
  2708. // Generated from the TEXTINCLUDE 2 resource.
  2709. //
  2710. #include "winres.h"
  2711.  
  2712. /////////////////////////////////////////////////////////////////////////////
  2713. #undef APSTUDIO_READONLY_SYMBOLS
  2714.  
  2715. /////////////////////////////////////////////////////////////////////////////
  2716. // English (United States) resources
  2717.  
  2718. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  2719. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  2720. #pragma code_page(1252)
  2721.  
  2722. #ifdef APSTUDIO_INVOKED
  2723. /////////////////////////////////////////////////////////////////////////////
  2724. //
  2725. // TEXTINCLUDE
  2726. //
  2727.  
  2728. 1 TEXTINCLUDE
  2729. BEGIN
  2730.     "resource.h\0"
  2731. END
  2732.  
  2733. 2 TEXTINCLUDE
  2734. BEGIN
  2735.     "#include ""winres.h""\r\n"
  2736.     "\0"
  2737. END
  2738.  
  2739. 3 TEXTINCLUDE
  2740. BEGIN
  2741.     "\r\n"
  2742.     "\0"
  2743. END
  2744.  
  2745. #endif    // APSTUDIO_INVOKED
  2746.  
  2747.  
  2748. /////////////////////////////////////////////////////////////////////////////
  2749. //
  2750. // Icon
  2751. //
  2752.  
  2753. // Icon with lowest ID value placed first to ensure application icon
  2754. // remains consistent on all systems.
  2755. IDI_ICON1               ICON                    "D:\\Download\\cpp-projekt\\FuzenOp_SiloTest\\icons\\shell32_277.ico"
  2756.  
  2757. #endif    // English (United States) resources
  2758. /////////////////////////////////////////////////////////////////////////////
  2759.  
  2760.  
  2761.  
  2762. #ifndef APSTUDIO_INVOKED
  2763. /////////////////////////////////////////////////////////////////////////////
  2764. //
  2765. // Generated from the TEXTINCLUDE 3 resource.
  2766. //
  2767.  
  2768.  
  2769. /////////////////////////////////////////////////////////////////////////////
  2770. #endif    // not APSTUDIO_INVOKED
  2771.  
  2772. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  2773.  
  2774. /////////////////////////////////////////////////////////////////////////////
  2775. //
  2776. // Dialog
  2777. //
  2778.  
  2779. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 130 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs)
  2780. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  2781. CAPTION "New 8-Ball Game"
  2782. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  2783. BEGIN
  2784. // --- Game Mode Selection ---
  2785. // Group Box for Game Mode (Optional visually, but helps structure)
  2786. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  2787.  
  2788. // "2 Player" Radio Button (First in this group)
  2789. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  2790. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  2791.  
  2792. // "Human vs CPU" Radio Button
  2793. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  2794. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  2795.  
  2796.  
  2797. // --- AI Difficulty Selection (Inside its own Group Box) ---
  2798. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  2799.  
  2800. // "Easy" Radio Button (First in the AI group)
  2801. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  2802. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  2803.  
  2804. // "Medium" Radio Button
  2805. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  2806. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  2807.  
  2808. // "Hard" Radio Button
  2809. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  2810. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  2811.  
  2812.  
  2813. // --- Standard Buttons ---
  2814. DEFPUSHBUTTON   "Start", IDOK, 55, 105, 50, 14 // Default button (Enter key)
  2815. PUSHBUTTON      "Cancel", IDCANCEL, 115, 105, 50, 14
  2816. END
  2817. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement