Advertisement
alien_fx_fiend

Direct2D 8-Ball Pool Using Vector Graphics: Ultimate Final Edition (Yahoo-Style ShotMeter TableFrame

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