Advertisement
alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: Sound Playback Potential Fix V8

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