alien_fx_fiend

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

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