alien_fx_fiend

Restore Point Save Before 8-Ball + Foul + CPU Aim/Pocket Bugs Are Fixed Tomorrow !!

Jun 30th, 2025 (edited)
890
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 202.18 KB | Source Code | 0 0
  1. ==++ Here's the full source for (file 1/3 (No OOP-based)) "Pool-Game-CloneV18.cpp"::: ++==
  2. ```Pool-Game-CloneV18.cpp
  3. #define WIN32_LEAN_AND_MEAN
  4. #define NOMINMAX
  5. #include <windows.h>
  6. #include <d2d1.h>
  7. #include <dwrite.h>
  8. #include <fstream> // For file I/O
  9. #include <iostream> // For some basic I/O, though not strictly necessary for just file ops
  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 <tchar.h> //midi func
  20. #include <thread>
  21. #include <atomic>
  22. #include "resource.h"
  23.  
  24. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  25. #pragma comment(lib, "d2d1.lib")
  26. #pragma comment(lib, "dwrite.lib")
  27. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  28.  
  29. // --- Constants ---
  30. const float PI = 3.1415926535f;
  31. const float BALL_RADIUS = 10.0f;
  32. const float TABLE_LEFT = 100.0f;
  33. const float TABLE_TOP = 100.0f;
  34. const float TABLE_WIDTH = 700.0f;
  35. const float TABLE_HEIGHT = 350.0f;
  36. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  37. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  38. const float CUSHION_THICKNESS = 20.0f;
  39. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  40. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  41. const float MAX_SHOT_POWER = 15.0f;
  42. const float FRICTION = 0.985f; // Friction factor per frame
  43. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  44. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  45. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  46. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  47. const UINT ID_TIMER = 1;
  48. const int TARGET_FPS = 60; // Target frames per second for timer
  49.  
  50. // --- Enums ---
  51. // --- MODIFIED/NEW Enums ---
  52. enum GameState {
  53.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  54.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  55.    BREAKING,           // Player is aiming/shooting the break shot
  56.    CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  57.    CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  58.    AIMING,             // Player is aiming
  59.    AI_THINKING,        // NEW: AI is calculating its move
  60.    SHOT_IN_PROGRESS,   // Balls are moving
  61.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  62.    PLAYER1_TURN,
  63.    PLAYER2_TURN,
  64.    BALL_IN_HAND_P1,
  65.    BALL_IN_HAND_P2,
  66.    GAME_OVER
  67. };
  68.  
  69. enum BallType {
  70.    NONE,
  71.    SOLID,  // Yellow (1-7)
  72.    STRIPE, // Red (9-15)
  73.    EIGHT_BALL, // Black (8)
  74.    CUE_BALL // White (0)
  75. };
  76.  
  77. // NEW Enums for Game Mode and AI Difficulty
  78. enum GameMode {
  79.    HUMAN_VS_HUMAN,
  80.    HUMAN_VS_AI
  81. };
  82.  
  83. enum AIDifficulty {
  84.    EASY,
  85.    MEDIUM,
  86.    HARD
  87. };
  88.  
  89. enum OpeningBreakMode {
  90.    CPU_BREAK,
  91.    P1_BREAK,
  92.    FLIP_COIN_BREAK
  93. };
  94.  
  95. // --- Structs ---
  96. struct Ball {
  97.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  98.    BallType type;
  99.    float x, y;
  100.    float vx, vy;
  101.    D2D1_COLOR_F color;
  102.    bool isPocketed;
  103. };
  104.  
  105. struct PlayerInfo {
  106.    BallType assignedType;
  107.    int ballsPocketedCount;
  108.    std::wstring name;
  109. };
  110.  
  111. // --- Global Variables ---
  112.  
  113. // Direct2D & DirectWrite
  114. ID2D1Factory* pFactory = nullptr;
  115. //ID2D1Factory* g_pD2DFactory = nullptr;
  116. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  117. IDWriteFactory* pDWriteFactory = nullptr;
  118. IDWriteTextFormat* pTextFormat = nullptr;
  119. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  120.  
  121. // Game State
  122. HWND hwndMain = nullptr;
  123. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  124. std::vector<Ball> balls;
  125. int currentPlayer = 1; // 1 or 2
  126. PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
  127. PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
  128. bool foulCommitted = false;
  129. std::wstring gameOverMessage = L"";
  130. bool firstBallPocketedAfterBreak = false;
  131. std::vector<int> pocketedThisTurn;
  132. // --- NEW: 8-Ball Pocket Call Globals ---
  133. int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  134. int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  135. int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  136. std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  137.  
  138. // --- NEW: Foul Tracking Globals ---
  139. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  140. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  141. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  142. // --- End New Foul Tracking Globals ---
  143.  
  144. // NEW Game Mode/AI Globals
  145. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  146. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  147. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  148. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  149. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  150. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  151. // NEW: Flag to indicate if the current shot is the opening break of the game
  152. bool isOpeningBreakShot = false;
  153.  
  154. // NEW: For AI shot planning and visualization
  155. struct AIPlannedShot {
  156.    float angle;
  157.    float power;
  158.    float spinX;
  159.    float spinY;
  160.    bool isValid; // Is there a valid shot planned?
  161. };
  162. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  163. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  164. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  165. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  166.  
  167. // Input & Aiming
  168. POINT ptMouse = { 0, 0 };
  169. bool isAiming = false;
  170. bool isDraggingCueBall = false;
  171. // --- ENSURE THIS LINE EXISTS HERE ---
  172. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  173. // --- End Ensure ---
  174. bool isSettingEnglish = false;
  175. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  176. float cueAngle = 0.0f;
  177. float shotPower = 0.0f;
  178. float cueSpinX = 0.0f; // Range -1 to 1
  179. float cueSpinY = 0.0f; // Range -1 to 1
  180. float pocketFlashTimer = 0.0f;
  181. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  182. int draggingBallId = -1;
  183. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  184. MCIDEVICEID midiDeviceID = 0; //midi func
  185. std::atomic<bool> isMusicPlaying(false); //midi func
  186. std::thread musicThread; //midi func
  187. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  188. void StopMidi();
  189.  
  190. // UI Element Positions
  191. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  192. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  193. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  194. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  195. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  196.  
  197. // Corrected Pocket Center Positions (aligned with table corners/edges)
  198. const D2D1_POINT_2F pocketPositions[6] = {
  199.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  200.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  201.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  202.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  203.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  204.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  205. };
  206.  
  207. // Colors
  208. 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)
  209. //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)
  210. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  211. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  212. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  213. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  214. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  215. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
  216. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red);   // Stripes = Red
  217. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  218. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  219. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  220. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  221. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  222. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  223.  
  224. // --- Forward Declarations ---
  225. HRESULT CreateDeviceResources();
  226. void DiscardDeviceResources();
  227. void OnPaint();
  228. void OnResize(UINT width, UINT height);
  229. void InitGame();
  230. void GameUpdate();
  231. void UpdatePhysics();
  232. void CheckCollisions();
  233. bool CheckPockets(); // Returns true if any ball was pocketed
  234. void ProcessShotResults();
  235. void ApplyShot(float power, float angle, float spinX, float spinY);
  236. void RespawnCueBall(bool behindHeadstring);
  237. bool AreBallsMoving();
  238. void SwitchTurns();
  239. bool AssignPlayerBallTypes(BallType firstPocketedType);
  240. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  241. Ball* GetBallById(int id);
  242. Ball* GetCueBall();
  243. //void PlayGameMusic(HWND hwnd); //midi func
  244. void AIBreakShot();
  245.  
  246. // Drawing Functions
  247. void DrawScene(ID2D1RenderTarget* pRT);
  248. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  249. void DrawBalls(ID2D1RenderTarget* pRT);
  250. void DrawCueStick(ID2D1RenderTarget* pRT);
  251. void DrawAimingAids(ID2D1RenderTarget* pRT);
  252. void DrawUI(ID2D1RenderTarget* pRT);
  253. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  254. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  255. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  256. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  257. // NEW
  258. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  259.  
  260. // Helper Functions
  261. float GetDistance(float x1, float y1, float x2, float y2);
  262. float GetDistanceSq(float x1, float y1, float x2, float y2);
  263. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  264. template <typename T> void SafeRelease(T** ppT);
  265. // --- NEW HELPER FORWARD DECLARATIONS ---
  266. bool IsPlayerOnEightBall(int player);
  267. void CheckAndTransitionToPocketChoice(int playerID);
  268. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  269. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  270. // --- End Forward Declaration ---
  271. 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
  272.  
  273. // --- NEW Forward Declarations ---
  274.  
  275. // AI Related
  276. struct AIShotInfo; // Define below
  277. void TriggerAIMove();
  278. void AIMakeDecision();
  279. void AIPlaceCueBall();
  280. AIShotInfo AIFindBestShot();
  281. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  282. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  283. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  284. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  285. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  286. bool IsValidAIAimAngle(float angle); // Basic check
  287.  
  288. // Dialog Related
  289. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  290. void ShowNewGameDialog(HINSTANCE hInstance);
  291. void LoadSettings(); // For deserialization
  292. void SaveSettings(); // For serialization
  293. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  294. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  295.  
  296. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  297. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  298.  
  299. // --- NEW Struct for AI Shot Evaluation ---
  300. struct AIShotInfo {
  301.     bool possible = false;          // Is this shot considered viable?
  302.     Ball* targetBall = nullptr;     // Which ball to hit
  303.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  304.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  305.     float angle = 0.0f;             // Calculated shot angle
  306.     float power = 0.0f;             // Calculated shot power
  307.     float score = -1.0f;            // Score for this shot (higher is better)
  308.     bool involves8Ball = false;     // Is the target the 8-ball?
  309. };
  310.  
  311. /*
  312. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  313. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  314. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  315. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  316. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  317. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  318. */
  319.  
  320. // --- NEW Settings Serialization Functions ---
  321. void SaveSettings() {
  322.     std::ofstream outFile(SETTINGS_FILE_NAME);
  323.     if (outFile.is_open()) {
  324.         outFile << static_cast<int>(gameMode) << std::endl;
  325.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  326.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  327.         outFile.close();
  328.     }
  329.     // else: Handle error, e.g., log or silently fail
  330. }
  331.  
  332. void LoadSettings() {
  333.     std::ifstream inFile(SETTINGS_FILE_NAME);
  334.     if (inFile.is_open()) {
  335.         int gm, aid, obm;
  336.         if (inFile >> gm) {
  337.             gameMode = static_cast<GameMode>(gm);
  338.         }
  339.         if (inFile >> aid) {
  340.             aiDifficulty = static_cast<AIDifficulty>(aid);
  341.         }
  342.         if (inFile >> obm) {
  343.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  344.         }
  345.         inFile.close();
  346.  
  347.         // Validate loaded settings (optional, but good practice)
  348.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  349.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  350.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  351.     }
  352.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  353. }
  354. // --- End Settings Serialization Functions ---
  355.  
  356. // --- NEW Dialog Procedure ---
  357. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  358.     switch (message) {
  359.     case WM_INITDIALOG:
  360.     {
  361.         // --- ACTION 4: Center Dialog Box ---
  362. // Optional: Force centering if default isn't working
  363.         RECT rcDlg, rcOwner, rcScreen;
  364.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  365.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  366.  
  367.         GetWindowRect(hwndOwner, &rcOwner);
  368.         GetWindowRect(hDlg, &rcDlg);
  369.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  370.  
  371.         // Offset the owner rect relative to the screen if it's not the desktop
  372.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  373.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  374.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  375.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  376.         }
  377.  
  378.  
  379.         // Calculate centered position
  380.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  381.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  382.  
  383.         // Ensure it stays within screen bounds (optional safety)
  384.         x = std::max(static_cast<int>(rcScreen.left), x);
  385.         y = std::max(static_cast<int>(rcScreen.top), y);
  386.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  387.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  388.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  389.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  390.  
  391.  
  392.         // Set the dialog position
  393.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  394.  
  395.         // --- End Centering Code ---
  396.  
  397.         // Set initial state based on current global settings (or defaults)
  398.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  399.  
  400.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  401.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  402.  
  403.         // Enable/Disable AI group based on initial mode
  404.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  405.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  406.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  407.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  408.         // Set initial state for Opening Break Mode
  409.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  410.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  411.         // Enable/Disable Opening Break group based on initial mode
  412.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  413.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  414.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  415.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  416.     }
  417.     return (INT_PTR)TRUE;
  418.  
  419.     case WM_COMMAND:
  420.         switch (LOWORD(wParam)) {
  421.         case IDC_RADIO_2P:
  422.         case IDC_RADIO_CPU:
  423.         {
  424.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  425.             // Enable/Disable AI group controls based on selection
  426.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  427.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  428.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  429.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  430.             // Also enable/disable Opening Break Mode group
  431.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  432.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  433.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  434.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  435.         }
  436.         return (INT_PTR)TRUE;
  437.  
  438.         case IDOK:
  439.             // Retrieve selected options and store in global variables
  440.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  441.                 gameMode = HUMAN_VS_AI;
  442.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  443.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  444.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  445.  
  446.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  447.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  448.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  449.             }
  450.             else {
  451.                 gameMode = HUMAN_VS_HUMAN;
  452.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  453.             }
  454.             SaveSettings(); // Save settings when OK is pressed
  455.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  456.             return (INT_PTR)TRUE;
  457.  
  458.         case IDCANCEL: // Handle Cancel or closing the dialog
  459.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  460.             EndDialog(hDlg, IDCANCEL);
  461.             return (INT_PTR)TRUE;
  462.         }
  463.         break; // End WM_COMMAND
  464.     }
  465.     return (INT_PTR)FALSE; // Default processing
  466. }
  467.  
  468. // --- NEW Helper to Show Dialog ---
  469. void ShowNewGameDialog(HINSTANCE hInstance) {
  470.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  471.         // User clicked Start, reset game with new settings
  472.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  473.         if (isPlayer2AI) {
  474.             switch (aiDifficulty) {
  475.             case EASY: player2Info.name = L"CPU (Easy)"; break;
  476.             case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  477.             case HARD: player2Info.name = L"CPU (Hard)"; break;
  478.             }
  479.         }
  480.         else {
  481.             player2Info.name = L"Player 2";
  482.         }
  483.         // Update window title
  484.         std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  485.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  486.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  487.         SetWindowText(hwndMain, windowTitle.c_str());
  488.  
  489.         InitGame(); // Re-initialize game logic & board
  490.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  491.     }
  492.     else {
  493.         // User cancelled dialog - maybe just resume game? Or exit?
  494.         // For simplicity, we do nothing, game continues as it was.
  495.         // To exit on cancel from F2, would need more complex state management.
  496.     }
  497. }
  498.  
  499. // --- NEW Reset Game Function ---
  500. void ResetGame(HINSTANCE hInstance) {
  501.     // Call the helper function to show the dialog and re-init if OK clicked
  502.     ShowNewGameDialog(hInstance);
  503. }
  504.  
  505. // --- WinMain ---
  506. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  507.     if (FAILED(CoInitialize(NULL))) {
  508.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  509.         return -1;
  510.     }
  511.  
  512.     // --- NEW: Load settings at startup ---
  513.     LoadSettings();
  514.  
  515.     // --- NEW: Show configuration dialog FIRST ---
  516.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  517.         // User cancelled the dialog
  518.         CoUninitialize();
  519.         return 0; // Exit gracefully if dialog cancelled
  520.     }
  521.     // Global gameMode and aiDifficulty are now set by the DialogProc
  522.  
  523.     // Set AI flag based on game mode
  524.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  525.     if (isPlayer2AI) {
  526.         switch (aiDifficulty) {
  527.         case EASY: player2Info.name = L"CPU (Easy)"; break;
  528.         case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  529.         case HARD: player2Info.name = L"CPU (Hard)"; break;
  530.         }
  531.     }
  532.     else {
  533.         player2Info.name = L"Player 2";
  534.     }
  535.     // --- End of Dialog Logic ---
  536.  
  537.  
  538.     WNDCLASS wc = { };
  539.     wc.lpfnWndProc = WndProc;
  540.     wc.hInstance = hInstance;
  541.     wc.lpszClassName = L"Direct2D_8BallPool";
  542.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  543.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  544.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  545.  
  546.     if (!RegisterClass(&wc)) {
  547.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  548.         CoUninitialize();
  549.         return -1;
  550.     }
  551.  
  552.     // --- ACTION 4: Calculate Centered Window Position ---
  553.     const int WINDOW_WIDTH = 1000; // Define desired width
  554.     const int WINDOW_HEIGHT = 700; // Define desired height
  555.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  556.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  557.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  558.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  559.  
  560.     // --- Change Window Title based on mode ---
  561.     std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  562.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  563.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  564.  
  565.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  566.  
  567.     hwndMain = CreateWindowEx(
  568.         0, L"Direct2D_8BallPool", windowTitle.c_str(), dwStyle,
  569.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  570.         NULL, NULL, hInstance, NULL
  571.     );
  572.  
  573.     if (!hwndMain) {
  574.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  575.         CoUninitialize();
  576.         return -1;
  577.     }
  578.  
  579.     // Initialize Direct2D Resources AFTER window creation
  580.     if (FAILED(CreateDeviceResources())) {
  581.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  582.         DestroyWindow(hwndMain);
  583.         CoUninitialize();
  584.         return -1;
  585.     }
  586.  
  587.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  588.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  589.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  590.     //PlayGameMusic(hwndMain); //midi func
  591.  
  592.     ShowWindow(hwndMain, nCmdShow);
  593.     UpdateWindow(hwndMain);
  594.  
  595.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  596.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  597.         DestroyWindow(hwndMain);
  598.         CoUninitialize();
  599.         return -1;
  600.     }
  601.  
  602.     MSG msg = { };
  603.     // --- Modified Main Loop ---
  604.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  605.     // or gets reset to it via F2. The main loop runs normally once game starts.
  606.     while (GetMessage(&msg, NULL, 0, 0)) {
  607.         // We might need modeless dialog handling here if F2 shows dialog
  608.         // while window is active, but DialogBoxParam is modal.
  609.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  610.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  611.         TranslateMessage(&msg);
  612.         DispatchMessage(&msg);
  613.     }
  614.  
  615.  
  616.     KillTimer(hwndMain, ID_TIMER);
  617.     DiscardDeviceResources();
  618.     SaveSettings(); // Save settings on exit
  619.     CoUninitialize();
  620.  
  621.     return (int)msg.wParam;
  622. }
  623.  
  624. // --- WndProc ---
  625. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  626.     // Declare cueBall pointer once at the top, used in multiple cases
  627.     // For clarity, often better to declare within each case where needed.
  628.     Ball* cueBall = nullptr; // Initialize to nullptr
  629.     switch (msg) {
  630.     case WM_CREATE:
  631.         // Resources are now created in WinMain after CreateWindowEx
  632.         return 0;
  633.  
  634.     case WM_PAINT:
  635.         OnPaint();
  636.         // Validate the entire window region after painting
  637.         ValidateRect(hwnd, NULL);
  638.         return 0;
  639.  
  640.     case WM_SIZE: {
  641.         UINT width = LOWORD(lParam);
  642.         UINT height = HIWORD(lParam);
  643.         OnResize(width, height);
  644.         return 0;
  645.     }
  646.  
  647.     case WM_TIMER:
  648.         if (wParam == ID_TIMER) {
  649.             GameUpdate(); // Update game logic and physics
  650.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  651.         }
  652.         return 0;
  653.  
  654.         // --- NEW: Handle F2 Key for Reset ---
  655.         // --- MODIFIED: Handle More Keys ---
  656.     case WM_KEYDOWN:
  657.     { // Add scope for variable declarations
  658.  
  659.         // --- FIX: Get Cue Ball pointer for this scope ---
  660.         cueBall = GetCueBall();
  661.         // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
  662.         // --- End Fix ---
  663.  
  664.         // Check which player can interact via keyboard (Humans only)
  665.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  666.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  667.  
  668.         // --- F1 / F2 Keys (Always available) ---
  669.         if (wParam == VK_F2) {
  670.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  671.             ResetGame(hInstance); // Call reset function
  672.             return 0; // Indicate key was processed
  673.         }
  674.         else if (wParam == VK_F1) {
  675.             MessageBox(hwnd,
  676.                 L"Direct2D-based StickPool game made in C++ from scratch (2764+ lines of code)\n" // Update line count if needed
  677.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  678.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  679.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions.\n"
  680.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  681.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  682.             return 0; // Indicate key was processed
  683.         }
  684.  
  685.         // Check for 'M' key (uppercase or lowercase)
  686.             // Toggle music with "M"
  687.         if (wParam == 'M' || wParam == 'm') {
  688.             //static bool isMusicPlaying = false;
  689.             if (isMusicPlaying) {
  690.                 // Stop the music
  691.                 StopMidi();
  692.                 isMusicPlaying = false;
  693.             }
  694.             else {
  695.                 // Build the MIDI file path
  696.                 TCHAR midiPath[MAX_PATH];
  697.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  698.                 // Keep only the directory part
  699.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  700.                 if (lastBackslash != NULL) {
  701.                     *(lastBackslash + 1) = '\0';
  702.                 }
  703.                 // Append the MIDI filename
  704.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
  705.  
  706.                 // Start playing MIDI
  707.                 StartMidi(hwndMain, midiPath);
  708.                 isMusicPlaying = true;
  709.             }
  710.         }
  711.  
  712.  
  713.         // --- Player Interaction Keys (Only if allowed) ---
  714.         if (canPlayerControl) {
  715.             // --- Get Shift Key State ---
  716.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  717.             float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
  718.             float powerStep = 0.2f; // Power step (Adjust as needed)
  719.  
  720.             switch (wParam) {
  721.             case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
  722.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  723.                     cueAngle -= angleStep;
  724.                     // Normalize angle (keep between 0 and 2*PI)
  725.                     if (cueAngle < 0) cueAngle += 2 * PI;
  726.                     // Ensure state shows aiming visuals if turn just started
  727.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  728.                     isAiming = false; // Keyboard adjust doesn't use mouse aiming state
  729.                     isDraggingStick = false;
  730.                     keyboardAimingActive = true;
  731.                 }
  732.                 break;
  733.  
  734.             case VK_RIGHT: // Rotate Cue Stick Clockwise
  735.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  736.                     cueAngle += angleStep;
  737.                     // Normalize angle (keep between 0 and 2*PI)
  738.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  739.                     // Ensure state shows aiming visuals if turn just started
  740.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  741.                     isAiming = false;
  742.                     isDraggingStick = false;
  743.                     keyboardAimingActive = true;
  744.                 }
  745.                 break;
  746.  
  747.             case VK_UP: // Decrease Shot Power
  748.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  749.                     shotPower -= powerStep;
  750.                     if (shotPower < 0.0f) shotPower = 0.0f;
  751.                     // Ensure state shows aiming visuals if turn just started
  752.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  753.                     isAiming = true; // Keyboard adjust doesn't use mouse aiming state
  754.                     isDraggingStick = false;
  755.                     keyboardAimingActive = true;
  756.                 }
  757.                 break;
  758.  
  759.             case VK_DOWN: // Increase Shot Power
  760.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  761.                     shotPower += powerStep;
  762.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  763.                     // Ensure state shows aiming visuals if turn just started
  764.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  765.                     isAiming = true;
  766.                     isDraggingStick = false;
  767.                     keyboardAimingActive = true;
  768.                 }
  769.                 break;
  770.  
  771.             case VK_SPACE: // Trigger Shot
  772.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  773.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  774.                 {
  775.                     if (shotPower > 0.15f) { // Use same threshold as mouse
  776.                        // Reset foul flags BEFORE applying shot
  777.                         firstHitBallIdThisShot = -1;
  778.                         cueHitObjectBallThisShot = false;
  779.                         railHitAfterContact = false;
  780.  
  781.                         // Play sound & Apply Shot
  782.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  783.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  784.  
  785.                         // Update State
  786.                         currentGameState = SHOT_IN_PROGRESS;
  787.                         foulCommitted = false;
  788.                         pocketedThisTurn.clear();
  789.                         shotPower = 0; // Reset power after shooting
  790.                         isAiming = false; isDraggingStick = false; // Reset aiming flags
  791.                         keyboardAimingActive = false;
  792.                     }
  793.                 }
  794.                 break;
  795.  
  796.             case VK_ESCAPE: // Cancel Aim/Shot Setup
  797.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  798.                 {
  799.                     shotPower = 0.0f;
  800.                     isAiming = false;
  801.                     isDraggingStick = false;
  802.                     keyboardAimingActive = false;
  803.                     // Revert to basic turn state if not breaking
  804.                     if (currentGameState != BREAKING) {
  805.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  806.                     }
  807.                 }
  808.                 break;
  809.  
  810.             case 'G': // Toggle Cheat Mode
  811.                 cheatModeEnabled = !cheatModeEnabled;
  812.                 if (cheatModeEnabled)
  813.                     MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
  814.                 else
  815.                     MessageBeep(MB_OK); // Play a different beep when disabling
  816.                 break;
  817.  
  818.             default:
  819.                 // Allow default processing for other keys if needed
  820.                 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
  821.                 break;
  822.             } // End switch(wParam) for player controls
  823.             return 0; // Indicate player control key was processed
  824.         } // End if(canPlayerControl)
  825.     } // End scope for WM_KEYDOWN case
  826.     // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
  827.     // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
  828.     return 0;
  829.  
  830.     case WM_MOUSEMOVE: {
  831.         ptMouse.x = LOWORD(lParam);
  832.         ptMouse.y = HIWORD(lParam);
  833.  
  834.         // --- NEW LOGIC: Handle Pocket Hover ---
  835.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  836.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  837.             int oldHover = currentlyHoveredPocket;
  838.             currentlyHoveredPocket = -1; // Reset
  839.             for (int i = 0; i < 6; ++i) {
  840.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  841.                     currentlyHoveredPocket = i;
  842.                     break;
  843.                 }
  844.             }
  845.             if (oldHover != currentlyHoveredPocket) {
  846.                 InvalidateRect(hwnd, NULL, FALSE);
  847.             }
  848.             // Do NOT return 0 here, allow normal mouse angle update to continue
  849.         }
  850.         // --- END NEW LOGIC ---
  851.  
  852.  
  853.         cueBall = GetCueBall(); // Declare and get cueBall pointer
  854.  
  855.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  856.             Ball* ball = GetBallById(draggingBallId);
  857.             if (ball) {
  858.                 ball->x = (float)ptMouse.x;
  859.                 ball->y = (float)ptMouse.y;
  860.                 ball->vx = ball->vy = 0.0f;
  861.             }
  862.             return 0;
  863.         }
  864.  
  865.         if (!cueBall) return 0;
  866.  
  867.         // Update Aiming Logic (Check player turn)
  868.         if (isDraggingCueBall &&
  869.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  870.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  871.                 currentGameState == PRE_BREAK_PLACEMENT))
  872.         {
  873.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  874.             // Tentative position update
  875.             cueBall->x = (float)ptMouse.x;
  876.             cueBall->y = (float)ptMouse.y;
  877.             cueBall->vx = cueBall->vy = 0;
  878.         }
  879.         else if ((isAiming || isDraggingStick) &&
  880.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  881.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  882.         {
  883.             //NEW2 MOUSEBOUND CODE = START
  884.                 /*// Clamp mouse inside table bounds during aiming
  885.                 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
  886.             if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
  887.             if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
  888.             if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
  889.             //NEW2 MOUSEBOUND CODE = END
  890.             // Aiming drag updates angle and power
  891.             float dx = (float)ptMouse.x - cueBall->x;
  892.             float dy = (float)ptMouse.y - cueBall->y;
  893.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  894.             //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  895.             //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  896.             if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
  897.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  898.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  899.             }
  900.         }
  901.         else if (isSettingEnglish &&
  902.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  903.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  904.         {
  905.             // Setting English
  906.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  907.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  908.             float dist = GetDistance(dx, dy, 0, 0);
  909.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  910.             cueSpinX = dx / spinIndicatorRadius;
  911.             cueSpinY = dy / spinIndicatorRadius;
  912.         }
  913.         else {
  914.             //DISABLE PERM AIMING = START
  915.             /*// Update visual angle even when not aiming/dragging (Check player turn)
  916.             bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
  917.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
  918.                 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
  919.  
  920.             if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
  921.             {
  922.                 // NEW MOUSEBOUND CODE = START
  923.                     // Only update cue angle if mouse is inside the playable table area
  924.                 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
  925.                     ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
  926.                 {
  927.                     // NEW MOUSEBOUND CODE = END
  928.                     Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
  929.                     if (cb) {
  930.                         float dx = (float)ptMouse.x - cb->x;
  931.                         float dy = (float)ptMouse.y - cb->y;
  932.                         if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  933.                     }
  934.                 } //NEW MOUSEBOUND CODE LINE = DISABLE
  935.             }*/
  936.             //DISABLE PERM AIMING = END
  937.         }
  938.         return 0;
  939.     } // End WM_MOUSEMOVE
  940.  
  941.     case WM_LBUTTONDOWN: {
  942.         ptMouse.x = LOWORD(lParam);
  943.         ptMouse.y = HIWORD(lParam);
  944.  
  945.         // --- NEW LOGIC: Handle Pocket Selection First ---
  946.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  947.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  948.  
  949.             int clickedPocketIndex = -1;
  950.             for (int i = 0; i < 6; ++i) {
  951.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  952.                     clickedPocketIndex = i;
  953.                     break;
  954.                 }
  955.             }
  956.  
  957.             if (clickedPocketIndex != -1) { // Player clicked on a pocket
  958.                 // FIX: Update the called pocket, but DO NOT change the game state.
  959.                 // This allows the player to click another pocket to change their mind.
  960.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  961.                 else calledPocketP2 = clickedPocketIndex;
  962.                 InvalidateRect(hwnd, NULL, FALSE); // Redraw to show updated arrow
  963.                 return 0; // Consume the click and stay in CHOOSING_POCKET state
  964.             }
  965.  
  966.             // FIX: Add new logic to CONFIRM the choice by clicking the cue ball.
  967.             Ball* cueBall = GetCueBall();
  968.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  969.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  970.                 // A pocket has been selected, and the player now clicks the cue ball.
  971.                 // NOW we transition to the normal aiming state.
  972.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  973.                 pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  974.                 isAiming = true; // Prepare for aiming
  975.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable
  976.                 return 0;
  977.             }
  978.  
  979.             // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  980.             return 0;
  981.         }
  982.         // --- END NEW LOGIC ---
  983.  
  984.  
  985.         if (cheatModeEnabled) {
  986.             // Allow dragging any ball freely
  987.             for (Ball& ball : balls) {
  988.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  989.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
  990.                     isDraggingCueBall = true;
  991.                     draggingBallId = ball.id;
  992.                     if (ball.id == 0) {
  993.                         // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
  994.                         if (currentPlayer == 1)
  995.                             currentGameState = BALL_IN_HAND_P1;
  996.                         else if (currentPlayer == 2 && !isPlayer2AI)
  997.                             currentGameState = BALL_IN_HAND_P2;
  998.                     }
  999.                     return 0;
  1000.                 }
  1001.             }
  1002.         }
  1003.  
  1004.         Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer            
  1005.  
  1006.         // Check which player is allowed to interact via mouse click
  1007.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  1008.         // Define states where interaction is generally allowed
  1009.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  1010.             currentGameState == AIMING || currentGameState == BREAKING ||
  1011.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  1012.             currentGameState == PRE_BREAK_PLACEMENT);
  1013.  
  1014.         // Check Spin Indicator first (Allow if player's turn/aim phase)
  1015.         if (canPlayerClickInteract && canInteractState) {
  1016.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  1017.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  1018.                 isSettingEnglish = true;
  1019.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1020.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1021.                 float dist = GetDistance(dx, dy, 0, 0);
  1022.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1023.                 cueSpinX = dx / spinIndicatorRadius;
  1024.                 cueSpinY = dy / spinIndicatorRadius;
  1025.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  1026.                 return 0;
  1027.             }
  1028.         }
  1029.  
  1030.         if (!cueBall) return 0;
  1031.  
  1032.         // Check Ball-in-Hand placement/drag
  1033.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1034.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  1035.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1036.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1037.                 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
  1038.  
  1039.         if (isPlayerAllowedToPlace) {
  1040.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1041.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  1042.                 isDraggingCueBall = true;
  1043.                 isAiming = false; isDraggingStick = false;
  1044.             }
  1045.             else {
  1046.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1047.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  1048.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  1049.                     cueBall->vx = 0; cueBall->vy = 0;
  1050.                     isDraggingCueBall = false;
  1051.                     // Transition state
  1052.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1053.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1054.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1055.                     cueAngle = 0.0f;
  1056.                 }
  1057.             }
  1058.             return 0;
  1059.         }
  1060.  
  1061.         // Check for starting Aim (Cue Ball OR Stick)
  1062.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  1063.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  1064.  
  1065.         if (canAim) {
  1066.             const float stickDrawLength = 150.0f * 1.4f;
  1067.             float currentStickAngle = cueAngle + PI;
  1068.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  1069.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  1070.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  1071.             float stickClickThresholdSq = 36.0f;
  1072.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1073.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  1074.  
  1075.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  1076.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  1077.  
  1078.             if (clickedStick || clickedCueArea) {
  1079.                 isDraggingStick = clickedStick && !clickedCueArea;
  1080.                 isAiming = clickedCueArea;
  1081.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1082.                 shotPower = 0;
  1083.                 float dx = (float)ptMouse.x - cueBall->x;
  1084.                 float dy = (float)ptMouse.y - cueBall->y;
  1085.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1086.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  1087.             }
  1088.         }
  1089.         return 0;
  1090.     } // End WM_LBUTTONDOWN
  1091.  
  1092.  
  1093.     case WM_LBUTTONUP: {
  1094.         if (cheatModeEnabled && draggingBallId != -1) {
  1095.             Ball* b = GetBallById(draggingBallId);
  1096.             if (b) {
  1097.                 for (int p = 0; p < 6; ++p) {
  1098.                     float dx = b->x - pocketPositions[p].x;
  1099.                     float dy = b->y - pocketPositions[p].y;
  1100.                     if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1101.                         // --- Assign ball type on first cheat-pocket if table still open ---
  1102.                         if (player1Info.assignedType == BallType::NONE
  1103.                             && player2Info.assignedType == BallType::NONE
  1104.                             && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  1105.                         {
  1106.                             AssignPlayerBallTypes(b->type);
  1107.                         }
  1108.                         b->isPocketed = true;
  1109.                         pocketedThisTurn.push_back(b->id);
  1110.                         // Immediately increment that player's count (skip cue/8)
  1111.                         if (b->id != 0 && b->id != 8) {
  1112.                             if (currentPlayer == 1)
  1113.                                 player1Info.ballsPocketedCount++;
  1114.                             else
  1115.                                 player2Info.ballsPocketedCount++;
  1116.                         }
  1117.                         break;
  1118.                     }
  1119.                 }
  1120.             }
  1121.         }
  1122.  
  1123.         ptMouse.x = LOWORD(lParam);
  1124.         ptMouse.y = HIWORD(lParam);
  1125.  
  1126.         Ball* cueBall = GetCueBall(); // Get cueBall pointer
  1127.  
  1128.         // Check for releasing aim drag (Stick OR Cue Ball)
  1129.         if ((isAiming || isDraggingStick) &&
  1130.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  1131.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  1132.         {
  1133.             bool wasAiming = isAiming;
  1134.             bool wasDraggingStick = isDraggingStick;
  1135.             isAiming = false; isDraggingStick = false;
  1136.  
  1137.             if (shotPower > 0.15f) { // Check power threshold
  1138.                 if (currentGameState != AI_THINKING) {
  1139.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
  1140.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1141.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  1142.                     currentGameState = SHOT_IN_PROGRESS;
  1143.                     foulCommitted = false; pocketedThisTurn.clear();
  1144.                 }
  1145.             }
  1146.             else if (currentGameState != AI_THINKING) { // Revert state if power too low
  1147.                 if (currentGameState == BREAKING) { /* Still breaking */ }
  1148.                 else {
  1149.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1150.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  1151.                 }
  1152.             }
  1153.             shotPower = 0; // Reset power indicator regardless
  1154.         }
  1155.  
  1156.         // Handle releasing cue ball drag (placement)
  1157.         if (isDraggingCueBall) {
  1158.             isDraggingCueBall = false;
  1159.             // Check player allowed to place
  1160.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1161.             bool isPlayerAllowed = (isPlacingState &&
  1162.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1163.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1164.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  1165.  
  1166.             if (isPlayerAllowed && cueBall) {
  1167.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1168.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  1169.                     // Finalize position already set by mouse move
  1170.                     // Transition state
  1171.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1172.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1173.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1174.                     cueAngle = 0.0f;
  1175.                 }
  1176.                 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
  1177.             }
  1178.         }
  1179.  
  1180.         // Handle releasing english setting
  1181.         if (isSettingEnglish) {
  1182.             isSettingEnglish = false;
  1183.         }
  1184.         return 0;
  1185.     } // End WM_LBUTTONUP
  1186.  
  1187.     case WM_DESTROY:
  1188.         isMusicPlaying = false;
  1189.         if (midiDeviceID != 0) {
  1190.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  1191.             midiDeviceID = 0;
  1192.             SaveSettings(); // Save settings on exit
  1193.         }
  1194.         PostQuitMessage(0);
  1195.         return 0;
  1196.  
  1197.     default:
  1198.         return DefWindowProc(hwnd, msg, wParam, lParam);
  1199.     }
  1200.     return 0;
  1201. }
  1202.  
  1203. // --- Direct2D Resource Management ---
  1204.  
  1205. HRESULT CreateDeviceResources() {
  1206.     HRESULT hr = S_OK;
  1207.  
  1208.     // Create Direct2D Factory
  1209.     if (!pFactory) {
  1210.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  1211.         if (FAILED(hr)) return hr;
  1212.     }
  1213.  
  1214.     // Create DirectWrite Factory
  1215.     if (!pDWriteFactory) {
  1216.         hr = DWriteCreateFactory(
  1217.             DWRITE_FACTORY_TYPE_SHARED,
  1218.             __uuidof(IDWriteFactory),
  1219.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  1220.         );
  1221.         if (FAILED(hr)) return hr;
  1222.     }
  1223.  
  1224.     // Create Text Formats
  1225.     if (!pTextFormat && pDWriteFactory) {
  1226.         hr = pDWriteFactory->CreateTextFormat(
  1227.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1228.             16.0f, L"en-us", &pTextFormat
  1229.         );
  1230.         if (FAILED(hr)) return hr;
  1231.         // Center align text
  1232.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1233.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1234.     }
  1235.     if (!pLargeTextFormat && pDWriteFactory) {
  1236.         hr = pDWriteFactory->CreateTextFormat(
  1237.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1238.             48.0f, L"en-us", &pLargeTextFormat
  1239.         );
  1240.         if (FAILED(hr)) return hr;
  1241.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  1242.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1243.     }
  1244.  
  1245.  
  1246.     // Create Render Target (needs valid hwnd)
  1247.     if (!pRenderTarget && hwndMain) {
  1248.         RECT rc;
  1249.         GetClientRect(hwndMain, &rc);
  1250.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  1251.  
  1252.         hr = pFactory->CreateHwndRenderTarget(
  1253.             D2D1::RenderTargetProperties(),
  1254.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  1255.             &pRenderTarget
  1256.         );
  1257.         if (FAILED(hr)) {
  1258.             // If failed, release factories if they were created in this call
  1259.             SafeRelease(&pTextFormat);
  1260.             SafeRelease(&pLargeTextFormat);
  1261.             SafeRelease(&pDWriteFactory);
  1262.             SafeRelease(&pFactory);
  1263.             pRenderTarget = nullptr; // Ensure it's null on failure
  1264.             return hr;
  1265.         }
  1266.     }
  1267.  
  1268.     return hr;
  1269. }
  1270.  
  1271. void DiscardDeviceResources() {
  1272.     SafeRelease(&pRenderTarget);
  1273.     SafeRelease(&pTextFormat);
  1274.     SafeRelease(&pLargeTextFormat);
  1275.     SafeRelease(&pDWriteFactory);
  1276.     // Keep pFactory until application exit? Or release here too? Let's release.
  1277.     SafeRelease(&pFactory);
  1278. }
  1279.  
  1280. void OnResize(UINT width, UINT height) {
  1281.     if (pRenderTarget) {
  1282.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  1283.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  1284.     }
  1285. }
  1286.  
  1287. // --- Game Initialization ---
  1288. void InitGame() {
  1289.     srand((unsigned int)time(NULL)); // Seed random number generator
  1290.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  1291.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  1292.     aiIsDisplayingAim = false;
  1293.     aiAimDisplayFramesLeft = 0;
  1294.     // ... (rest of InitGame())
  1295.  
  1296.     // --- Ensure pocketed list is clear from the absolute start ---
  1297.     pocketedThisTurn.clear();
  1298.  
  1299.     balls.clear(); // Clear existing balls
  1300.  
  1301.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  1302.     player1Info.assignedType = BallType::NONE;
  1303.     player1Info.ballsPocketedCount = 0;
  1304.     // Player 1 Name usually remains "Player 1"
  1305.     player2Info.assignedType = BallType::NONE;
  1306.     player2Info.ballsPocketedCount = 0;
  1307.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  1308.  
  1309.     // Create Cue Ball (ID 0)
  1310.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  1311.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  1312.  
  1313.     // --- Create Object Balls (Temporary List) ---
  1314.     std::vector<Ball> objectBalls;
  1315.     // Solids (1-7, Yellow)
  1316.     for (int i = 1; i <= 7; ++i) {
  1317.         objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  1318.     }
  1319.     // Stripes (9-15, Red)
  1320.     for (int i = 9; i <= 15; ++i) {
  1321.         objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  1322.     }
  1323.     // 8-Ball (ID 8) - Add it to the list to be placed
  1324.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  1325.  
  1326.  
  1327.     // --- Racking Logic (Improved) ---
  1328.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  1329.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  1330.  
  1331.     // Define rack positions (0-14 indices corresponding to triangle spots)
  1332.     D2D1_POINT_2F rackPositions[15];
  1333.     int rackIndex = 0;
  1334.     for (int row = 0; row < 5; ++row) {
  1335.         for (int col = 0; col <= row; ++col) {
  1336.             if (rackIndex >= 15) break;
  1337.             float x = RACK_POS_X + row * spacingX;
  1338.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  1339.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  1340.         }
  1341.     }
  1342.  
  1343.     // Separate 8-ball
  1344.     Ball eightBall;
  1345.     std::vector<Ball> otherBalls; // Solids and Stripes
  1346.     bool eightBallFound = false;
  1347.     for (const auto& ball : objectBalls) {
  1348.         if (ball.id == 8) {
  1349.             eightBall = ball;
  1350.             eightBallFound = true;
  1351.         }
  1352.         else {
  1353.             otherBalls.push_back(ball);
  1354.         }
  1355.     }
  1356.     // Ensure 8 ball was actually created (should always be true)
  1357.     if (!eightBallFound) {
  1358.         // Handle error - perhaps recreate it? For now, proceed.
  1359.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  1360.     }
  1361.  
  1362.  
  1363.     // Shuffle the other 14 balls
  1364.     // Use std::shuffle if available (C++11 and later) for better randomness
  1365.     // std::random_device rd;
  1366.     // std::mt19937 g(rd());
  1367.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  1368.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  1369.  
  1370.     // --- Place balls into the main 'balls' vector in rack order ---
  1371.     // Important: Add the cue ball (already created) first.
  1372.     // (Cue ball added at the start of the function now)
  1373.  
  1374.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  1375.     int eightBallRackIndex = 4;
  1376.     eightBall.x = rackPositions[eightBallRackIndex].x;
  1377.     eightBall.y = rackPositions[eightBallRackIndex].y;
  1378.     eightBall.vx = 0;
  1379.     eightBall.vy = 0;
  1380.     eightBall.isPocketed = false;
  1381.     balls.push_back(eightBall); // Add 8 ball to the main vector
  1382.  
  1383.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  1384.     size_t otherBallIdx = 0;
  1385.     //int otherBallIdx = 0;
  1386.     for (int i = 0; i < 15; ++i) {
  1387.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  1388.  
  1389.         if (otherBallIdx < otherBalls.size()) {
  1390.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  1391.             ballToPlace.x = rackPositions[i].x;
  1392.             ballToPlace.y = rackPositions[i].y;
  1393.             ballToPlace.vx = 0;
  1394.             ballToPlace.vy = 0;
  1395.             ballToPlace.isPocketed = false;
  1396.             balls.push_back(ballToPlace); // Add to the main game vector
  1397.         }
  1398.     }
  1399.     // --- End Racking Logic ---
  1400.  
  1401.  
  1402.     // --- Determine Who Breaks and Initial State ---
  1403.     if (isPlayer2AI) {
  1404.         /*// AI Mode: Randomly decide who breaks
  1405.         if ((rand() % 2) == 0) {
  1406.             // AI (Player 2) breaks
  1407.             currentPlayer = 2;
  1408.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  1409.             aiTurnPending = true; // Trigger AI logic
  1410.         }
  1411.         else {
  1412.             // Player 1 (Human) breaks
  1413.             currentPlayer = 1;
  1414.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  1415.             aiTurnPending = false;*/
  1416.         switch (openingBreakMode) {
  1417.         case CPU_BREAK:
  1418.             currentPlayer = 2; // AI breaks
  1419.             currentGameState = PRE_BREAK_PLACEMENT;
  1420.             aiTurnPending = true;
  1421.             break;
  1422.         case P1_BREAK:
  1423.             currentPlayer = 1; // Player 1 breaks
  1424.             currentGameState = PRE_BREAK_PLACEMENT;
  1425.             aiTurnPending = false;
  1426.             break;
  1427.         case FLIP_COIN_BREAK:
  1428.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  1429.                 currentPlayer = 2; // AI breaks
  1430.                 currentGameState = PRE_BREAK_PLACEMENT;
  1431.                 aiTurnPending = true;
  1432.             }
  1433.             else {
  1434.                 currentPlayer = 1; // Player 1 breaks
  1435.                 currentGameState = PRE_BREAK_PLACEMENT;
  1436.                 aiTurnPending = false;
  1437.             }
  1438.             break;
  1439.         default: // Fallback to CPU break
  1440.             currentPlayer = 2;
  1441.             currentGameState = PRE_BREAK_PLACEMENT;
  1442.             aiTurnPending = true;
  1443.             break;
  1444.         }
  1445.     }
  1446.     else {
  1447.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  1448.         currentPlayer = 1;
  1449.         currentGameState = PRE_BREAK_PLACEMENT;
  1450.         aiTurnPending = false; // No AI involved
  1451.     }
  1452.  
  1453.     // Reset other relevant game state variables
  1454.     foulCommitted = false;
  1455.     gameOverMessage = L"";
  1456.     firstBallPocketedAfterBreak = false;
  1457.     // pocketedThisTurn cleared at start
  1458.     // Reset shot parameters and input flags
  1459.     shotPower = 0.0f;
  1460.     cueSpinX = 0.0f;
  1461.     cueSpinY = 0.0f;
  1462.     isAiming = false;
  1463.     isDraggingCueBall = false;
  1464.     isSettingEnglish = false;
  1465.     cueAngle = 0.0f; // Reset aim angle
  1466. }
  1467.  
  1468.  
  1469. // --- Game Loop ---
  1470. void GameUpdate() {
  1471.     if (currentGameState == SHOT_IN_PROGRESS) {
  1472.         UpdatePhysics();
  1473.         CheckCollisions();
  1474.  
  1475.         if (AreBallsMoving()) {
  1476.             // When all balls stop, clear aiming flags
  1477.             isAiming = false;
  1478.             aiIsDisplayingAim = false;
  1479.             //ProcessShotResults();
  1480.         }
  1481.  
  1482.         bool pocketed = CheckPockets(); // Store if any ball was pocketed
  1483.  
  1484.         // --- Update pocket flash animation timer ---
  1485.         if (pocketFlashTimer > 0.0f) {
  1486.             pocketFlashTimer -= 0.02f;
  1487.             if (pocketFlashTimer < 0.0f) pocketFlashTimer = 0.0f;
  1488.         }
  1489.  
  1490.         if (!AreBallsMoving()) {
  1491.             ProcessShotResults(); // Determine next state based on what happened
  1492.         }
  1493.     }
  1494.  
  1495.     // --- Check if AI needs to act ---
  1496.     else if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  1497.         if (aiIsDisplayingAim) { // AI has decided a shot and is displaying aim
  1498.             aiAimDisplayFramesLeft--;
  1499.             if (aiAimDisplayFramesLeft <= 0) {
  1500.                 aiIsDisplayingAim = false; // Done displaying
  1501.                 if (aiPlannedShotDetails.isValid) {
  1502.                     // Execute the planned shot
  1503.                     firstHitBallIdThisShot = -1;
  1504.                     cueHitObjectBallThisShot = false;
  1505.                     railHitAfterContact = false;
  1506.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1507.                     ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
  1508.                     aiPlannedShotDetails.isValid = false; // Clear the planned shot
  1509.                 }
  1510.                 currentGameState = SHOT_IN_PROGRESS;
  1511.                 foulCommitted = false;
  1512.                 pocketedThisTurn.clear();
  1513.             }
  1514.             // Else, continue displaying aim
  1515.         }
  1516.         else if (aiTurnPending) { // AI needs to start its decision process
  1517.             // Valid states for AI to start thinking
  1518.             /*/if (currentGameState == PRE_BREAK_PLACEMENT && isOpeningBreakShot) {*/
  1519.             //newcode 1 commented out
  1520.             /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
  1521.                 // Handle the break shot
  1522.                 AIBreakShot();
  1523.             }*/ //new code 1 end  
  1524.             /*else if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING ||
  1525.                 currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2) {*/
  1526.  
  1527.                 // aiTurnPending might be consumed by AIBreakShot or remain for next cycle if needed
  1528.         /* } //new code 2 commented out
  1529.         else if (currentGameState == BALL_IN_HAND_P2 && currentPlayer == 2 && isPlayer2AI) {
  1530.             AIPlaceCueBall(); // AI places the ball first
  1531.             // After placement, AI needs to decide its shot.
  1532.             // Transition to a state where AIMakeDecision will be called for shot selection.
  1533.             currentGameState = PLAYER2_TURN; // Or a specific AI_AIMING_AFTER_PLACEMENT state
  1534.                                              // aiTurnPending remains true to trigger AIMakeDecision next.
  1535.         }
  1536.         else if (currentGameState == PLAYER2_TURN && currentPlayer == 2 && isPlayer2AI) {
  1537.             // This is for a normal turn (not break, not immediately after ball-in-hand placement)
  1538.  
  1539.                 currentGameState = AI_THINKING; // Set state to indicate AI is processing
  1540.                 aiTurnPending = false;         // Consume the pending turn flag
  1541.                 AIMakeDecision();              // For normal shots (non-break)
  1542.             }
  1543.             else {
  1544.                 // Not a state where AI should act
  1545.                 aiTurnPending = false;
  1546.             }*/
  1547.             // 2b) AI is ready to think (pending flag)
  1548.             // **1) Ball-in-Hand** let AI place the cue ball first
  1549.             if (currentGameState == BALL_IN_HAND_P2) {
  1550.                 // Step 1: AI places the cue ball.
  1551.                 AIPlaceCueBall();
  1552.                 // Step 2: Transition to thinking state for shot decision.
  1553.                 currentGameState = AI_THINKING; //newcode5
  1554.                 // Step 3: Consume the pending flag for the placement phase.
  1555.                 //         AIMakeDecision will handle shot planning now.
  1556.                 aiTurnPending = false; //newcode5
  1557.                 // Step 4: AI immediately decides the shot from the new position.
  1558.                 AIMakeDecision(); //newcode5
  1559.             }
  1560.             // **2) Opening break** special break shot logic
  1561.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  1562.                 AIBreakShot();
  1563.             }
  1564.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) { //newcode5
  1565.                 // General turn for AI to think (not ball-in-hand, not initial break placement)
  1566.                 currentGameState = AI_THINKING; //newcode5
  1567.                 aiTurnPending = false; // Consume the flag //newcode5
  1568.                 AIMakeDecision(); //newcode5
  1569.             }
  1570.             // **3) Otherwise** normal shot planning
  1571.             /*else { //orig uncommented oldcode5
  1572.                 currentGameState = AI_THINKING;
  1573.                 aiTurnPending = false;
  1574.                 AIMakeDecision();
  1575.             }*/
  1576.         }
  1577.  
  1578.         //} //bracefix
  1579.         // If current state is AI_THINKING but not displaying aim, then AI decision has already been made
  1580.     }
  1581. }
  1582.  
  1583. // --- Physics and Collision ---
  1584. void UpdatePhysics() {
  1585.     for (size_t i = 0; i < balls.size(); ++i) {
  1586.         Ball& b = balls[i];
  1587.         if (!b.isPocketed) {
  1588.             b.x += b.vx;
  1589.             b.y += b.vy;
  1590.  
  1591.             // Apply friction
  1592.             b.vx *= FRICTION;
  1593.             b.vy *= FRICTION;
  1594.  
  1595.             // Stop balls if velocity is very low
  1596.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  1597.                 b.vx = 0;
  1598.                 b.vy = 0;
  1599.             }
  1600.         }
  1601.     }
  1602. }
  1603.  
  1604. void CheckCollisions() {
  1605.     float left = TABLE_LEFT;
  1606.     float right = TABLE_RIGHT;
  1607.     float top = TABLE_TOP;
  1608.     float bottom = TABLE_BOTTOM;
  1609.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
  1610.  
  1611.     // --- Reset Per-Frame Sound Flags ---
  1612.     bool playedWallSoundThisFrame = false;
  1613.     bool playedCollideSoundThisFrame = false;
  1614.     // ---
  1615.  
  1616.     for (size_t i = 0; i < balls.size(); ++i) {
  1617.         Ball& b1 = balls[i];
  1618.         if (b1.isPocketed) continue;
  1619.  
  1620.         bool nearPocket[6];
  1621.         for (int p = 0; p < 6; ++p) {
  1622.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  1623.         }
  1624.         bool nearTopLeftPocket = nearPocket[0];
  1625.         bool nearTopMidPocket = nearPocket[1];
  1626.         bool nearTopRightPocket = nearPocket[2];
  1627.         bool nearBottomLeftPocket = nearPocket[3];
  1628.         bool nearBottomMidPocket = nearPocket[4];
  1629.         bool nearBottomRightPocket = nearPocket[5];
  1630.  
  1631.         bool collidedWallThisBall = false;
  1632.  
  1633.         // --- Ball-Wall Collisions ---
  1634.         // (Check logic unchanged, added sound calls and railHitAfterContact update)
  1635.         // Left Wall
  1636.         if (b1.x - BALL_RADIUS < left) {
  1637.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1638.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1639.                 if (!playedWallSoundThisFrame) {
  1640.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1641.                     playedWallSoundThisFrame = true;
  1642.                 }
  1643.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1644.             }
  1645.         }
  1646.         // Right Wall
  1647.         if (b1.x + BALL_RADIUS > right) {
  1648.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1649.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1650.                 if (!playedWallSoundThisFrame) {
  1651.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1652.                     playedWallSoundThisFrame = true;
  1653.                 }
  1654.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1655.             }
  1656.         }
  1657.         // Top Wall
  1658.         if (b1.y - BALL_RADIUS < top) {
  1659.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1660.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1661.                 if (!playedWallSoundThisFrame) {
  1662.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1663.                     playedWallSoundThisFrame = true;
  1664.                 }
  1665.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1666.             }
  1667.         }
  1668.         // Bottom Wall
  1669.         if (b1.y + BALL_RADIUS > bottom) {
  1670.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1671.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1672.                 if (!playedWallSoundThisFrame) {
  1673.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1674.                     playedWallSoundThisFrame = true;
  1675.                 }
  1676.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1677.             }
  1678.         }
  1679.  
  1680.         // Spin effect (Unchanged)
  1681.         if (collidedWallThisBall) {
  1682.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  1683.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  1684.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  1685.         }
  1686.  
  1687.  
  1688.         // --- Ball-Ball Collisions ---
  1689.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1690.             Ball& b2 = balls[j];
  1691.             if (b2.isPocketed) continue;
  1692.  
  1693.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  1694.             float distSq = dx * dx + dy * dy;
  1695.             float minDist = BALL_RADIUS * 2.0f;
  1696.  
  1697.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  1698.                 float dist = sqrtf(distSq);
  1699.                 float overlap = minDist - dist;
  1700.                 float nx = dx / dist; float ny = dy / dist;
  1701.  
  1702.                 // Separation (Unchanged)
  1703.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  1704.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  1705.  
  1706.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  1707.                 float velAlongNormal = rvx * nx + rvy * ny;
  1708.  
  1709.                 if (velAlongNormal > 0) { // Colliding
  1710.                     // --- Play Ball Collision Sound ---
  1711.                     if (!playedCollideSoundThisFrame) {
  1712.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  1713.                         playedCollideSoundThisFrame = true; // Set flag
  1714.                     }
  1715.                     // --- End Sound ---
  1716.  
  1717.                     // --- NEW: Track First Hit and Cue/Object Collision ---
  1718.                     if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
  1719.                         if (b1.id == 0) { // Cue ball hit b2 first
  1720.                             firstHitBallIdThisShot = b2.id;
  1721.                             cueHitObjectBallThisShot = true;
  1722.                         }
  1723.                         else if (b2.id == 0) { // Cue ball hit b1 first
  1724.                             firstHitBallIdThisShot = b1.id;
  1725.                             cueHitObjectBallThisShot = true;
  1726.                         }
  1727.                         // If neither is cue ball, doesn't count as first hit for foul purposes
  1728.                     }
  1729.                     else if (b1.id == 0 || b2.id == 0) {
  1730.                         // Track subsequent cue ball collisions with object balls
  1731.                         cueHitObjectBallThisShot = true;
  1732.                     }
  1733.                     // --- End First Hit Tracking ---
  1734.  
  1735.  
  1736.                     // Impulse (Unchanged)
  1737.                     float impulse = velAlongNormal;
  1738.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  1739.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  1740.  
  1741.                     // Spin Transfer (Unchanged)
  1742.                     if (b1.id == 0 || b2.id == 0) {
  1743.                         float spinEffectFactor = 0.08f;
  1744.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1745.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1746.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1747.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1748.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  1749.                     }
  1750.                 }
  1751.             }
  1752.         } // End ball-ball loop
  1753.     } // End ball loop
  1754. } // End CheckCollisions
  1755.  
  1756.  
  1757. bool CheckPockets() {
  1758.     bool ballPocketedThisCheck = false; // Local flag for this specific check run
  1759.     for (size_t i = 0; i < balls.size(); ++i) {
  1760.         Ball& b = balls[i];
  1761.         if (!b.isPocketed) { // Only check balls that aren't already flagged as pocketed
  1762.             for (int p = 0; p < 6; ++p) {
  1763.                 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
  1764.                 // --- Use updated POCKET_RADIUS ---
  1765.                 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
  1766.                     b.isPocketed = true;
  1767.                     b.vx = b.vy = 0;
  1768.                     pocketedThisTurn.push_back(b.id);
  1769.  
  1770.                     // --- Play Pocket Sound (Threaded) ---
  1771.                     if (!ballPocketedThisCheck) {
  1772.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  1773.                         ballPocketedThisCheck = true;
  1774.                     }
  1775.                     // --- End Sound ---
  1776.  
  1777.                     break; // Ball is pocketed
  1778.                 }
  1779.             }
  1780.         }
  1781.     }
  1782.     return ballPocketedThisCheck;
  1783. }
  1784.  
  1785. bool AreBallsMoving() {
  1786.     for (size_t i = 0; i < balls.size(); ++i) {
  1787.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1788.             return true;
  1789.         }
  1790.     }
  1791.     return false;
  1792. }
  1793.  
  1794. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1795.     Ball* cueBall = GetCueBall();
  1796.     if (cueBall) {
  1797.         // Reset position to a default
  1798.         //disabled for behind headstring (now move anywhere)
  1799.         /*cueBall->x = HEADSTRING_X * 0.5f;
  1800.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;*/
  1801.         // Reset position to a default:
  1802.         if (behindHeadstring) {
  1803.             // Opening break: kitchen center
  1804.             cueBall->x = HEADSTRING_X * 0.5f;
  1805.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1806.         }
  1807.         else {
  1808.             // Ball-in-hand (foul): center of full table
  1809.             cueBall->x = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  1810.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1811.         }
  1812.         cueBall->vx = 0;
  1813.         cueBall->vy = 0;
  1814.         cueBall->isPocketed = false;
  1815.  
  1816.         // Set state based on who gets ball-in-hand
  1817.         /*// 'currentPlayer' already reflects who's turn it is NOW (switched before calling this)*/
  1818.         // 'currentPlayer' has already been switched to the player whose turn it will be.
  1819.         // The 'behindHeadstring' parameter to RespawnCueBall is mostly for historical reasons / initial setup.
  1820.         if (currentPlayer == 1) { // Player 2 (AI/Human) fouled, Player 1 (Human) gets ball-in-hand
  1821.             currentGameState = BALL_IN_HAND_P1;
  1822.             aiTurnPending = false; // Ensure AI flag off
  1823.         }
  1824.         else { // Player 1 (Human) fouled, Player 2 gets ball-in-hand
  1825.             if (isPlayer2AI) {
  1826.                 // --- CONFIRMED FIX: Set correct state for AI Ball-in-Hand ---
  1827.                 currentGameState = BALL_IN_HAND_P2; // AI now needs to place the ball
  1828.                 aiTurnPending = true; // Trigger AI logic (will call AIPlaceCueBall first)
  1829.             }
  1830.             else { // Human Player 2
  1831.                 currentGameState = BALL_IN_HAND_P2;
  1832.                 aiTurnPending = false; // Ensure AI flag off
  1833.             }
  1834.         }
  1835.         // Handle initial placement state correctly if called from InitGame
  1836.         /*if (behindHeadstring && currentGameState != PRE_BREAK_PLACEMENT) {
  1837.             // This case might need review depending on exact initial setup flow,
  1838.             // but the foul logic above should now be correct.
  1839.             // Let's ensure initial state is PRE_BREAK_PLACEMENT if behindHeadstring is true.*/
  1840.             //currentGameState = PRE_BREAK_PLACEMENT;
  1841.     }
  1842. }
  1843. //}
  1844.  
  1845.  
  1846. // --- Game Logic ---
  1847.  
  1848. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1849.     Ball* cueBall = GetCueBall();
  1850.     if (cueBall) {
  1851.  
  1852.         // --- Play Cue Strike Sound (Threaded) ---
  1853.         if (power > 0.1f) { // Only play if it's an audible shot
  1854.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1855.         }
  1856.         // --- End Sound ---
  1857.  
  1858.         cueBall->vx = cosf(angle) * power;
  1859.         cueBall->vy = sinf(angle) * power;
  1860.  
  1861.         // Apply English (Spin) - Simplified effect (Unchanged)
  1862.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  1863.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1864.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1865.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1866.  
  1867.         // Store spin (Unchanged)
  1868.         cueSpinX = spinX;
  1869.         cueSpinY = spinY;
  1870.  
  1871.         // --- Reset Foul Tracking flags for the new shot ---
  1872.         // (Also reset in LBUTTONUP, but good to ensure here too)
  1873.         firstHitBallIdThisShot = -1;      // No ball hit yet
  1874.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  1875.         railHitAfterContact = false;     // No rail hit after contact yet
  1876.         // --- End Reset ---
  1877.  
  1878.                 // If this was the opening break shot, clear the flag
  1879.         if (isOpeningBreakShot) {
  1880.             isOpeningBreakShot = false; // Mark opening break as taken
  1881.         }
  1882.     }
  1883. }
  1884.  
  1885.  
  1886. void ProcessShotResults() {
  1887.     bool cueBallPocketed = false;
  1888.     bool eightBallPocketed = false;
  1889.     bool playerContinuesTurn = false;
  1890.  
  1891.     // --- Preliminary Analysis & Score Update ---
  1892.     // First, update the counts to ensure all subsequent logic has the correct score.
  1893.     // This is the key fix for the off-by-one visual error.
  1894.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  1895.     int ownBallsPocketedThisTurn = 0;
  1896.  
  1897.     for (int id : pocketedThisTurn) {
  1898.         Ball* b = GetBallById(id);
  1899.         if (!b) continue;
  1900.         if (b->id == 0) cueBallPocketed = true;
  1901.         else if (b->id == 8) eightBallPocketed = true;
  1902.         else {
  1903.             if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) player1Info.ballsPocketedCount++;
  1904.             else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) player2Info.ballsPocketedCount++;
  1905.  
  1906.             if (b->type == shootingPlayer.assignedType) {
  1907.                 ownBallsPocketedThisTurn++;
  1908.             }
  1909.         }
  1910.     }
  1911.  
  1912.     if (ownBallsPocketedThisTurn > 0) {
  1913.         playerContinuesTurn = true;
  1914.     }
  1915.  
  1916.     // --- Step 1: Check for Game-Ending 8-Ball Shot ---
  1917.     if (eightBallPocketed) {
  1918.         CheckGameOverConditions(true, cueBallPocketed);
  1919.         if (currentGameState == GAME_OVER) { pocketedThisTurn.clear(); return; }
  1920.     }
  1921.  
  1922.     // --- Step 2: Check for Fouls ---
  1923.     // This logic is now more robust. A foul is only checked against the state of the game *before* the shot.
  1924.     // The fact that the player is NOW on the 8-ball doesn't make their previous legal shot a foul.
  1925.     bool turnFoul = false;
  1926.     Ball* firstHit = GetBallById(firstHitBallIdThisShot);
  1927.  
  1928.     if (cueBallPocketed) {
  1929.         turnFoul = true;
  1930.     }
  1931.     else if (!firstHit) {
  1932.         turnFoul = true; // Hit nothing.
  1933.     }
  1934.     else {
  1935.         // Check for illegal first hit based on the rules BEFORE this shot was taken.
  1936.         bool wasOnEightBall = (shootingPlayer.assignedType != BallType::NONE && (shootingPlayer.ballsPocketedCount - ownBallsPocketedThisTurn) >= 7);
  1937.  
  1938.         if (player1Info.assignedType != BallType::NONE) { // Colors are assigned
  1939.             if (wasOnEightBall) {
  1940.                 if (firstHit->id != 8) turnFoul = true; // Was on 8-ball, but didn't hit it first.
  1941.             }
  1942.             else {
  1943.                 if (firstHit->type != shootingPlayer.assignedType) turnFoul = true; // Wasn't on 8-ball, but hit wrong type.
  1944.             }
  1945.         }
  1946.     }
  1947.  
  1948.     if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
  1949.         turnFoul = true; // No rail after contact.
  1950.     }
  1951.     foulCommitted = turnFoul;
  1952.  
  1953.     // --- Step 3: Final State Transition ---
  1954.     if (foulCommitted) {
  1955.         SwitchTurns();
  1956.         RespawnCueBall(false);
  1957.     }
  1958.     else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed) {
  1959.         // Table is open, assign types.
  1960.         for (int id : pocketedThisTurn) {
  1961.             Ball* b = GetBallById(id);
  1962.             if (b && b->type != BallType::EIGHT_BALL) {
  1963.                 AssignPlayerBallTypes(b->type);
  1964.                 break;
  1965.             }
  1966.         }
  1967.         CheckAndTransitionToPocketChoice(currentPlayer); // Player continues turn
  1968.     }
  1969.     else if (playerContinuesTurn) {
  1970.         // Player legally pocketed a ball. Check if they are now on the 8-ball.
  1971.         CheckAndTransitionToPocketChoice(currentPlayer);
  1972.     }
  1973.     else {
  1974.         // No legal ball pocketed, no foul. Switch turns.
  1975.         SwitchTurns();
  1976.     }
  1977.  
  1978.     pocketedThisTurn.clear();
  1979. }
  1980.  
  1981. bool AssignPlayerBallTypes(BallType firstPocketedType) {
  1982.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  1983.         if (currentPlayer == 1) {
  1984.             player1Info.assignedType = firstPocketedType;
  1985.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1986.         }
  1987.         else {
  1988.             player2Info.assignedType = firstPocketedType;
  1989.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1990.         }
  1991.         return true; // Assignment was successful
  1992.     }
  1993.     return false; // No assignment made (e.g., 8-ball was pocketed on break)
  1994. }
  1995.     // If 8-ball was first (illegal on break generally), rules vary.
  1996.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  1997.     // Or assign based on what *else* was pocketed, if anything.
  1998.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  1999.  
  2000.  
  2001. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2002.     if (!eightBallPocketed) return;
  2003.  
  2004.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  2005.     PlayerInfo& opponentPlayer = (currentPlayer == 1) ? player2Info : player1Info;
  2006.     bool shooterWasOn8Ball = IsPlayerOnEightBall(currentPlayer);
  2007.     int pocketThe8BallEntered = -1;
  2008.  
  2009.     // Find which pocket the 8-ball actually went into
  2010.     Ball* b = GetBallById(8);
  2011.     if (b) {
  2012.         for (int p_idx = 0; p_idx < 6; ++p_idx) {
  2013.             if (GetDistanceSq(b->x, b->y, pocketPositions[p_idx].x, pocketPositions[p_idx].y) < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2014.                 pocketThe8BallEntered = p_idx;
  2015.                 break;
  2016.             }
  2017.         }
  2018.     }
  2019.  
  2020.     // Case 1: 8-ball pocketed on the break (or before colors assigned)
  2021.     if (player1Info.assignedType == BallType::NONE) {
  2022.         if (b) { // Re-spot the 8-ball
  2023.             b->isPocketed = false;
  2024.             b->x = RACK_POS_X;
  2025.             b->y = RACK_POS_Y;
  2026.             b->vx = b->vy = 0;
  2027.         }
  2028.         if (cueBallPocketed) {
  2029.             foulCommitted = true; // Let ProcessShotResults handle the foul, game doesn't end.
  2030.         }
  2031.         return; // Game continues
  2032.     }
  2033.  
  2034.     // Case 2: Normal gameplay win/loss conditions
  2035.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2036.  
  2037.     if (!shooterWasOn8Ball) {
  2038.         // Loss: Pocketed 8-ball before clearing own group.
  2039.         gameOverMessage = opponentPlayer.name + L" Wins! (" + shootingPlayer.name + L" pocketed 8-ball early)";
  2040.     }
  2041.     else if (cueBallPocketed) {
  2042.         // Loss: Scratched while shooting for the 8-ball.
  2043.         gameOverMessage = opponentPlayer.name + L" Wins! (" + shootingPlayer.name + L" scratched on 8-ball)";
  2044.     }
  2045.     else if (calledPocket == -1) {
  2046.         // Loss: Pocketed 8-ball without calling a pocket. THIS IS THE KEY FIX FOR YOUR REPORTED PROBLEM.
  2047.         gameOverMessage = opponentPlayer.name + L" Wins! (" + shootingPlayer.name + L" did not call a pocket)";
  2048.     }
  2049.     else if (pocketThe8BallEntered != calledPocket) {
  2050.         // Loss: Pocketed 8-ball in the wrong pocket.
  2051.         gameOverMessage = opponentPlayer.name + L" Wins! (" + shootingPlayer.name + L" 8-ball in wrong pocket)";
  2052.     }
  2053.     else {
  2054.         // WIN! Pocketed 8-ball in the called pocket without a foul.
  2055.         gameOverMessage = shootingPlayer.name + L" Wins!";
  2056.     }
  2057.  
  2058.     currentGameState = GAME_OVER;
  2059. }
  2060.  
  2061.  
  2062. void SwitchTurns() {
  2063.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  2064.     isAiming = false;
  2065.     shotPower = 0;
  2066.     CheckAndTransitionToPocketChoice(currentPlayer); // Use the new helper
  2067. }
  2068.  
  2069. void AIBreakShot() {
  2070.     Ball* cueBall = GetCueBall();
  2071.     if (!cueBall) return;
  2072.  
  2073.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  2074.     // AI will place the cue ball and then plan the shot.
  2075.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2076.         // Place cue ball in the kitchen randomly
  2077.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  2078.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  2079.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  2080.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  2081.  
  2082.         // --- AI Places Cue Ball for Break ---
  2083. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  2084. // towards one side for a more angled break, or center for direct apex hit.
  2085. // A common strategy is to hit the second ball of the rack.
  2086.  
  2087.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  2088.         float placementX;
  2089.  
  2090.         // Randomly choose a side or center-ish placement for variation.
  2091.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  2092.  
  2093.         if (placementChoice == 0) { // Left-ish
  2094.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  2095.         }
  2096.         else if (placementChoice == 2) { // Right-ish
  2097.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  2098.         }
  2099.         else { // Center-ish
  2100.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  2101.         }
  2102.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  2103.  
  2104.         bool validPos = false;
  2105.         int attempts = 0;
  2106.         while (!validPos && attempts < 100) {
  2107.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  2108.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  2109.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  2110.                 validPos = true; // [cite: 1591]*/
  2111.                 // Try the chosen X, but vary Y slightly to find a clear spot
  2112.             cueBall->x = placementX;
  2113.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  2114.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  2115.  
  2116.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  2117.                 validPos = true;
  2118.             }
  2119.             attempts++; // [cite: 1592]
  2120.         }
  2121.         if (!validPos) {
  2122.             // Fallback position
  2123.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  2124.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  2125.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  2126.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  2127.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  2128.             }
  2129.         }
  2130.         cueBall->vx = 0; // [cite: 1595]
  2131.         cueBall->vy = 0; // [cite: 1596]
  2132.  
  2133.         // Plan a break shot: aim at the center of the rack (apex ball)
  2134.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  2135.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  2136.  
  2137.         float dx = targetX - cueBall->x; // [cite: 1599]
  2138.         float dy = targetY - cueBall->y; // [cite: 1600]
  2139.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  2140.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  2141.  
  2142.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  2143.             cueBall->y = RACK_POS_Y;
  2144.         }
  2145.         cueBall->vx = 0; cueBall->vy = 0;
  2146.  
  2147.         // --- AI Plans the Break Shot ---
  2148.         float targetX, targetY;
  2149.         // If cue ball is near center of kitchen width, aim for apex.
  2150.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  2151.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  2152.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  2153.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  2154.             targetX = RACK_POS_X; // Apex ball X
  2155.             targetY = RACK_POS_Y; // Apex ball Y
  2156.         }
  2157.         else {
  2158.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  2159.             // This is a simplification. A more robust way is to find the actual second ball.
  2160.             // For now, aim slightly off the apex towards the side the cue ball is on.
  2161.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  2162.             targetY = RACK_POS_Y + ((cueBall->y > RACK_POS_Y) ? -BALL_RADIUS : BALL_RADIUS); // Aim at the upper or lower of the two second-row balls
  2163.         }
  2164.  
  2165.         float dx = targetX - cueBall->x;
  2166.         float dy = targetY - cueBall->y;
  2167.         float shotAngle = atan2f(dy, dx);
  2168.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  2169.  
  2170.         // Store planned shot details for the AI
  2171.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  2172.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  2173.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  2174.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  2175.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  2176.  
  2177.         aiPlannedShotDetails.angle = shotAngle;
  2178.         aiPlannedShotDetails.power = shotPowerValue;
  2179.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  2180.         aiPlannedShotDetails.spinY = 0.0f;
  2181.         aiPlannedShotDetails.isValid = true;
  2182.  
  2183.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  2184.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  2185.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  2186.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  2187.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  2188.  
  2189.         ::cueAngle = aiPlannedShotDetails.angle;
  2190.         ::shotPower = aiPlannedShotDetails.power;
  2191.         ::cueSpinX = aiPlannedShotDetails.spinX;
  2192.         ::cueSpinY = aiPlannedShotDetails.spinY;
  2193.  
  2194.         // Set up for AI display via GameUpdate
  2195.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  2196.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  2197.  
  2198.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  2199.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  2200.                                         // and then execute the shot using aiPlannedShotDetails.
  2201.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  2202.  
  2203.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  2204.  
  2205.         aiIsDisplayingAim = true;
  2206.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2207.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  2208.  
  2209.         return; // The break shot is now planned and will be executed by GameUpdate
  2210.     }
  2211.  
  2212.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  2213.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  2214.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  2215.     //    For now, the primary logic is above.
  2216. }
  2217.  
  2218. // --- Helper Functions ---
  2219.  
  2220. Ball* GetBallById(int id) {
  2221.     for (size_t i = 0; i < balls.size(); ++i) {
  2222.         if (balls[i].id == id) {
  2223.             return &balls[i];
  2224.         }
  2225.     }
  2226.     return nullptr;
  2227. }
  2228.  
  2229. Ball* GetCueBall() {
  2230.     return GetBallById(0);
  2231. }
  2232.  
  2233. float GetDistance(float x1, float y1, float x2, float y2) {
  2234.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  2235. }
  2236.  
  2237. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  2238.     float dx = x2 - x1;
  2239.     float dy = y2 - y1;
  2240.     return dx * dx + dy * dy;
  2241. }
  2242.  
  2243. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  2244.     // Basic bounds check (inside cushions)
  2245.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  2246.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  2247.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  2248.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  2249.  
  2250.     if (x < left || x > right || y < top || y > bottom) {
  2251.         return false;
  2252.     }
  2253.  
  2254.     // Check headstring restriction if needed
  2255.     if (checkHeadstring && x >= HEADSTRING_X) {
  2256.         return false;
  2257.     }
  2258.  
  2259.     // Check overlap with other balls
  2260.     for (size_t i = 0; i < balls.size(); ++i) {
  2261.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  2262.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  2263.                 return false; // Overlapping another ball
  2264.             }
  2265.         }
  2266.     }
  2267.  
  2268.     return true;
  2269. }
  2270.  
  2271. // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  2272.  
  2273. // Checks if a player has pocketed all their balls and is now on the 8-ball.
  2274. bool IsPlayerOnEightBall(int player) {
  2275.     PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  2276.     if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  2277.         Ball* eightBall = GetBallById(8);
  2278.         return (eightBall && !eightBall->isPocketed);
  2279.     }
  2280.     return false;
  2281. }
  2282.  
  2283. // Centralized logic to enter the "choosing pocket" state. This fixes the indicator bugs.
  2284. void CheckAndTransitionToPocketChoice(int playerID) {
  2285.     bool needsToCall = IsPlayerOnEightBall(playerID);
  2286.     int* calledPocketForPlayer = (playerID == 1) ? &calledPocketP1 : &calledPocketP2;
  2287.  
  2288.     if (needsToCall && *calledPocketForPlayer == -1) { // Only transition if a pocket hasn't been called yet
  2289.         pocketCallMessage = ((playerID == 1) ? player1Info.name : player2Info.name) + L": Choose a pocket...";
  2290.         if (playerID == 1) {
  2291.             currentGameState = CHOOSING_POCKET_P1;
  2292.         }
  2293.         else { // Player 2
  2294.             if (isPlayer2AI) {
  2295.                 currentGameState = AI_THINKING;
  2296.                 aiTurnPending = true;
  2297.             }
  2298.             else {
  2299.                 currentGameState = CHOOSING_POCKET_P2;
  2300.             }
  2301.         }
  2302.         if (!(playerID == 2 && isPlayer2AI)) {
  2303.             *calledPocketForPlayer = 5; // Default to top-right if none chosen
  2304.         }
  2305.     }
  2306.     else {
  2307.         // Player does not need to call a pocket (or already has), proceed to normal turn.
  2308.         pocketCallMessage = L""; // Clear any message
  2309.         currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2310.         if (playerID == 2 && isPlayer2AI) {
  2311.             aiTurnPending = true;
  2312.         }
  2313.     }
  2314. }
  2315.  
  2316. template <typename T>
  2317. void SafeRelease(T** ppT) {
  2318.     if (*ppT) {
  2319.         (*ppT)->Release();
  2320.         *ppT = nullptr;
  2321.     }
  2322. }
  2323.  
  2324. // --- Helper Function for Line Segment Intersection ---
  2325. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  2326. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  2327. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  2328. {
  2329.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  2330.  
  2331.     // Check if lines are parallel or collinear
  2332.     if (fabs(denominator) < 1e-6) {
  2333.         return false;
  2334.     }
  2335.  
  2336.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  2337.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  2338.  
  2339.     // Check if intersection point lies on both segments
  2340.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  2341.         intersection.x = p1.x + ua * (p2.x - p1.x);
  2342.         intersection.y = p1.y + ua * (p2.y - p1.y);
  2343.         return true;
  2344.     }
  2345.  
  2346.     return false;
  2347. }
  2348.  
  2349. // --- INSERT NEW HELPER FUNCTION HERE ---
  2350. // Calculates the squared distance from point P to the line segment AB.
  2351. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  2352.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  2353.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  2354.     // Consider P projecting onto the line AB infinite line
  2355.     // t = [(P-A) . (B-A)] / |B-A|^2
  2356.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  2357.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  2358.     // Projection falls on the segment
  2359.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  2360.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  2361. }
  2362. // --- End New Helper ---
  2363.  
  2364. // --- NEW AI Implementation Functions ---
  2365.  
  2366. // Main entry point for AI turn
  2367. void AIMakeDecision() {
  2368.     //AIShotInfo bestShot = { false }; // Declare here
  2369.     // This function is called when currentGameState is AI_THINKING (for a normal shot decision)
  2370.     Ball* cueBall = GetCueBall();
  2371.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) {
  2372.         aiPlannedShotDetails.isValid = false; // Ensure no shot if conditions not met
  2373.         return;
  2374.     }
  2375.  
  2376.     // Phase 1: Placement if needed (Ball-in-Hand or Initial Break)
  2377.     /*if ((isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) || currentGameState == BALL_IN_HAND_P2) {
  2378.         AIPlaceCueBall(); // Handles kitchen placement for break or regular ball-in-hand
  2379.         if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2380.             currentGameState = BREAKING; // Now AI needs to decide the break shot parameters
  2381.         }
  2382.         // For regular BALL_IN_HAND_P2, after placement, it will proceed to find a shot.
  2383.     }*/
  2384.  
  2385.     aiPlannedShotDetails.isValid = false; // Default to no valid shot found yet for this decision cycle
  2386.     // Note: isOpeningBreakShot is false here because AIBreakShot handles the break.
  2387.  
  2388.      // Phase 2: Decide shot parameters (Break or Normal play)
  2389.     /*if (isOpeningBreakShot && currentGameState == BREAKING) {
  2390.         // Force cue ball into center of kitchen
  2391.         cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2392.         cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f;
  2393.         cueBall->vx = cueBall->vy = 0.0f;
  2394.  
  2395.         float rackCenterX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f * 2.0f;
  2396.         float rackCenterY = RACK_POS_Y;
  2397.         float dx = rackCenterX - cueBall->x;
  2398.         float dy = rackCenterY - cueBall->y;
  2399.  
  2400.         aiPlannedShotDetails.angle = atan2f(dy, dx);
  2401.         aiPlannedShotDetails.power = MAX_SHOT_POWER;
  2402.         aiPlannedShotDetails.spinX = 0.0f;
  2403.         aiPlannedShotDetails.spinY = 0.0f;
  2404.         aiPlannedShotDetails.isValid = true;
  2405.  
  2406.         // Apply shot immediately
  2407.         cueAngle = aiPlannedShotDetails.angle;
  2408.         shotPower = aiPlannedShotDetails.power;
  2409.         cueSpinX = aiPlannedShotDetails.spinX;
  2410.         cueSpinY = aiPlannedShotDetails.spinY;
  2411.  
  2412.         firstHitBallIdThisShot = -1;
  2413.         cueHitObjectBallThisShot = false;
  2414.         railHitAfterContact = false;
  2415.         isAiming = false;
  2416.         aiIsDisplayingAim = false;
  2417.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2418.         //bool aiIsDisplayingAim = true;
  2419.  
  2420.         std::thread([](const TCHAR* soundName) {
  2421.             PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  2422.             }, TEXT("cue.wav")).detach();
  2423.  
  2424.             ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2425.             currentGameState = SHOT_IN_PROGRESS;
  2426.             isOpeningBreakShot = false;
  2427.             aiTurnPending = false;
  2428.             pocketedThisTurn.clear();
  2429.             return;
  2430.     }
  2431.     else {*/
  2432.     // --- Normal AI Shot Decision (using AIFindBestShot) ---
  2433.     AIShotInfo bestShot = AIFindBestShot(); // bugtraq
  2434.     //bestShot = AIFindBestShot(); // bugtraq
  2435.     if (bestShot.possible) {
  2436.         aiPlannedShotDetails.angle = bestShot.angle;
  2437.         aiPlannedShotDetails.power = bestShot.power;
  2438.         aiPlannedShotDetails.spinX = 0.0f; // AI doesn't use spin yet
  2439.         aiPlannedShotDetails.spinY = 0.0f;
  2440.         aiPlannedShotDetails.isValid = true;
  2441.     }
  2442.     else {
  2443.         // Safety tap if no better shot found
  2444.         // Try to hit the closest 'own' ball gently or any ball if types not assigned
  2445.         Ball* ballToNudge = nullptr;
  2446.         float minDistSq = -1.0f;
  2447.         BallType aiTargetType = player2Info.assignedType;
  2448.         bool mustHit8Ball = (aiTargetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2449.  
  2450.         for (auto& b : balls) {
  2451.             if (b.isPocketed || b.id == 0) continue;
  2452.             bool canHitThis = false;
  2453.             if (mustHit8Ball) canHitThis = (b.id == 8);
  2454.             else if (aiTargetType != BallType::NONE) canHitThis = (b.type == aiTargetType);
  2455.             else canHitThis = (b.id != 8); // Can hit any non-8-ball if types not assigned
  2456.  
  2457.             if (canHitThis) {
  2458.                 float dSq = GetDistanceSq(cueBall->x, cueBall->y, b.x, b.y);
  2459.                 if (ballToNudge == nullptr || dSq < minDistSq) {
  2460.                     ballToNudge = &b;
  2461.                     minDistSq = dSq;
  2462.                 }
  2463.             }
  2464.         }
  2465.         if (ballToNudge) { // Found a ball to nudge
  2466.             aiPlannedShotDetails.angle = atan2f(ballToNudge->y - cueBall->y, ballToNudge->x - cueBall->x);
  2467.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.15f; // Gentle tap
  2468.         }
  2469.         else { // Absolute fallback: small tap forward
  2470.             aiPlannedShotDetails.angle = cueAngle; // Keep last angle or default
  2471.             //aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
  2472.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
  2473.         }
  2474.         aiPlannedShotDetails.spinX = 0.0f;
  2475.         aiPlannedShotDetails.spinY = 0.0f;
  2476.         aiPlannedShotDetails.isValid = true; // Safety shot is a "valid" plan
  2477.     }
  2478.     //} //bracefix
  2479.  
  2480.     // Phase 3: Setup for Aim Display (if a valid shot was decided)
  2481.     if (aiPlannedShotDetails.isValid) {
  2482.         cueAngle = aiPlannedShotDetails.angle;   // Update global for drawing
  2483.         shotPower = aiPlannedShotDetails.power;  // Update global for drawing
  2484.         // cueSpinX and cueSpinY could also be set here if AI used them
  2485.         cueSpinX = aiPlannedShotDetails.spinX; // Also set these for drawing consistency
  2486.         cueSpinY = aiPlannedShotDetails.spinY; //
  2487.  
  2488.         aiIsDisplayingAim = true;
  2489.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2490.         // currentGameState remains AI_THINKING, GameUpdate will handle the display countdown and shot execution.
  2491.             // FIRE THE BREAK SHOT NOW
  2492.             // Immediately execute the break shot after setting parameters
  2493.         /*ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
  2494.         currentGameState = SHOT_IN_PROGRESS;
  2495.         aiTurnPending = false;
  2496.         isOpeningBreakShot = false;*/
  2497.     }
  2498.     else {
  2499.         // Should not happen if safety shot is always planned, but as a fallback:
  2500.         aiIsDisplayingAim = false;
  2501.         // If AI truly can't decide anything, maybe switch turn or log error. For now, it will do nothing this frame.
  2502.         // Or force a minimal safety tap without display.
  2503.         // To ensure game progresses, let's plan a minimal tap if nothing else.
  2504.         if (!aiPlannedShotDetails.isValid) { // Double check
  2505.             aiPlannedShotDetails.angle = 0.0f;
  2506.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.05f; // Very small tap
  2507.             aiPlannedShotDetails.spinX = 0.0f; aiPlannedShotDetails.spinY = 0.0f;
  2508.             aiPlannedShotDetails.isValid = true;
  2509.             //cueAngle = aiPlannedShotDetails.angle; shotPower = aiPlannedShotDetails.power;
  2510.             cueAngle = aiPlannedShotDetails.angle;
  2511.             shotPower = aiPlannedShotDetails.power;
  2512.             cueSpinX = aiPlannedShotDetails.spinX;
  2513.             cueSpinY = aiPlannedShotDetails.spinY;
  2514.             aiIsDisplayingAim = true; // Allow display for this minimal tap too
  2515.             aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES / 2; // Shorter display for fallback
  2516.         }
  2517.     }
  2518.     // aiTurnPending was set to false by GameUpdate before calling AIMakeDecision.
  2519.     // AIMakeDecision's job is to populate aiPlannedShotDetails and trigger display.
  2520. }
  2521.  
  2522. // AI logic for placing cue ball during ball-in-hand
  2523. void AIPlaceCueBall() {
  2524.     Ball* cueBall = GetCueBall();
  2525.     if (!cueBall) return;
  2526.  
  2527.     // --- CPU AI Opening Break: Kitchen Placement ---
  2528.     /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
  2529.         float kitchenMinX = TABLE_LEFT + BALL_RADIUS;
  2530.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS;
  2531.         float kitchenMinY = TABLE_TOP + BALL_RADIUS;
  2532.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS;
  2533.         bool validPositionFound = false;
  2534.         int attempts = 0;
  2535.         while (!validPositionFound && attempts < 100) {
  2536.             cueBall->x = kitchenMinX + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxX - kitchenMinX)));
  2537.             cueBall->y = kitchenMinY + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxY - kitchenMinY)));
  2538.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
  2539.                 validPositionFound = true;
  2540.             }
  2541.             attempts++;
  2542.         }
  2543.         if (!validPositionFound) {
  2544.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2545.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2546.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
  2547.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2.0f;
  2548.                 cueBall->y = RACK_POS_Y;
  2549.             }
  2550.         }
  2551.         cueBall->vx = 0; cueBall->vy = 0;
  2552.         return;
  2553.     }*/
  2554.     // --- End CPU AI Opening Break Placement ---
  2555.  
  2556.     // This function is now SOLELY for Ball-In-Hand placement for the AI (anywhere on the table).
  2557.     // Break placement is handled by AIBreakShot().
  2558.  
  2559.     // Simple Strategy: Find the easiest possible shot for the AI's ball type
  2560.     // Place the cue ball directly behind that target ball, aiming straight at a pocket.
  2561.     // (More advanced: find spot offering multiple options or safety)
  2562.  
  2563.     AIShotInfo bestPlacementShot = { false };
  2564.     D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
  2565.  
  2566.     // A better default for ball-in-hand (anywhere) might be center table if no shot found.
  2567.     bestPlacePos = D2D1::Point2F(TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP + TABLE_HEIGHT / 2.0f);
  2568.     float bestPlacementScore = -1.0f; // Keep track of the score for the best placement found
  2569.  
  2570.     BallType targetType = player2Info.assignedType;
  2571.     bool canTargetAnyPlacement = false; // Local scope variable for placement logic
  2572.     if (targetType == BallType::NONE) {
  2573.         canTargetAnyPlacement = true;
  2574.     }
  2575.     bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2576.     if (target8Ball) targetType = BallType::EIGHT_BALL;
  2577.  
  2578.  
  2579.     for (auto& targetBall : balls) {
  2580.         if (targetBall.isPocketed || targetBall.id == 0) continue;
  2581.  
  2582.         // Determine if current ball is a valid target for placement consideration
  2583.         bool currentBallIsValidTarget = false;
  2584.         if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
  2585.         else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
  2586.         else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
  2587.  
  2588.         if (!currentBallIsValidTarget) continue; // Skip if not a valid target
  2589.  
  2590.         for (int p = 0; p < 6; ++p) {
  2591.             // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
  2592.             float targetToPocketX = pocketPositions[p].x - targetBall.x;
  2593.             float targetToPocketY = pocketPositions[p].y - targetBall.y;
  2594.             float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  2595.             if (dist < 1.0f) continue; // Avoid division by zero
  2596.  
  2597.             float idealAngle = atan2f(targetToPocketY, targetToPocketX);
  2598.             // Place cue ball slightly behind target ball along this line
  2599.             float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
  2600.             D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
  2601.                 targetBall.x - cosf(idealAngle) * placeDist,
  2602.                 targetBall.y - sinf(idealAngle) * placeDist
  2603.             );
  2604.  
  2605.             // Check if this placement is valid (on table, behind headstring if break, not overlapping)
  2606.             /*bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);*/
  2607.             // For ball-in-hand (NOT break), behindHeadstringRule is false.
  2608.             // The currentGameState should be BALL_IN_HAND_P2 when this is called for a foul.
  2609.             bool behindHeadstringRule = false; // Player can place anywhere after a foul
  2610.             if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
  2611.                 // Is path from potentialPlacePos to targetBall clear?
  2612.                 // Use D2D1::Point2F() factory function here
  2613.                 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
  2614.                     // Is path from targetBall to pocket clear?
  2615.                     // Use D2D1::Point2F() factory function here
  2616.                     if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
  2617.                         // This seems like a good potential placement. Score it?
  2618.                         // Easy AI: Just take the first valid one found.
  2619.                         /*bestPlacePos = potentialPlacePos;
  2620.                         goto placement_found;*/ // Use goto for simplicity in non-OOP structure
  2621.                         // This is a possible shot. Score this placement.
  2622. // A simple score: distance to target ball (shorter is better for placement).
  2623. // More advanced: consider angle to pocket, difficulty of the shot from this placement.
  2624.                         AIShotInfo tempShotInfo;
  2625.                         tempShotInfo.possible = true;
  2626.                         tempShotInfo.targetBall = &targetBall;
  2627.                         tempShotInfo.pocketIndex = p;
  2628.                         tempShotInfo.ghostBallPos = CalculateGhostBallPos(&targetBall, p); // Not strictly needed for placement score but good for consistency
  2629.                         tempShotInfo.angle = idealAngle; // The angle from the placed ball to target
  2630.                         // Use EvaluateShot's scoring mechanism if possible, or a simpler one here.
  2631.                         float currentScore = 1000.0f / (1.0f + GetDistance(potentialPlacePos.x, potentialPlacePos.y, targetBall.x, targetBall.y)); // Inverse distance
  2632.  
  2633.                         if (currentScore > bestPlacementScore) {
  2634.                             bestPlacementScore = currentScore;
  2635.                             bestPlacePos = potentialPlacePos;
  2636.                         }
  2637.                     }
  2638.                 }
  2639.             }
  2640.         }
  2641.     }
  2642.  
  2643. placement_found:
  2644.     // Place the cue ball at the best found position (or default if no good spot found)
  2645.     cueBall->x = bestPlacePos.x;
  2646.     cueBall->y = bestPlacePos.y;
  2647.     cueBall->vx = 0;
  2648.     cueBall->vy = 0;
  2649. }
  2650.  
  2651.  
  2652. // AI finds the best shot available on the table
  2653. AIShotInfo AIFindBestShot() {
  2654.     AIShotInfo bestShotOverall = { false };
  2655.     Ball* cueBall = GetCueBall();
  2656.     if (!cueBall) return bestShotOverall;
  2657.     // Ensure cue ball position is up-to-date if AI just placed it
  2658.     // (AIPlaceCueBall should have already set cueBall->x, cueBall->y)
  2659.  
  2660.     // Determine target ball type for AI (Player 2)
  2661.     BallType targetType = player2Info.assignedType;
  2662.     bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
  2663.     if (targetType == BallType::NONE) {
  2664.         // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
  2665.         // Or, more simply, treat any ball as a potential target to make *a* pocket
  2666.         canTargetAny = true; // Simplification: allow targeting any non-8 ball.
  2667.         // A better rule is hit lowest numbered ball first on break follow-up.
  2668.     }
  2669.  
  2670.     // Check if AI needs to shoot the 8-ball
  2671.     bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2672.  
  2673.  
  2674.     // Iterate through all potential target balls
  2675.     for (auto& potentialTarget : balls) {
  2676.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
  2677.  
  2678.         // Check if this ball is a valid target
  2679.         bool isValidTarget = false;
  2680.         if (target8Ball) {
  2681.             isValidTarget = (potentialTarget.id == 8);
  2682.         }
  2683.         else if (canTargetAny) {
  2684.             isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
  2685.         }
  2686.         else { // Colors assigned, not yet shooting 8-ball
  2687.             isValidTarget = (potentialTarget.type == targetType);
  2688.         }
  2689.  
  2690.         if (!isValidTarget) continue; // Skip if not a valid target for this turn
  2691.  
  2692.         // Now, check all pockets for this target ball
  2693.         for (int p = 0; p < 6; ++p) {
  2694.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  2695.             currentShot.involves8Ball = (potentialTarget.id == 8);
  2696.  
  2697.             if (currentShot.possible) {
  2698.                 // Compare scores to find the best shot
  2699.                 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  2700.                     bestShotOverall = currentShot;
  2701.                 }
  2702.             }
  2703.         }
  2704.     } // End loop through potential target balls
  2705.  
  2706.     // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
  2707.     // need a safety strategy. Current simple AI just takes best found or taps cue ball.
  2708.  
  2709.     return bestShotOverall;
  2710. }
  2711.  
  2712.  
  2713. // Evaluate a potential shot at a specific target ball towards a specific pocket
  2714. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  2715.     AIShotInfo shotInfo;
  2716.     shotInfo.possible = false; // Assume not possible initially
  2717.     shotInfo.targetBall = targetBall;
  2718.     shotInfo.pocketIndex = pocketIndex;
  2719.  
  2720.     Ball* cueBall = GetCueBall();
  2721.     if (!cueBall || !targetBall) return shotInfo;
  2722.  
  2723.     // --- Define local state variables needed for legality checks ---
  2724.     BallType aiAssignedType = player2Info.assignedType;
  2725.     bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
  2726.     bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  2727.     // ---
  2728.  
  2729.     // 1. Calculate Ghost Ball position
  2730.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  2731.  
  2732.     // 2. Calculate Angle from Cue Ball to Ghost Ball
  2733.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  2734.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  2735.     if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
  2736.     shotInfo.angle = atan2f(dy, dx);
  2737.  
  2738.     // Basic angle validity check (optional)
  2739.     if (!IsValidAIAimAngle(shotInfo.angle)) {
  2740.         // Maybe log this or handle edge cases
  2741.     }
  2742.  
  2743.     // 3. Check Path: Cue Ball -> Ghost Ball Position
  2744.     // Use D2D1::Point2F() factory function here
  2745.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  2746.         return shotInfo; // Path blocked
  2747.     }
  2748.  
  2749.     // 4. Check Path: Target Ball -> Pocket
  2750.     // Use D2D1::Point2F() factory function here
  2751.     if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
  2752.         return shotInfo; // Path blocked
  2753.     }
  2754.  
  2755.     // 5. Check First Ball Hit Legality
  2756.     float firstHitDistSq = -1.0f;
  2757.     // Use D2D1::Point2F() factory function here
  2758.     Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
  2759.  
  2760.     if (!firstHit) {
  2761.         return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
  2762.     }
  2763.  
  2764.     // Check if the first ball hit is the intended target ball
  2765.     if (firstHit->id != targetBall->id) {
  2766.         // Allow hitting slightly off target if it's very close to ghost ball pos
  2767.         float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
  2768.         // Allow a tolerance roughly half the ball radius squared
  2769.         if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
  2770.             // First hit is significantly different from the target point.
  2771.             // This shot path leads to hitting the wrong ball first.
  2772.             return shotInfo; // Foul or unintended shot
  2773.         }
  2774.         // If first hit is not target, but very close, allow it for now (might still be foul based on type).
  2775.     }
  2776.  
  2777.     // Check legality of the *first ball actually hit* based on game rules
  2778.     if (!canTargetAny) { // Colors are assigned (or should be)
  2779.         if (mustTarget8Ball) { // Must hit 8-ball first
  2780.             if (firstHit->id != 8) {
  2781.                 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
  2782.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  2783.             }
  2784.         }
  2785.         else { // Must hit own ball type first
  2786.             if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
  2787.                 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
  2788.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  2789.             }
  2790.             else if (firstHit->id == 8) {
  2791.                 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
  2792.                 // Keep shot possible for now
  2793.             }
  2794.         }
  2795.     }
  2796.     // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
  2797.  
  2798.  
  2799.     // 6. Calculate Score & Power (Difficulty affects this)
  2800.     shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
  2801.  
  2802.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  2803.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  2804.  
  2805.     // Simple Score: Shorter shots are better, straighter shots are slightly better.
  2806.     float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
  2807.  
  2808.     // Angle Score: Calculate cut angle
  2809.     // Vector Cue -> Ghost
  2810.     float v1x = shotInfo.ghostBallPos.x - cueBall->x;
  2811.     float v1y = shotInfo.ghostBallPos.y - cueBall->y;
  2812.     // Vector Target -> Pocket
  2813.     float v2x = pocketPositions[pocketIndex].x - targetBall->x;
  2814.     float v2y = pocketPositions[pocketIndex].y - targetBall->y;
  2815.     // Normalize vectors
  2816.     float mag1 = sqrtf(v1x * v1x + v1y * v1y);
  2817.     float mag2 = sqrtf(v2x * v2x + v2y * v2y);
  2818.     float angleScoreFactor = 0.5f; // Default if vectors are zero len
  2819.     if (mag1 > 0.1f && mag2 > 0.1f) {
  2820.         v1x /= mag1; v1y /= mag1;
  2821.         v2x /= mag2; v2y /= mag2;
  2822.         // Dot product gives cosine of angle between cue ball path and target ball path
  2823.         float dotProduct = v1x * v2x + v1y * v2y;
  2824.         // Straighter shot (dot product closer to 1) gets higher score
  2825.         angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
  2826.     }
  2827.     angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
  2828.  
  2829.     shotInfo.score = distanceScore * angleScoreFactor;
  2830.  
  2831.     // Bonus for pocketing 8-ball legally
  2832.     if (mustTarget8Ball && targetBall->id == 8) {
  2833.         shotInfo.score *= 10.0; // Strongly prefer the winning shot
  2834.     }
  2835.  
  2836.     // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
  2837.  
  2838.     // 7. Calculate Power
  2839.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  2840.  
  2841.     // 8. Add Inaccuracy based on Difficulty (same as before)
  2842.     float angleError = 0.0f;
  2843.     float powerErrorFactor = 1.0f;
  2844.  
  2845.     switch (aiDifficulty) {
  2846.     case EASY:
  2847.         angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
  2848.         powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
  2849.         shotInfo.power *= 0.8f;
  2850.         break;
  2851.     case MEDIUM:
  2852.         angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
  2853.         powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
  2854.         break;
  2855.     case HARD:
  2856.         angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
  2857.         powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
  2858.         break;
  2859.     }
  2860.     shotInfo.angle += angleError;
  2861.     shotInfo.power *= powerErrorFactor;
  2862.     shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
  2863.  
  2864.     return shotInfo;
  2865. }
  2866.  
  2867.  
  2868. // Calculates required power (simplified)
  2869. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  2870.     // Basic model: Power needed increases with total distance the balls need to travel.
  2871.     // Need enough power for cue ball to reach target AND target to reach pocket.
  2872.     float totalDist = cueToGhostDist + targetToPocketDist;
  2873.  
  2874.     // Map distance to power (needs tuning)
  2875.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  2876.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  2877.  
  2878.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  2879.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  2880.  
  2881.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  2882.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  2883. }
  2884.  
  2885. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  2886. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  2887.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  2888.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  2889.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  2890.  
  2891.     if (dist < 1.0f) { // Target is basically in the pocket
  2892.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  2893.         // For simplicity, return a point slightly behind center along the reverse line.
  2894.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  2895.     }
  2896.  
  2897.     // Normalize direction vector from target to pocket
  2898.     float nx = targetToPocketX / dist;
  2899.     float ny = targetToPocketY / dist;
  2900.  
  2901.     // Ghost ball position is diameter distance *behind* the target ball along this line
  2902.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  2903.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  2904.  
  2905.     return D2D1::Point2F(ghostX, ghostY);
  2906. }
  2907.  
  2908. // Checks if line segment is clear of obstructing balls
  2909. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  2910.     float dx = end.x - start.x;
  2911.     float dy = end.y - start.y;
  2912.     float segmentLenSq = dx * dx + dy * dy;
  2913.  
  2914.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  2915.  
  2916.     for (const auto& ball : balls) {
  2917.         if (ball.isPocketed) continue;
  2918.         if (ball.id == ignoredBallId1) continue;
  2919.         if (ball.id == ignoredBallId2) continue;
  2920.  
  2921.         // Check distance from ball center to the line segment
  2922.         float ballToStartX = ball.x - start.x;
  2923.         float ballToStartY = ball.y - start.y;
  2924.  
  2925.         // Project ball center onto the line defined by the segment
  2926.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  2927.  
  2928.         D2D1_POINT_2F closestPointOnLine;
  2929.         if (dot < 0) { // Closest point is start point
  2930.             closestPointOnLine = start;
  2931.         }
  2932.         else if (dot > 1) { // Closest point is end point
  2933.             closestPointOnLine = end;
  2934.         }
  2935.         else { // Closest point is along the segment
  2936.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  2937.         }
  2938.  
  2939.         // Check if the closest point is within collision distance (ball radius + path radius)
  2940.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  2941.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  2942.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  2943.             return false; // Path is blocked
  2944.         }
  2945.     }
  2946.     return true; // No obstructions found
  2947. }
  2948.  
  2949. // Finds the first ball hit along a path (simplified)
  2950. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  2951.     Ball* hitBall = nullptr;
  2952.     hitDistSq = -1.0f; // Initialize hit distance squared
  2953.     float minCollisionDistSq = -1.0f;
  2954.  
  2955.     float cosA = cosf(angle);
  2956.     float sinA = sinf(angle);
  2957.  
  2958.     for (auto& ball : balls) {
  2959.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  2960.  
  2961.         float dx = ball.x - start.x;
  2962.         float dy = ball.y - start.y;
  2963.  
  2964.         // Project vector from start->ball onto the aim direction vector
  2965.         float dot = dx * cosA + dy * sinA;
  2966.  
  2967.         if (dot > 0) { // Ball is generally in front
  2968.             // Find closest point on aim line to the ball's center
  2969.             float closestPointX = start.x + dot * cosA;
  2970.             float closestPointY = start.y + dot * sinA;
  2971.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  2972.  
  2973.             // Check if the aim line passes within the ball's radius
  2974.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  2975.                 // Calculate distance from start to the collision point on the ball's circumference
  2976.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  2977.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  2978.  
  2979.                 if (collisionDist > 0) { // Ensure collision is in front
  2980.                     float collisionDistSq = collisionDist * collisionDist;
  2981.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  2982.                         minCollisionDistSq = collisionDistSq;
  2983.                         hitBall = &ball; // Found a closer hit ball
  2984.                     }
  2985.                 }
  2986.             }
  2987.         }
  2988.     }
  2989.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  2990.     return hitBall;
  2991. }
  2992.  
  2993. // Basic check for reasonable AI aim angles (optional)
  2994. bool IsValidAIAimAngle(float angle) {
  2995.     // Placeholder - could check for NaN or infinity if calculations go wrong
  2996.     return isfinite(angle);
  2997. }
  2998.  
  2999. //midi func = start
  3000. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  3001.     while (isMusicPlaying) {
  3002.         MCI_OPEN_PARMS mciOpen = { 0 };
  3003.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  3004.         mciOpen.lpstrElementName = midiPath;
  3005.  
  3006.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  3007.             midiDeviceID = mciOpen.wDeviceID;
  3008.  
  3009.             MCI_PLAY_PARMS mciPlay = { 0 };
  3010.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  3011.  
  3012.             // Wait for playback to complete
  3013.             MCI_STATUS_PARMS mciStatus = { 0 };
  3014.             mciStatus.dwItem = MCI_STATUS_MODE;
  3015.  
  3016.             do {
  3017.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  3018.                 Sleep(100); // adjust as needed
  3019.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  3020.  
  3021.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3022.             midiDeviceID = 0;
  3023.         }
  3024.     }
  3025. }
  3026.  
  3027. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  3028.     if (isMusicPlaying) {
  3029.         StopMidi();
  3030.     }
  3031.     isMusicPlaying = true;
  3032.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3033. }
  3034.  
  3035. void StopMidi() {
  3036.     if (isMusicPlaying) {
  3037.         isMusicPlaying = false;
  3038.         if (musicThread.joinable()) musicThread.join();
  3039.         if (midiDeviceID != 0) {
  3040.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3041.             midiDeviceID = 0;
  3042.         }
  3043.     }
  3044. }
  3045.  
  3046. /*void PlayGameMusic(HWND hwnd) {
  3047.     // Stop any existing playback
  3048.     if (isMusicPlaying) {
  3049.         isMusicPlaying = false;
  3050.         if (musicThread.joinable()) {
  3051.             musicThread.join();
  3052.         }
  3053.         if (midiDeviceID != 0) {
  3054.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3055.             midiDeviceID = 0;
  3056.         }
  3057.     }
  3058.  
  3059.     // Get the path of the executable
  3060.     TCHAR exePath[MAX_PATH];
  3061.     GetModuleFileName(NULL, exePath, MAX_PATH);
  3062.  
  3063.     // Extract the directory path
  3064.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  3065.     if (lastBackslash != NULL) {
  3066.         *(lastBackslash + 1) = '\0';
  3067.     }
  3068.  
  3069.     // Construct the full path to the MIDI file
  3070.     static TCHAR midiPath[MAX_PATH];
  3071.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  3072.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  3073.  
  3074.     // Start the background playback
  3075.     isMusicPlaying = true;
  3076.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3077. }*/
  3078. //midi func = end
  3079.  
  3080. // --- Drawing Functions ---
  3081.  
  3082. void OnPaint() {
  3083.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  3084.  
  3085.     if (SUCCEEDED(hr)) {
  3086.         pRenderTarget->BeginDraw();
  3087.         DrawScene(pRenderTarget); // Pass render target
  3088.         hr = pRenderTarget->EndDraw();
  3089.  
  3090.         if (hr == D2DERR_RECREATE_TARGET) {
  3091.             DiscardDeviceResources();
  3092.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  3093.             // But the timer loop will trigger redraw anyway.
  3094.         }
  3095.     }
  3096.     // If CreateDeviceResources failed, EndDraw might not be called.
  3097.     // Consider handling this more robustly if needed.
  3098. }
  3099.  
  3100. void DrawScene(ID2D1RenderTarget* pRT) {
  3101.     if (!pRT) return;
  3102.  
  3103.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  3104.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  3105.     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)
  3106.     //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)
  3107.  
  3108.     DrawTable(pRT, pFactory);
  3109.     DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  3110.     DrawBalls(pRT);
  3111.     DrawAimingAids(pRT); // Includes cue stick if aiming
  3112.     DrawUI(pRT);
  3113.     DrawPowerMeter(pRT);
  3114.     DrawSpinIndicator(pRT);
  3115.     DrawPocketedBallsIndicator(pRT);
  3116.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  3117.  
  3118.      // Draw Game Over Message
  3119.     if (currentGameState == GAME_OVER && pTextFormat) {
  3120.         ID2D1SolidColorBrush* pBrush = nullptr;
  3121.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  3122.         if (pBrush) {
  3123.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  3124.             pRT->DrawText(
  3125.                 gameOverMessage.c_str(),
  3126.                 (UINT32)gameOverMessage.length(),
  3127.                 pTextFormat, // Use large format maybe?
  3128.                 &layoutRect,
  3129.                 pBrush
  3130.             );
  3131.             SafeRelease(&pBrush);
  3132.         }
  3133.     }
  3134.  
  3135. }
  3136.  
  3137. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  3138.     ID2D1SolidColorBrush* pBrush = nullptr;
  3139.  
  3140.     // === Draw Full Orange Frame (Table Border) ===
  3141.     ID2D1SolidColorBrush* pFrameBrush = nullptr;
  3142.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3143.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3144.     if (pFrameBrush) {
  3145.         D2D1_RECT_F outerRect = D2D1::RectF(
  3146.             TABLE_LEFT - CUSHION_THICKNESS,
  3147.             TABLE_TOP - CUSHION_THICKNESS,
  3148.             TABLE_RIGHT + CUSHION_THICKNESS,
  3149.             TABLE_BOTTOM + CUSHION_THICKNESS
  3150.         );
  3151.         pRT->FillRectangle(&outerRect, pFrameBrush);
  3152.         SafeRelease(&pFrameBrush);
  3153.     }
  3154.  
  3155.     // Draw Table Bed (Green Felt)
  3156.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  3157.     if (!pBrush) return;
  3158.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  3159.     pRT->FillRectangle(&tableRect, pBrush);
  3160.     SafeRelease(&pBrush);
  3161.  
  3162.     // Draw Cushions (Red Border)
  3163.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  3164.     if (!pBrush) return;
  3165.     // Top Cushion (split by middle pocket)
  3166.     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);
  3167.     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);
  3168.     // Bottom Cushion (split by middle pocket)
  3169.     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);
  3170.     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);
  3171.     // Left Cushion
  3172.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3173.     // Right Cushion
  3174.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3175.     SafeRelease(&pBrush);
  3176.  
  3177.  
  3178.     // Draw Pockets (Black Circles)
  3179.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  3180.     if (!pBrush) return;
  3181.     for (int i = 0; i < 6; ++i) {
  3182.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  3183.         pRT->FillEllipse(&ellipse, pBrush);
  3184.     }
  3185.     SafeRelease(&pBrush);
  3186.  
  3187.     // Draw Headstring Line (White)
  3188.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3189.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3190.     if (!pBrush) return;
  3191.     pRT->DrawLine(
  3192.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  3193.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  3194.         pBrush,
  3195.         1.0f // Line thickness
  3196.     );
  3197.     SafeRelease(&pBrush);
  3198.  
  3199.     // Draw Semicircle facing West (flat side East)
  3200.     // Draw Semicircle facing East (curved side on the East, flat side on the West)
  3201.     ID2D1PathGeometry* pGeometry = nullptr;
  3202.     HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  3203.     if (SUCCEEDED(hr) && pGeometry)
  3204.     {
  3205.         ID2D1GeometrySink* pSink = nullptr;
  3206.         hr = pGeometry->Open(&pSink);
  3207.         if (SUCCEEDED(hr) && pSink)
  3208.         {
  3209.             float radius = 60.0f; // Radius for the semicircle
  3210.             D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  3211.  
  3212.             // For a semicircle facing East (curved side on the East), use the top and bottom points.
  3213.             D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
  3214.  
  3215.             pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  3216.  
  3217.             D2D1_ARC_SEGMENT arc = {};
  3218.             arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
  3219.             arc.size = D2D1::SizeF(radius, radius);
  3220.             arc.rotationAngle = 0.0f;
  3221.             // Use the correct identifier with the extra underscore:
  3222.             arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3223.             arc.arcSize = D2D1_ARC_SIZE_SMALL;
  3224.  
  3225.             pSink->AddArc(&arc);
  3226.             pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  3227.             pSink->Close();
  3228.             SafeRelease(&pSink);
  3229.  
  3230.             ID2D1SolidColorBrush* pArcBrush = nullptr;
  3231.             //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
  3232.             pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  3233.             if (pArcBrush)
  3234.             {
  3235.                 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  3236.                 SafeRelease(&pArcBrush);
  3237.             }
  3238.         }
  3239.         SafeRelease(&pGeometry);
  3240.     }
  3241.  
  3242.  
  3243.  
  3244.  
  3245. }
  3246.  
  3247.  
  3248. void DrawBalls(ID2D1RenderTarget* pRT) {
  3249.     ID2D1SolidColorBrush* pBrush = nullptr;
  3250.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  3251.  
  3252.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  3253.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3254.  
  3255.     if (!pBrush || !pStripeBrush) {
  3256.         SafeRelease(&pBrush);
  3257.         SafeRelease(&pStripeBrush);
  3258.         return;
  3259.     }
  3260.  
  3261.  
  3262.     for (size_t i = 0; i < balls.size(); ++i) {
  3263.         const Ball& b = balls[i];
  3264.         if (!b.isPocketed) {
  3265.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3266.  
  3267.             // Set main ball color
  3268.             pBrush->SetColor(b.color);
  3269.             pRT->FillEllipse(&ellipse, pBrush);
  3270.  
  3271.             // Draw Stripe if applicable
  3272.             if (b.type == BallType::STRIPE) {
  3273.                 // Draw a white band across the middle (simplified stripe)
  3274.                 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);
  3275.                 // Need to clip this rectangle to the ellipse bounds - complex!
  3276.                 // Alternative: Draw two colored arcs leaving a white band.
  3277.                 // Simplest: Draw a white circle inside, slightly smaller.
  3278.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  3279.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  3280.                 pBrush->SetColor(b.color); // Set back to stripe color
  3281.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  3282.  
  3283.                 // Let's try drawing a thick white line across
  3284.                 // This doesn't look great. Just drawing solid red for stripes for now.
  3285.             }
  3286.  
  3287.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  3288.             // if (b.id != 0 && pTextFormat) {
  3289.             //     std::wstring numStr = std::to_wstring(b.id);
  3290.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  3291.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  3292.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  3293.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  3294.             //     // Create a smaller text format...
  3295.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  3296.             //     SafeRelease(&pNumBrush);
  3297.             // }
  3298.         }
  3299.     }
  3300.  
  3301.     SafeRelease(&pBrush);
  3302.     SafeRelease(&pStripeBrush);
  3303. }
  3304.  
  3305.  
  3306. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3307.     // Condition check at start (Unchanged)
  3308.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  3309.         //currentGameState != BREAKING && currentGameState != AIMING)
  3310.     //{
  3311.         //return;
  3312.     //}
  3313.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  3314.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  3315.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3316.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3317.             currentGameState == BREAKING || currentGameState == AIMING);
  3318.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  3319.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  3320.         // NEW Condition: AI is displaying its aim
  3321.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  3322.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  3323.  
  3324.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  3325.         return;
  3326.     }
  3327.  
  3328.     Ball* cueBall = GetCueBall();
  3329.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  3330.  
  3331.     ID2D1SolidColorBrush* pBrush = nullptr;
  3332.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  3333.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  3334.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  3335.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  3336.  
  3337.     // Ensure render target is valid
  3338.     if (!pRT) return;
  3339.  
  3340.     // Create Brushes and Styles (check for failures)
  3341.     HRESULT hr;
  3342.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  3343.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  3344.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  3345.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  3346.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  3347.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  3348.     // Create reflection brush (e.g., lighter shade or different color)
  3349.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  3350.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  3351.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  3352.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  3353.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  3354.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  3355.     if (FAILED(hr)) {
  3356.         SafeRelease(&pCyanBrush);
  3357.         // handle error if needed
  3358.     }
  3359.     // Create a Purple brush for primary and secondary lines
  3360.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  3361.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  3362.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  3363.     if (FAILED(hr)) {
  3364.         SafeRelease(&pPurpleBrush);
  3365.         // handle error if needed
  3366.     }
  3367.  
  3368.     if (pFactory) {
  3369.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  3370.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  3371.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  3372.         if FAILED(hr) { pDashedStyle = nullptr; }
  3373.     }
  3374.  
  3375.  
  3376.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  3377.     const float baseStickLength = 150.0f;
  3378.     const float baseStickThickness = 4.0f;
  3379.     float stickLength = baseStickLength * 1.4f;
  3380.     float stickThickness = baseStickThickness * 1.5f;
  3381.     float stickAngle = cueAngle + PI;
  3382.     float powerOffset = 0.0f;
  3383.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  3384.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  3385.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  3386.         powerOffset = shotPower * 5.0f;
  3387.     }
  3388.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  3389.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  3390.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  3391.  
  3392.  
  3393.     // --- Projection Line Calculation ---
  3394.     float cosA = cosf(cueAngle);
  3395.     float sinA = sinf(cueAngle);
  3396.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  3397.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  3398.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  3399.  
  3400.     // Find the first ball hit by the aiming ray
  3401.     Ball* hitBall = nullptr;
  3402.     float firstHitDistSq = -1.0f;
  3403.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  3404.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  3405.  
  3406.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  3407.     if (hitBall) {
  3408.         // Calculate the point on the target ball's circumference
  3409.         float collisionDist = sqrtf(firstHitDistSq);
  3410.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  3411.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  3412.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  3413.     }
  3414.  
  3415.     // Find the first rail hit by the aiming ray
  3416.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  3417.     float minRailDistSq = rayLength * rayLength;
  3418.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  3419.  
  3420.     // Define table edge segments for intersection checks
  3421.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  3422.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  3423.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  3424.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  3425.  
  3426.     D2D1_POINT_2F currentIntersection;
  3427.  
  3428.     // Check Left Rail
  3429.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  3430.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3431.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  3432.     }
  3433.     // Check Right Rail
  3434.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  3435.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3436.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  3437.     }
  3438.     // Check Top Rail
  3439.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  3440.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3441.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  3442.     }
  3443.     // Check Bottom Rail
  3444.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  3445.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3446.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  3447.     }
  3448.  
  3449.  
  3450.     // --- Determine final aim line end point ---
  3451.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  3452.     bool aimingAtRail = true;
  3453.  
  3454.     if (hitBall && firstHitDistSq < minRailDistSq) {
  3455.         // Ball collision is closer than rail collision
  3456.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  3457.         aimingAtRail = false;
  3458.     }
  3459.  
  3460.     // --- Draw Primary Aiming Line ---
  3461.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3462.  
  3463.     // --- Draw Target Circle/Indicator ---
  3464.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  3465.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  3466.  
  3467.     // --- Draw Projection/Reflection Lines ---
  3468.     if (!aimingAtRail && hitBall) {
  3469.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  3470.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  3471.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3472.  
  3473.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  3474.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  3475.         // Clamp angle calculation if distance is tiny
  3476.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  3477.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  3478.         }
  3479.  
  3480.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  3481.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  3482.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  3483.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  3484.         );
  3485.         // Draw solid line for target projection
  3486.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  3487.  
  3488.     //new code start
  3489.  
  3490.                 // Dual trajectory with edge-aware contact simulation
  3491.         D2D1_POINT_2F dir = {
  3492.             targetProjectionEnd.x - targetStartPoint.x,
  3493.             targetProjectionEnd.y - targetStartPoint.y
  3494.         };
  3495.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  3496.         dir.x /= dirLen;
  3497.         dir.y /= dirLen;
  3498.  
  3499.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  3500.  
  3501.         // Approximate cue ball center by reversing from tip
  3502.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  3503.             targetStartPoint.x - dir.x * BALL_RADIUS,
  3504.             targetStartPoint.y - dir.y * BALL_RADIUS
  3505.         };
  3506.  
  3507.         // REAL contact-ball center - use your physics object's center:
  3508.         // (replace 'objectBallPos' with whatever you actually call it)
  3509.         // (targetStartPoint is already hitBall->x, hitBall->y)
  3510.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  3511.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  3512.  
  3513.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  3514.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  3515.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  3516.        // and 'perp' is perpendicular to 'dir'.
  3517.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  3518.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  3519.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  3520.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  3521.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  3522.             float absOffset = fabsf(offset);
  3523.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  3524.  
  3525.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  3526.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  3527.  
  3528.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  3529.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  3530.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  3531.         float absOffset = fabsf(offset);
  3532.         float side = (offset >= 0 ? 1.0f : -1.0f);
  3533.  
  3534.  
  3535.         // Actual contact point on target ball edge
  3536.         D2D1_POINT_2F contactPoint = {
  3537.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  3538.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  3539.         };
  3540.  
  3541.         // Tangent (cut shot) path from contact point
  3542.             // Tangent (cut shot) path: from contact point to contact ball center
  3543.         D2D1_POINT_2F objectBallDir = {
  3544.             contactBallCenter.x - contactPoint.x,
  3545.             contactBallCenter.y - contactPoint.y
  3546.         };
  3547.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  3548.         if (oLen != 0.0f) {
  3549.             objectBallDir.x /= oLen;
  3550.             objectBallDir.y /= oLen;
  3551.         }
  3552.  
  3553.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  3554.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  3555.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  3556.  
  3557.         D2D1_POINT_2F primaryEnd = {
  3558.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  3559.             targetStartPoint.y + dir.y * PRIMARY_LEN
  3560.         };
  3561.  
  3562.         // Secondary line starts from the contact ball's center
  3563.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  3564.         D2D1_POINT_2F secondaryEnd = {
  3565.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  3566.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  3567.         };
  3568.  
  3569.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  3570.         {
  3571.             // Straight: secondary behind primary
  3572.                     // secondary behind primary {pDashedStyle param at end}
  3573.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3574.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3575.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3576.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3577.         }
  3578.         else
  3579.         {
  3580.             // Cut shot: both visible
  3581.                     // both visible for cut shot
  3582.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3583.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3584.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3585.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3586.         }
  3587.         // End improved trajectory logic
  3588.  
  3589.     //new code end
  3590.  
  3591.         // -- Cue Ball Path after collision (Optional, requires physics) --
  3592.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  3593.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  3594.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  3595.         // D2D1_POINT_2F cueProjectionEnd = ...
  3596.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3597.  
  3598.         // --- Accuracy Comment ---
  3599.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  3600.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  3601.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  3602.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  3603.  
  3604.     }
  3605.     else if (aimingAtRail && hitRailIndex != -1) {
  3606.         // Aiming at a rail: Draw reflection line
  3607.         float reflectAngle = cueAngle;
  3608.         // Reflect angle based on which rail was hit
  3609.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  3610.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  3611.         }
  3612.         else { // Top or Bottom rail
  3613.             reflectAngle = -cueAngle; // Reflect vertical component
  3614.         }
  3615.         // Normalize angle if needed (atan2 usually handles this)
  3616.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  3617.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  3618.  
  3619.  
  3620.         float reflectionLength = 60.0f; // Length of the reflection line
  3621.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  3622.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  3623.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  3624.         );
  3625.  
  3626.         // Draw the reflection line (e.g., using a different color/style)
  3627.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3628.     }
  3629.  
  3630.     // Release resources
  3631.     SafeRelease(&pBrush);
  3632.     SafeRelease(&pGhostBrush);
  3633.     SafeRelease(&pCueBrush);
  3634.     SafeRelease(&pReflectBrush); // Release new brush
  3635.     SafeRelease(&pCyanBrush);
  3636.     SafeRelease(&pPurpleBrush);
  3637.     SafeRelease(&pDashedStyle);
  3638. }
  3639.  
  3640.  
  3641. void DrawUI(ID2D1RenderTarget* pRT) {
  3642.     if (!pTextFormat || !pLargeTextFormat) return;
  3643.  
  3644.     ID2D1SolidColorBrush* pBrush = nullptr;
  3645.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  3646.     if (!pBrush) return;
  3647.  
  3648.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  3649.     float uiTop = TABLE_TOP - 80;
  3650.     float uiHeight = 60;
  3651.     float p1Left = TABLE_LEFT;
  3652.     float p1Width = 150;
  3653.     float p2Left = TABLE_RIGHT - p1Width;
  3654.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  3655.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  3656.  
  3657.     // Player 1 Info Text (Unchanged)
  3658.     std::wostringstream oss1;
  3659.     oss1 << player1Info.name.c_str() << L"\n";
  3660.     if (player1Info.assignedType != BallType::NONE) {
  3661.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3662.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  3663.     }
  3664.     else {
  3665.         oss1 << L"(Undecided)";
  3666.     }
  3667.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  3668.     // Draw Player 1 Side Ball
  3669.     if (player1Info.assignedType != BallType::NONE)
  3670.     {
  3671.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3672.         D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  3673.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3674.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3675.         if (pBallBrush)
  3676.         {
  3677.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
  3678.             float radius = 10.0f;
  3679.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3680.             pRT->FillEllipse(&ball, pBallBrush);
  3681.             SafeRelease(&pBallBrush);
  3682.             // Draw border around the ball
  3683.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3684.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3685.             if (pBorderBrush)
  3686.             {
  3687.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3688.                 SafeRelease(&pBorderBrush);
  3689.             }
  3690.  
  3691.             // If stripes, draw a stripe band
  3692.             if (player1Info.assignedType == BallType::STRIPE)
  3693.             {
  3694.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3695.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3696.                 if (pStripeBrush)
  3697.                 {
  3698.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3699.                         ballCenter.x - radius,
  3700.                         ballCenter.y - 3.0f,
  3701.                         ballCenter.x + radius,
  3702.                         ballCenter.y + 3.0f
  3703.                     );
  3704.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3705.                     SafeRelease(&pStripeBrush);
  3706.                 }
  3707.             }
  3708.         }
  3709.     }
  3710.  
  3711.  
  3712.     // Player 2 Info Text (Unchanged)
  3713.     std::wostringstream oss2;
  3714.     oss2 << player2Info.name.c_str() << L"\n";
  3715.     if (player2Info.assignedType != BallType::NONE) {
  3716.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3717.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  3718.     }
  3719.     else {
  3720.         oss2 << L"(Undecided)";
  3721.     }
  3722.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  3723.     // Draw Player 2 Side Ball
  3724.     if (player2Info.assignedType != BallType::NONE)
  3725.     {
  3726.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3727.         D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  3728.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3729.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3730.         if (pBallBrush)
  3731.         {
  3732.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
  3733.             float radius = 10.0f;
  3734.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3735.             pRT->FillEllipse(&ball, pBallBrush);
  3736.             SafeRelease(&pBallBrush);
  3737.             // Draw border around the ball
  3738.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3739.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3740.             if (pBorderBrush)
  3741.             {
  3742.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3743.                 SafeRelease(&pBorderBrush);
  3744.             }
  3745.  
  3746.             // If stripes, draw a stripe band
  3747.             if (player2Info.assignedType == BallType::STRIPE)
  3748.             {
  3749.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3750.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3751.                 if (pStripeBrush)
  3752.                 {
  3753.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3754.                         ballCenter.x - radius,
  3755.                         ballCenter.y - 3.0f,
  3756.                         ballCenter.x + radius,
  3757.                         ballCenter.y + 3.0f
  3758.                     );
  3759.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3760.                     SafeRelease(&pStripeBrush);
  3761.                 }
  3762.             }
  3763.         }
  3764.     }
  3765.  
  3766.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3767.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3768.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3769.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3770.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3771.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3772.         float arrowTipX, arrowBackX;
  3773.  
  3774.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  3775.         arrowBackX = playerBox.left - 25.0f;
  3776.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  3777.  
  3778.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  3779.         float notchWidth = 10.0f;
  3780.  
  3781.         float cx = arrowBackX;
  3782.         float cy = arrowCenterY;
  3783.  
  3784.         // Define triangle + rectangle tail shape
  3785.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  3786.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  3787.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  3788.  
  3789.         // Rectangle coordinates for the tail portion:
  3790.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  3791.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  3792.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  3793.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  3794.  
  3795.         ID2D1PathGeometry* pPath = nullptr;
  3796.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3797.             ID2D1GeometrySink* pSink = nullptr;
  3798.             if (SUCCEEDED(pPath->Open(&pSink))) {
  3799.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  3800.                 pSink->AddLine(baseTop);
  3801.                 pSink->AddLine(r2); // transition from triangle into rectangle
  3802.                 pSink->AddLine(r1);
  3803.                 pSink->AddLine(r4);
  3804.                 pSink->AddLine(r3);
  3805.                 pSink->AddLine(baseBot);
  3806.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3807.                 pSink->Close();
  3808.                 SafeRelease(&pSink);
  3809.                 pRT->FillGeometry(pPath, pArrowBrush);
  3810.             }
  3811.             SafeRelease(&pPath);
  3812.         }
  3813.  
  3814.  
  3815.         SafeRelease(&pArrowBrush);
  3816.     }
  3817.  
  3818.     //original
  3819. /*
  3820.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3821.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3822.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3823.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3824.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3825.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3826.         float arrowTipX, arrowBackX;
  3827.  
  3828.         if (currentPlayer == 1) {
  3829. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  3830.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3831.             // Define points for right-pointing arrow
  3832.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3833.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3834.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3835.             // Enhanced arrow with base rectangle intersection
  3836.     float notchDepth = 6.0f; // Depth of square base "stem"
  3837.     float notchWidth = 4.0f; // Thickness of square part
  3838.  
  3839.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3840.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3841.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  3842.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  3843.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3844.  
  3845.  
  3846.     ID2D1PathGeometry* pPath = nullptr;
  3847.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3848.         ID2D1GeometrySink* pSink = nullptr;
  3849.         if (SUCCEEDED(pPath->Open(&pSink))) {
  3850.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3851.             pSink->AddLine(pt2);
  3852.             pSink->AddLine(pt3);
  3853.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3854.             pSink->Close();
  3855.             SafeRelease(&pSink);
  3856.             pRT->FillGeometry(pPath, pArrowBrush);
  3857.         }
  3858.         SafeRelease(&pPath);
  3859.     }
  3860.         }
  3861.  
  3862.  
  3863.         //==================else player 2
  3864.         else { // Player 2
  3865.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  3866.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3867. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3868. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  3869. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3870. // Define points for right-pointing arrow
  3871. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3872. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3873. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3874.  
  3875. ID2D1PathGeometry* pPath = nullptr;
  3876. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3877.     ID2D1GeometrySink* pSink = nullptr;
  3878.     if (SUCCEEDED(pPath->Open(&pSink))) {
  3879.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3880.         pSink->AddLine(pt2);
  3881.         pSink->AddLine(pt3);
  3882.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3883.         pSink->Close();
  3884.         SafeRelease(&pSink);
  3885.         pRT->FillGeometry(pPath, pArrowBrush);
  3886.     }
  3887.     SafeRelease(&pPath);
  3888. }
  3889.         }
  3890.         */
  3891.  
  3892.         // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  3893.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  3894.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  3895.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  3896.         if (pFoulBrush && pLargeTextFormat) {
  3897.             // Calculate Rect for bottom-middle area
  3898.             float foulWidth = 200.0f; // Adjust width as needed
  3899.             float foulHeight = 60.0f;
  3900.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  3901.             // Position below the pocketed balls bar
  3902.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  3903.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  3904.  
  3905.             // --- Set text alignment to center for foul text ---
  3906.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  3907.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3908.  
  3909.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  3910.  
  3911.             // --- Restore default alignment for large text if needed elsewhere ---
  3912.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  3913.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3914.  
  3915.             SafeRelease(&pFoulBrush);
  3916.         }
  3917.     }
  3918.  
  3919.     // --- 8-Ball Pocket Selection Arrow & Prompt ---
  3920.     if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  3921.         // Determine which pocket to highlight (default to Top-Right if unset)
  3922.         int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3923.         if (idx < 0) idx = 2;
  3924.  
  3925.         // Draw the downward arrow
  3926.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3927.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3928.         if (pArrowBrush) {
  3929.             D2D1_POINT_2F P = pocketPositions[idx];
  3930.             D2D1_POINT_2F tri[3] = {
  3931.                 {P.x - 10.0f, P.y - 30.0f},
  3932.                 {P.x + 10.0f, P.y - 30.0f},
  3933.                 {P.x        , P.y - 10.0f}
  3934.             };
  3935.             ID2D1PathGeometry* geom = nullptr;
  3936.             pFactory->CreatePathGeometry(&geom);
  3937.             ID2D1GeometrySink* sink = nullptr;
  3938.             geom->Open(&sink);
  3939.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  3940.             sink->AddLines(&tri[1], 2);
  3941.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3942.             sink->Close();
  3943.             pRT->FillGeometry(geom, pArrowBrush);
  3944.             SafeRelease(&sink);
  3945.             SafeRelease(&geom);
  3946.             SafeRelease(&pArrowBrush);
  3947.         }
  3948.  
  3949.         // Draw “Choose a pocket...” text under the table
  3950.         D2D1_RECT_F prompt = D2D1::RectF(
  3951.             TABLE_LEFT,
  3952.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  3953.             TABLE_RIGHT,
  3954.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  3955.         );
  3956.         pRT->DrawText(
  3957.             L"Choose a pocket...",
  3958.             (UINT32)wcslen(L"Choose a pocket..."),
  3959.             pTextFormat,
  3960.             &prompt,
  3961.             pBrush
  3962.         );
  3963.  
  3964.         return; // Skip normal turn/foul text
  3965.     }
  3966.  
  3967.  
  3968.     // Show AI Thinking State (Unchanged from previous step)
  3969.     if (currentGameState == AI_THINKING && pTextFormat) {
  3970.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  3971.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  3972.         if (pThinkingBrush) {
  3973.             D2D1_RECT_F thinkingRect = p2Rect;
  3974.             thinkingRect.top += 20; // Offset within P2 box
  3975.             // Ensure default text alignment for this
  3976.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  3977.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3978.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  3979.             SafeRelease(&pThinkingBrush);
  3980.         }
  3981.     }
  3982.  
  3983.     SafeRelease(&pBrush);
  3984.  
  3985.     // --- Draw CHEAT MODE label if active ---
  3986.     if (cheatModeEnabled) {
  3987.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  3988.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  3989.         if (pCheatBrush && pTextFormat) {
  3990.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  3991.                 TABLE_LEFT + 10.0f,
  3992.                 TABLE_TOP + 10.0f,
  3993.                 TABLE_LEFT + 200.0f,
  3994.                 TABLE_TOP + 40.0f
  3995.             );
  3996.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  3997.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  3998.             pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
  3999.         }
  4000.         SafeRelease(&pCheatBrush);
  4001.     }
  4002. }
  4003.  
  4004. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  4005.     // Draw Border
  4006.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4007.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4008.     if (!pBorderBrush) return;
  4009.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  4010.     SafeRelease(&pBorderBrush);
  4011.  
  4012.     // Create Gradient Fill
  4013.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  4014.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  4015.     D2D1_GRADIENT_STOP gradientStops[4];
  4016.     gradientStops[0].position = 0.0f;
  4017.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  4018.     gradientStops[1].position = 0.45f;
  4019.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  4020.     gradientStops[2].position = 0.7f;
  4021.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  4022.     gradientStops[3].position = 1.0f;
  4023.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  4024.  
  4025.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  4026.     if (pGradientStops) {
  4027.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  4028.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  4029.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  4030.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  4031.         SafeRelease(&pGradientStops);
  4032.     }
  4033.  
  4034.     // Calculate Fill Height
  4035.     float fillRatio = 0;
  4036.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  4037.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  4038.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  4039.     // NEW Condition: AI is displaying its aim, so show its chosen power
  4040.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  4041.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  4042.  
  4043.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  4044.         fillRatio = shotPower / MAX_SHOT_POWER;
  4045.     }
  4046.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  4047.     D2D1_RECT_F fillRect = D2D1::RectF(
  4048.         powerMeterRect.left,
  4049.         powerMeterRect.bottom - fillHeight,
  4050.         powerMeterRect.right,
  4051.         powerMeterRect.bottom
  4052.     );
  4053.  
  4054.     if (pGradientBrush) {
  4055.         pRT->FillRectangle(&fillRect, pGradientBrush);
  4056.         SafeRelease(&pGradientBrush);
  4057.     }
  4058.  
  4059.     // Draw scale notches
  4060.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  4061.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  4062.     if (pNotchBrush) {
  4063.         for (int i = 0; i <= 8; ++i) {
  4064.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  4065.             pRT->DrawLine(
  4066.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  4067.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  4068.                 pNotchBrush,
  4069.                 1.5f
  4070.             );
  4071.         }
  4072.         SafeRelease(&pNotchBrush);
  4073.     }
  4074.  
  4075.     // Draw "Power" Label Below Meter
  4076.     if (pTextFormat) {
  4077.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  4078.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  4079.         if (pTextBrush) {
  4080.             D2D1_RECT_F textRect = D2D1::RectF(
  4081.                 powerMeterRect.left - 20.0f,
  4082.                 powerMeterRect.bottom + 8.0f,
  4083.                 powerMeterRect.right + 20.0f,
  4084.                 powerMeterRect.bottom + 38.0f
  4085.             );
  4086.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4087.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4088.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  4089.             SafeRelease(&pTextBrush);
  4090.         }
  4091.     }
  4092.  
  4093.     // Draw Glow Effect if fully charged or fading out
  4094.     static float glowPulse = 0.0f;
  4095.     static bool glowIncreasing = true;
  4096.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  4097.  
  4098.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  4099.         // While fully charged, keep pulsing normally
  4100.         if (glowIncreasing) {
  4101.             glowPulse += 0.02f;
  4102.             if (glowPulse >= 1.0f) glowIncreasing = false;
  4103.         }
  4104.         else {
  4105.             glowPulse -= 0.02f;
  4106.             if (glowPulse <= 0.0f) glowIncreasing = true;
  4107.         }
  4108.         glowFadeOut = 1.0f; // Reset fade out to full
  4109.     }
  4110.     else if (glowFadeOut > 0.0f) {
  4111.         // If shot fired, gradually fade out
  4112.         glowFadeOut -= 0.02f;
  4113.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  4114.     }
  4115.  
  4116.     if (glowFadeOut > 0.0f) {
  4117.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  4118.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  4119.         pRT->CreateSolidColorBrush(
  4120.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  4121.             &pGlowBrush
  4122.         );
  4123.         if (pGlowBrush) {
  4124.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  4125.             float glowCenterY = powerMeterRect.top;
  4126.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  4127.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  4128.                 12.0f + 3.0f * glowPulse,
  4129.                 6.0f + 2.0f * glowPulse
  4130.             );
  4131.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  4132.             SafeRelease(&pGlowBrush);
  4133.         }
  4134.     }
  4135. }
  4136.  
  4137. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  4138.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  4139.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  4140.  
  4141.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  4142.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  4143.  
  4144.     if (!pWhiteBrush || !pRedBrush) {
  4145.         SafeRelease(&pWhiteBrush);
  4146.         SafeRelease(&pRedBrush);
  4147.         return;
  4148.     }
  4149.  
  4150.     // Draw White Ball Background
  4151.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  4152.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  4153.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  4154.  
  4155.  
  4156.     // Draw Red Dot for Spin Position
  4157.     float dotRadius = 4.0f;
  4158.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  4159.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  4160.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  4161.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  4162.  
  4163.     SafeRelease(&pWhiteBrush);
  4164.     SafeRelease(&pRedBrush);
  4165. }
  4166.  
  4167.  
  4168. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  4169.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  4170.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  4171.  
  4172.     // Ensure render target is valid before proceeding
  4173.     if (!pRT) return;
  4174.  
  4175.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  4176.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  4177.  
  4178.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  4179.     if (FAILED(hr)) {
  4180.         SafeRelease(&pBgBrush);
  4181.         SafeRelease(&pBallBrush);
  4182.         return; // Exit if brush creation fails
  4183.     }
  4184.  
  4185.     // Draw the background bar (rounded rect)
  4186.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  4187.     float baseAlpha = 0.8f;
  4188.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  4189.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  4190.     pBgBrush->SetOpacity(finalAlpha);
  4191.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  4192.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  4193.  
  4194.     // --- Draw small circles for pocketed balls inside the bar ---
  4195.  
  4196.     // Calculate dimensions based on the bar's height for better scaling
  4197.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  4198.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  4199.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  4200.     float padding = spacing * 0.75f; // Add padding from the edges
  4201.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  4202.  
  4203.     // Starting X positions with padding
  4204.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  4205.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  4206.  
  4207.     int p1DrawnCount = 0;
  4208.     int p2DrawnCount = 0;
  4209.     const int maxBallsToShow = 7; // Max balls per player in the bar
  4210.  
  4211.     for (const auto& b : balls) {
  4212.         if (b.isPocketed) {
  4213.             // Skip cue ball and 8-ball in this indicator
  4214.             if (b.id == 0 || b.id == 8) continue;
  4215.  
  4216.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  4217.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  4218.  
  4219.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  4220.                 pBallBrush->SetColor(b.color);
  4221.                 // Draw P1 balls from left to right
  4222.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4223.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4224.                 p1DrawnCount++;
  4225.             }
  4226.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  4227.                 pBallBrush->SetColor(b.color);
  4228.                 // Draw P2 balls from right to left
  4229.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4230.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4231.                 p2DrawnCount++;
  4232.             }
  4233.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  4234.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  4235.         }
  4236.     }
  4237.  
  4238.     SafeRelease(&pBgBrush);
  4239.     SafeRelease(&pBallBrush);
  4240. }
  4241.  
  4242. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  4243.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  4244.         return; // Only show when placing/dragging
  4245.     }
  4246.  
  4247.     Ball* cueBall = GetCueBall();
  4248.     if (!cueBall) return;
  4249.  
  4250.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  4251.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  4252.  
  4253.     if (pGhostBrush) {
  4254.         D2D1_POINT_2F drawPos;
  4255.         if (isDraggingCueBall) {
  4256.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  4257.         }
  4258.         else {
  4259.             // If not dragging but in placement state, show at current ball pos
  4260.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  4261.         }
  4262.  
  4263.         // Check if the placement is valid before drawing differently?
  4264.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  4265.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  4266.  
  4267.         if (!isValid) {
  4268.             // Maybe draw red outline if invalid placement?
  4269.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  4270.         }
  4271.  
  4272.  
  4273.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  4274.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  4275.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  4276.  
  4277.         SafeRelease(&pGhostBrush);
  4278.     }
  4279. }
  4280.  
  4281. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  4282.     int pocketToIndicate = -1;
  4283.     // A human player is actively choosing if they are in the CHOOSING_POCKET state.
  4284.     bool isHumanChoosing = (currentGameState == CHOOSING_POCKET_P1 || (currentGameState == CHOOSING_POCKET_P2 && !isPlayer2AI));
  4285.  
  4286.     if (isHumanChoosing) {
  4287.         // When choosing, show the currently selected pocket (which has a default).
  4288.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4289.     }
  4290.     else if (IsPlayerOnEightBall(currentPlayer)) {
  4291.         // If it's a normal turn but the player is on the 8-ball, show their called pocket as a reminder.
  4292.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4293.     }
  4294.  
  4295.     if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  4296.         return; // Don't draw if no pocket is selected or relevant.
  4297.     }
  4298.  
  4299.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4300.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  4301.     if (!pArrowBrush) return;
  4302.  
  4303.     // ... The rest of your arrow drawing geometry logic remains exactly the same ...
  4304.     // (No changes needed to the points/path drawing, only the logic above)
  4305.     D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  4306.     float arrowHeadSize = HOLE_VISUAL_RADIUS * 0.5f;
  4307.     float arrowShaftLength = HOLE_VISUAL_RADIUS * 0.3f;
  4308.     float arrowShaftWidth = arrowHeadSize * 0.4f;
  4309.     float verticalOffsetFromPocketCenter = HOLE_VISUAL_RADIUS * 1.6f;
  4310.     D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  4311.  
  4312.     if (targetPocketCenter.y == TABLE_TOP) {
  4313.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  4314.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  4315.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  4316.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  4317.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  4318.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  4319.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  4320.     }
  4321.     else {
  4322.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  4323.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  4324.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  4325.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  4326.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  4327.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  4328.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  4329.     }
  4330.  
  4331.     ID2D1PathGeometry* pPath = nullptr;
  4332.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4333.         ID2D1GeometrySink* pSink = nullptr;
  4334.         if (SUCCEEDED(pPath->Open(&pSink))) {
  4335.             pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  4336.             pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  4337.             pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  4338.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4339.             pSink->Close();
  4340.             SafeRelease(&pSink);
  4341.             pRT->FillGeometry(pPath, pArrowBrush);
  4342.         }
  4343.         SafeRelease(&pPath);
  4344.     }
  4345.     SafeRelease(&pArrowBrush);
  4346. }
  4347.  
  4348. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  4349. ```resource.h
  4350. //{{NO_DEPENDENCIES}}
  4351. // Microsoft Visual C++ generated include file.
  4352. // Used by Yahoo-8Ball-Pool-Clone.rc
  4353. //
  4354. #define IDI_ICON1                       101
  4355. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  4356. #define IDD_NEWGAMEDLG 106
  4357. #define IDC_RADIO_2P   1003
  4358. #define IDC_RADIO_CPU  1005
  4359. #define IDC_GROUP_AI   1006
  4360. #define IDC_RADIO_EASY 1007
  4361. #define IDC_RADIO_MEDIUM 1008
  4362. #define IDC_RADIO_HARD 1009
  4363. // --- NEW Resource IDs for Opening Break ---
  4364. #define IDC_GROUP_BREAK_MODE 1010
  4365. #define IDC_RADIO_CPU_BREAK  1011
  4366. #define IDC_RADIO_P1_BREAK   1012
  4367. #define IDC_RADIO_FLIP_BREAK 1013
  4368. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  4369.  
  4370. // Next default values for new objects
  4371. //
  4372. #ifdef APSTUDIO_INVOKED
  4373. #ifndef APSTUDIO_READONLY_SYMBOLS
  4374. #define _APS_NEXT_RESOURCE_VALUE        102
  4375. #define _APS_NEXT_COMMAND_VALUE         40002 // Incremented
  4376. #define _APS_NEXT_CONTROL_VALUE         1014 // Incremented
  4377. #define _APS_NEXT_SYMED_VALUE           101
  4378. #endif
  4379. #endif
  4380.  
  4381. ```
  4382.  
  4383. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  4384. ```Yahoo-8Ball-Pool-Clone.rc
  4385. // Microsoft Visual C++ generated resource script.
  4386. //
  4387. #include "resource.h"
  4388.  
  4389. #define APSTUDIO_READONLY_SYMBOLS
  4390. /////////////////////////////////////////////////////////////////////////////
  4391. //
  4392. // Generated from the TEXTINCLUDE 2 resource.
  4393. //
  4394. #include "winres.h"
  4395.  
  4396. /////////////////////////////////////////////////////////////////////////////
  4397. #undef APSTUDIO_READONLY_SYMBOLS
  4398.  
  4399. /////////////////////////////////////////////////////////////////////////////
  4400. // English (United States) resources
  4401.  
  4402. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  4403. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  4404. #pragma code_page(1252)
  4405.  
  4406. #ifdef APSTUDIO_INVOKED
  4407. /////////////////////////////////////////////////////////////////////////////
  4408. //
  4409. // TEXTINCLUDE
  4410. //
  4411.  
  4412. 1 TEXTINCLUDE
  4413. BEGIN
  4414.     "resource.h\0"
  4415. END
  4416.  
  4417. 2 TEXTINCLUDE
  4418. BEGIN
  4419.     "#include ""winres.h""\r\n"
  4420.     "\0"
  4421. END
  4422.  
  4423. 3 TEXTINCLUDE
  4424. BEGIN
  4425.     "\r\n"
  4426.     "\0"
  4427. END
  4428.  
  4429. #endif    // APSTUDIO_INVOKED
  4430.  
  4431.  
  4432. /////////////////////////////////////////////////////////////////////////////
  4433. //
  4434. // Icon
  4435. //
  4436.  
  4437. // Icon with lowest ID value placed first to ensure application icon
  4438. // remains consistent on all systems.
  4439. IDI_ICON1               ICON                    "D:\\Download\\cpp-projekt\\FuzenOp_SiloTest\\icons\\shell32_277.ico"
  4440.  
  4441. #endif    // English (United States) resources
  4442. /////////////////////////////////////////////////////////////////////////////
  4443.  
  4444.  
  4445.  
  4446. #ifndef APSTUDIO_INVOKED
  4447. /////////////////////////////////////////////////////////////////////////////
  4448. //
  4449. // Generated from the TEXTINCLUDE 3 resource.
  4450. //
  4451.  
  4452.  
  4453. /////////////////////////////////////////////////////////////////////////////
  4454. #endif    // not APSTUDIO_INVOKED
  4455.  
  4456. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  4457.  
  4458. /////////////////////////////////////////////////////////////////////////////
  4459. //
  4460. // Dialog
  4461. //
  4462.  
  4463. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 185 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs) - Increased Height
  4464. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  4465. CAPTION "New 8-Ball Game"
  4466. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  4467. BEGIN
  4468. // --- Game Mode Selection ---
  4469. // Group Box for Game Mode (Optional visually, but helps structure)
  4470. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  4471.  
  4472. // "2 Player" Radio Button (First in this group)
  4473. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  4474. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  4475.  
  4476. // "Human vs CPU" Radio Button
  4477. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  4478. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  4479.  
  4480.  
  4481. // --- AI Difficulty Selection (Inside its own Group Box) ---
  4482. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  4483.  
  4484. // "Easy" Radio Button (First in the AI group)
  4485. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  4486. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  4487.  
  4488. // "Medium" Radio Button
  4489. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  4490. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  4491.  
  4492. // "Hard" Radio Button
  4493. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  4494. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  4495.  
  4496. // --- Opening Break Modes (For Versus CPU Only) ---
  4497. GROUPBOX        "Opening Break Modes:", IDC_GROUP_BREAK_MODE, 118, 82, 95, 60
  4498.  
  4499. // "CPU Break" Radio Button (Default for this group)
  4500. CONTROL         "&CPU Break", IDC_RADIO_CPU_BREAK, "Button",
  4501. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 95, 70, 10
  4502.  
  4503. // "P1 Break" Radio Button
  4504. CONTROL         "&P1 Break", IDC_RADIO_P1_BREAK, "Button",
  4505. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 110, 70, 10
  4506.  
  4507. // "FlipCoin Break" Radio Button
  4508. CONTROL         "&FlipCoin Break", IDC_RADIO_FLIP_BREAK, "Button",
  4509. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 125, 70, 10
  4510.  
  4511.  
  4512. // --- Standard Buttons ---
  4513. DEFPUSHBUTTON   "Start", IDOK, 55, 160, 50, 14 // Default button (Enter key) - Adjusted Y position
  4514. PUSHBUTTON      "Cancel", IDCANCEL, 115, 160, 50, 14 // Adjusted Y position
  4515. END
  4516.  
  4517. ```
Advertisement
Add Comment
Please, Sign In to add comment