alien_fx_fiend

Alt# Pool Modfiication By ChatGPT4o (MAY BE BROKEN)

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