Advertisement
alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: xSounds + Embellishments V5

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