alien_fx_fiend

Pool Modification 8BallPocketSelectionIndicator (UNTESTED)

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