alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: ChatGPT Foul Fix (HotSwap 4 Gemini) V7

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