alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: Sounds V6

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