alien_fx_fiend

Pool Original Stable w/o Experimental Features (JUSTINCASE)

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