alien_fx_fiend

2D StickPool Game C++ D2D VectorGFX (O3 AI's CPU Revamp + PIA Fixed + Off-By-1 Fixed Complete V23)

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