alien_fx_fiend

Direct2D 8-Ball Pool Using Vector Graphics: Improved AIBreakShot()+AI Foul Move Ball Anywhere+Config

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