alien_fx_fiend

2D 8-Ball Pool Using Vector Graphics: Minor Glitches Fixed + Improvements V3

Apr 25th, 2025 (edited)
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 111.88 KB | Source Code | 0 0
  1. ==++ Here's the full source for (file 1/3 (No OOP-based)) "Pool-Game-Clone.cpp"::: ++==
  2. ```Pool-Game-Clone.cpp
  3. #define WIN32_LEAN_AND_MEAN
  4. #define NOMINMAX
  5. #include <windows.h>
  6. #include <d2d1.h>
  7. #include <dwrite.h>
  8. #include <vector>
  9. #include <cmath>
  10. #include <string>
  11. #include <sstream> // Required for wostringstream
  12. #include <algorithm> // Required for std::max, std::min
  13. #include <ctime>    // Required for srand, time
  14. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  15. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  16. #include "resource.h"
  17.  
  18. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  19. #pragma comment(lib, "d2d1.lib")
  20. #pragma comment(lib, "dwrite.lib")
  21.  
  22. // --- Constants ---
  23. const float PI = 3.1415926535f;
  24. const float BALL_RADIUS = 10.0f;
  25. const float TABLE_LEFT = 100.0f;
  26. const float TABLE_TOP = 100.0f;
  27. const float TABLE_WIDTH = 700.0f;
  28. const float TABLE_HEIGHT = 350.0f;
  29. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  30. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  31. const float CUSHION_THICKNESS = 20.0f;
  32. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  33. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS; // Make detection radius match visual size (or slightly larger)
  34. const float MAX_SHOT_POWER = 15.0f;
  35. const float FRICTION = 0.985f; // Friction factor per frame
  36. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  37. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  38. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  39. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  40. const UINT ID_TIMER = 1;
  41. const int TARGET_FPS = 60; // Target frames per second for timer
  42.  
  43. // --- Enums ---
  44. // --- MODIFIED/NEW Enums ---
  45. enum GameState {
  46.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  47.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  48.    BREAKING,           // Player is aiming/shooting the break shot
  49.    AIMING,             // Player is aiming
  50.    AI_THINKING,        // NEW: AI is calculating its move
  51.    SHOT_IN_PROGRESS,   // Balls are moving
  52.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  53.    PLAYER1_TURN,
  54.    PLAYER2_TURN,
  55.    BALL_IN_HAND_P1,
  56.    BALL_IN_HAND_P2,
  57.    GAME_OVER
  58. };
  59.  
  60. enum BallType {
  61.    NONE,
  62.    SOLID,  // Yellow (1-7)
  63.    STRIPE, // Red (9-15)
  64.    EIGHT_BALL, // Black (8)
  65.    CUE_BALL // White (0)
  66. };
  67.  
  68. // NEW Enums for Game Mode and AI Difficulty
  69. enum GameMode {
  70.    HUMAN_VS_HUMAN,
  71.    HUMAN_VS_AI
  72. };
  73.  
  74. enum AIDifficulty {
  75.    EASY,
  76.    MEDIUM,
  77.    HARD
  78. };
  79.  
  80. // --- Structs ---
  81. struct Ball {
  82.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  83.    BallType type;
  84.    float x, y;
  85.    float vx, vy;
  86.    D2D1_COLOR_F color;
  87.    bool isPocketed;
  88. };
  89.  
  90. struct PlayerInfo {
  91.    BallType assignedType;
  92.    int ballsPocketedCount;
  93.    std::wstring name;
  94. };
  95.  
  96. // --- Global Variables ---
  97.  
  98. // Direct2D & DirectWrite
  99. ID2D1Factory* pFactory = nullptr;
  100. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  101. IDWriteFactory* pDWriteFactory = nullptr;
  102. IDWriteTextFormat* pTextFormat = nullptr;
  103. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  104.  
  105. // Game State
  106. HWND hwndMain = nullptr;
  107. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  108. std::vector<Ball> balls;
  109. int currentPlayer = 1; // 1 or 2
  110. PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
  111. PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
  112. bool foulCommitted = false;
  113. std::wstring gameOverMessage = L"";
  114. bool firstBallPocketedAfterBreak = false;
  115. std::vector<int> pocketedThisTurn;
  116.  
  117. // NEW Game Mode/AI Globals
  118. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  119. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  120. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  121. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  122. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  123.  
  124. // Input & Aiming
  125. POINT ptMouse = { 0, 0 };
  126. bool isAiming = false;
  127. bool isDraggingCueBall = false;
  128. bool isSettingEnglish = false;
  129. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  130. float cueAngle = 0.0f;
  131. float shotPower = 0.0f;
  132. float cueSpinX = 0.0f; // Range -1 to 1
  133. float cueSpinY = 0.0f; // Range -1 to 1
  134.  
  135. // UI Element Positions
  136. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  137. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  138. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  139. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  140. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  141.  
  142. // Corrected Pocket Center Positions (aligned with table corners/edges)
  143. const D2D1_POINT_2F pocketPositions[6] = {
  144.    {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  145.    {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  146.    {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  147.    {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  148.    {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  149.    {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  150. };
  151.  
  152. // Colors
  153. const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.1f); // Darker Green
  154. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  155. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  156. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  157. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  158. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
  159. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red);   // Stripes = Red
  160. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  161. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  162. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  163. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  164. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  165.  
  166. // --- Forward Declarations ---
  167. HRESULT CreateDeviceResources();
  168. void DiscardDeviceResources();
  169. void OnPaint();
  170. void OnResize(UINT width, UINT height);
  171. void InitGame();
  172. void GameUpdate();
  173. void UpdatePhysics();
  174. void CheckCollisions();
  175. bool CheckPockets(); // Returns true if any ball was pocketed
  176. void ProcessShotResults();
  177. void ApplyShot(float power, float angle, float spinX, float spinY);
  178. void RespawnCueBall(bool behindHeadstring);
  179. bool AreBallsMoving();
  180. void SwitchTurns();
  181. void AssignPlayerBallTypes(BallType firstPocketedType);
  182. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  183. Ball* GetBallById(int id);
  184. Ball* GetCueBall();
  185.  
  186. // Drawing Functions
  187. void DrawScene(ID2D1RenderTarget* pRT);
  188. void DrawTable(ID2D1RenderTarget* pRT);
  189. void DrawBalls(ID2D1RenderTarget* pRT);
  190. void DrawCueStick(ID2D1RenderTarget* pRT);
  191. void DrawAimingAids(ID2D1RenderTarget* pRT);
  192. void DrawUI(ID2D1RenderTarget* pRT);
  193. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  194. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  195. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  196. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  197.  
  198. // Helper Functions
  199. float GetDistance(float x1, float y1, float x2, float y2);
  200. float GetDistanceSq(float x1, float y1, float x2, float y2);
  201. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  202. template <typename T> void SafeRelease(T** ppT);
  203.  
  204. // --- NEW Forward Declarations ---
  205.  
  206. // AI Related
  207. struct AIShotInfo; // Define below
  208. void TriggerAIMove();
  209. void AIMakeDecision();
  210. void AIPlaceCueBall();
  211. AIShotInfo AIFindBestShot();
  212. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  213. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  214. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  215. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  216. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  217. bool IsValidAIAimAngle(float angle); // Basic check
  218.  
  219. // Dialog Related
  220. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  221. void ShowNewGameDialog(HINSTANCE hInstance);
  222. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  223.  
  224. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  225. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  226.  
  227. // --- NEW Struct for AI Shot Evaluation ---
  228. struct AIShotInfo {
  229.    bool possible = false;          // Is this shot considered viable?
  230.    Ball* targetBall = nullptr;     // Which ball to hit
  231.    int pocketIndex = -1;           // Which pocket to aim for (0-5)
  232.    D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  233.    float angle = 0.0f;             // Calculated shot angle
  234.    float power = 0.0f;             // Calculated shot power
  235.    float score = -1.0f;            // Score for this shot (higher is better)
  236.    bool involves8Ball = false;     // Is the target the 8-ball?
  237. };
  238.  
  239. // --- NEW Dialog Procedure ---
  240. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  241.    switch (message) {
  242.    case WM_INITDIALOG:
  243.        // Set initial state based on current global settings (or defaults)
  244.        CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  245.  
  246.        CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  247.            (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  248.  
  249.        // Enable/Disable AI group based on initial mode
  250.        EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  251.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  252.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  253.        EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  254.  
  255.        return (INT_PTR)TRUE;
  256.  
  257.    case WM_COMMAND:
  258.        switch (LOWORD(wParam)) {
  259.        case IDC_RADIO_2P:
  260.        case IDC_RADIO_CPU:
  261.        {
  262.            bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  263.            // Enable/Disable AI group controls based on selection
  264.            EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  265.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  266.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  267.            EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  268.        }
  269.        return (INT_PTR)TRUE;
  270.  
  271.        case IDOK:
  272.            // Retrieve selected options and store in global variables
  273.            if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  274.                gameMode = HUMAN_VS_AI;
  275.                if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  276.                else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  277.                else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  278.            }
  279.            else {
  280.                gameMode = HUMAN_VS_HUMAN;
  281.            }
  282.            EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  283.            return (INT_PTR)TRUE;
  284.  
  285.        case IDCANCEL: // Handle Cancel or closing the dialog
  286.            EndDialog(hDlg, IDCANCEL);
  287.            return (INT_PTR)TRUE;
  288.        }
  289.        break; // End WM_COMMAND
  290.    }
  291.    return (INT_PTR)FALSE; // Default processing
  292. }
  293.  
  294. // --- NEW Helper to Show Dialog ---
  295. void ShowNewGameDialog(HINSTANCE hInstance) {
  296.    if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  297.        // User clicked Start, reset game with new settings
  298.        isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  299.        if (isPlayer2AI) {
  300.            switch (aiDifficulty) {
  301.            case EASY: player2Info.name = L"CPU (Easy)"; break;
  302.            case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  303.            case HARD: player2Info.name = L"CPU (Hard)"; break;
  304.            }
  305.        }
  306.        else {
  307.            player2Info.name = L"Player 2";
  308.        }
  309.        // Update window title
  310.        std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  311.        if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  312.        else windowTitle += L" (Human vs " + player2Info.name + L")";
  313.        SetWindowText(hwndMain, windowTitle.c_str());
  314.  
  315.        InitGame(); // Re-initialize game logic & board
  316.        InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  317.    }
  318.    else {
  319.        // User cancelled dialog - maybe just resume game? Or exit?
  320.        // For simplicity, we do nothing, game continues as it was.
  321.        // To exit on cancel from F2, would need more complex state management.
  322.    }
  323. }
  324.  
  325. // --- NEW Reset Game Function ---
  326. void ResetGame(HINSTANCE hInstance) {
  327.    // Call the helper function to show the dialog and re-init if OK clicked
  328.    ShowNewGameDialog(hInstance);
  329. }
  330.  
  331. // --- WinMain ---
  332. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  333.    if (FAILED(CoInitialize(NULL))) {
  334.        MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  335.        return -1;
  336.    }
  337.  
  338.    // --- NEW: Show configuration dialog FIRST ---
  339.    if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  340.        // User cancelled the dialog
  341.        CoUninitialize();
  342.        return 0; // Exit gracefully if dialog cancelled
  343.    }
  344.    // Global gameMode and aiDifficulty are now set by the DialogProc
  345.  
  346.    // Set AI flag based on game mode
  347.    isPlayer2AI = (gameMode == HUMAN_VS_AI);
  348.    if (isPlayer2AI) {
  349.        switch (aiDifficulty) {
  350.        case EASY: player2Info.name = L"CPU (Easy)"; break;
  351.        case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  352.        case HARD: player2Info.name = L"CPU (Hard)"; break;
  353.        }
  354.    }
  355.    else {
  356.        player2Info.name = L"Player 2";
  357.    }
  358.    // --- End of Dialog Logic ---
  359.  
  360.  
  361.    WNDCLASS wc = { };
  362.    wc.lpfnWndProc = WndProc;
  363.    wc.hInstance = hInstance;
  364.    wc.lpszClassName = L"Direct2D_8BallPool";
  365.    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  366.    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  367.    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
  368.  
  369.    if (!RegisterClass(&wc)) {
  370.        MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  371.        CoUninitialize();
  372.        return -1;
  373.    }
  374.  
  375.    // --- Change Window Title based on mode ---
  376.    std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  377.    if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  378.    else windowTitle += L" (Human vs " + player2Info.name + L")";
  379.  
  380.  
  381.    hwndMain = CreateWindowEx(
  382.        0, L"Direct2D_8BallPool", windowTitle.c_str(), WS_OVERLAPPEDWINDOW,
  383.        CW_USEDEFAULT, CW_USEDEFAULT, 1000, 700,
  384.        NULL, NULL, hInstance, NULL
  385.    );
  386.  
  387.    if (!hwndMain) {
  388.        MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  389.        CoUninitialize();
  390.        return -1;
  391.    }
  392.  
  393.    // Initialize Direct2D Resources AFTER window creation
  394.    if (FAILED(CreateDeviceResources())) {
  395.        MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  396.        DestroyWindow(hwndMain);
  397.        CoUninitialize();
  398.        return -1;
  399.    }
  400.  
  401.    InitGame(); // Initialize game state AFTER resources are ready & mode is set
  402.  
  403.    ShowWindow(hwndMain, nCmdShow);
  404.    UpdateWindow(hwndMain);
  405.  
  406.    if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  407.        MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  408.        DestroyWindow(hwndMain);
  409.        CoUninitialize();
  410.        return -1;
  411.    }
  412.  
  413.    MSG msg = { };
  414.    // --- Modified Main Loop ---
  415.    // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  416.    // or gets reset to it via F2. The main loop runs normally once game starts.
  417.    while (GetMessage(&msg, NULL, 0, 0)) {
  418.        // We might need modeless dialog handling here if F2 shows dialog
  419.        // while window is active, but DialogBoxParam is modal.
  420.        // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  421.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  422.         TranslateMessage(&msg);
  423.         DispatchMessage(&msg);
  424.     }
  425.  
  426.  
  427.     KillTimer(hwndMain, ID_TIMER);
  428.     DiscardDeviceResources();
  429.     CoUninitialize();
  430.  
  431.     return (int)msg.wParam;
  432. }
  433.  
  434. // --- WndProc ---
  435. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  436.     switch (msg) {
  437.     case WM_CREATE:
  438.         // Resources are now created in WinMain after CreateWindowEx
  439.         return 0;
  440.  
  441.     case WM_PAINT:
  442.         OnPaint();
  443.         // Validate the entire window region after painting
  444.         ValidateRect(hwnd, NULL);
  445.         return 0;
  446.  
  447.     case WM_SIZE: {
  448.         UINT width = LOWORD(lParam);
  449.         UINT height = HIWORD(lParam);
  450.         OnResize(width, height);
  451.         return 0;
  452.     }
  453.  
  454.     case WM_TIMER:
  455.         if (wParam == ID_TIMER) {
  456.             GameUpdate(); // Update game logic and physics
  457.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  458.         }
  459.         return 0;
  460.  
  461.         // --- NEW: Handle F2 Key for Reset ---
  462.     case WM_KEYDOWN:
  463.         if (wParam == VK_F2) {
  464.             // Get HINSTANCE from the window handle
  465.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  466.             ResetGame(hInstance); // Call reset function
  467.         }
  468.         return 0; // Indicate key was processed
  469.  
  470.     case WM_MOUSEMOVE: {
  471.         ptMouse.x = LOWORD(lParam);
  472.         ptMouse.y = HIWORD(lParam);
  473.  
  474.         Ball* cueBall = GetCueBall();
  475.         if (!cueBall) return 0;
  476.  
  477.         // Logic for dragging cue ball during ball-in-hand (unchanged)
  478.         if (isDraggingCueBall && (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)) {
  479.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  480.             if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  481.                 cueBall->x = (float)ptMouse.x;
  482.                 cueBall->y = (float)ptMouse.y;
  483.                 cueBall->vx = cueBall->vy = 0; // Ensure it's stopped
  484.             }
  485.         }
  486.         // Logic for aiming drag (unchanged math, just context)
  487.         else if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  488.             float dx = (float)ptMouse.x - cueBall->x;
  489.             float dy = (float)ptMouse.y - cueBall->y;
  490.             // Prevent setting angle if mouse is exactly on cue ball center
  491.             if (dx != 0 || dy != 0) {
  492.                 cueAngle = atan2f(dy, dx);
  493.             }
  494.             // Calculate power based on distance pulled back from the initial click point (aimStartPoint)
  495.             float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  496.             // Scale power more aggressively, maybe? Or keep scale factor 10.0
  497.             shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER); // Scale power, clamp to max
  498.         }
  499.         // Logic for setting english (unchanged)
  500.         else if (isSettingEnglish) {
  501.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  502.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  503.             float dist = GetDistance(dx, dy, 0, 0);
  504.             if (dist > spinIndicatorRadius) { // Clamp to edge
  505.                 dx *= spinIndicatorRadius / dist;
  506.                 dy *= spinIndicatorRadius / dist;
  507.             }
  508.             cueSpinX = dx / spinIndicatorRadius; // Normalize to -1 to 1
  509.             cueSpinY = dy / spinIndicatorRadius;
  510.         }
  511.         // InvalidateRect is handled by WM_TIMER
  512.         return 0;
  513.     }
  514.  
  515.     case WM_LBUTTONDOWN: {
  516.         ptMouse.x = LOWORD(lParam);
  517.         ptMouse.y = HIWORD(lParam);
  518.  
  519.         // Check if clicking on Spin Indicator (unchanged)
  520.         float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  521.         if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius) {
  522.             isSettingEnglish = true;
  523.             // Update spin immediately on click
  524.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  525.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  526.             cueSpinX = dx / spinIndicatorRadius;
  527.             cueSpinY = dy / spinIndicatorRadius;
  528.             return 0; // Don't process other clicks if setting english
  529.         }
  530.  
  531.  
  532.         Ball* cueBall = GetCueBall();
  533.         if (!cueBall) return 0;
  534.  
  535.         // Logic for Ball-in-Hand placement click (unchanged)
  536.         if (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT) {
  537.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  538.             if (distSq < BALL_RADIUS * BALL_RADIUS * 4) { // Allow clicking near the ball to start drag
  539.                 isDraggingCueBall = true;
  540.             }
  541.             else { // If clicking elsewhere on the table (and valid), place the ball
  542.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  543.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  544.                     cueBall->x = (float)ptMouse.x;
  545.                     cueBall->y = (float)ptMouse.y;
  546.                     cueBall->vx = cueBall->vy = 0;
  547.                     isDraggingCueBall = false;
  548.                     // Transition state appropriate to ending placement
  549.                     if (currentGameState == PRE_BREAK_PLACEMENT) {
  550.                         // Depends on who is breaking
  551.                         currentGameState = BREAKING;
  552.                         // If AI was breaking, aiTurnPending should still be true
  553.                     }
  554.                     else if (currentGameState == BALL_IN_HAND_P1) {
  555.                         currentGameState = PLAYER1_TURN;
  556.                     }
  557.                     else if (currentGameState == BALL_IN_HAND_P2) {
  558.                         // If AI placed ball, AIMakeDecision should have been called? Or trigger now?
  559.                         // Assuming SwitchTurns/Respawn set aiTurnPending correctly earlier
  560.                         currentGameState = PLAYER2_TURN; // Ready for AI/Human P2 to aim
  561.                     }
  562.                 }
  563.             }
  564.         }
  565.         // --- MODIFIED: Logic for starting aim ---
  566.         else if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  567.             // Allow initiating aim by clicking in a larger radius around the cue ball
  568.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  569.             // Increased radius check (e.g., 5x ball radius squared)
  570.             if (distSq < BALL_RADIUS * BALL_RADIUS * 25) { // Click somewhat close to cue ball
  571.                 isAiming = true;
  572.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Store where aiming drag started
  573.                 shotPower = 0; // Reset power
  574.                 // Transition to AIMING state (if not already BREAKING)
  575.                 if (currentGameState != BREAKING) {
  576.                     currentGameState = AIMING;
  577.                 }
  578.                 // Set initial cueAngle based on click relative to ball, for immediate feedback
  579.                 float dx = (float)ptMouse.x - cueBall->x;
  580.                 float dy = (float)ptMouse.y - cueBall->y;
  581.                 if (dx != 0 || dy != 0) {
  582.                     cueAngle = atan2f(dy, dx);
  583.                     // If starting aim by clicking, maybe point stick towards mouse initially?
  584.                     // Current logic updates angle on MOUSEMOVE anyway.
  585.                 }
  586.             }
  587.         }
  588.         return 0;
  589.     }
  590.  
  591.     case WM_LBUTTONUP: {
  592.         ptMouse.x = LOWORD(lParam);
  593.         ptMouse.y = HIWORD(lParam);
  594.  
  595.         if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  596.             isAiming = false; // Stop the aiming drag visual state
  597.  
  598.             // --- MODIFIED: Increased threshold for taking shot ---
  599.             if (shotPower > 0.15f) { // Only shoot if power is significant enough
  600.                 // Prevent player from shooting if it's AI's turn calculation phase
  601.                 if (currentGameState != AI_THINKING) {
  602.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  603.                     currentGameState = SHOT_IN_PROGRESS;
  604.                     foulCommitted = false; // Reset foul flag for the new shot
  605.                     pocketedThisTurn.clear();
  606.                 }
  607.             }
  608.             // If shotPower is too low, reset state back to player's turn
  609.             else if (currentGameState != AI_THINKING) {
  610.                 // If no power, revert state back without shooting
  611.                 if (currentGameState == BREAKING) {
  612.                     // Still breaking state if power was too low
  613.                 }
  614.                 else {
  615.                     // Revert to appropriate player turn state
  616.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  617.                     // Clear pending AI turn flag if it somehow got set during a zero-power human shot attempt
  618.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  619.                 }
  620.             }
  621.             shotPower = 0; // Reset power indicator regardless of shot taken
  622.         }
  623.  
  624.         // Logic for releasing cue ball after dragging (unchanged)
  625.         if (isDraggingCueBall) {
  626.             isDraggingCueBall = false;
  627.             // After placing the ball, transition state if needed (state might already be set by click placement)
  628.             if (currentGameState == PRE_BREAK_PLACEMENT) {
  629.                 currentGameState = BREAKING;
  630.             }
  631.             else if (currentGameState == BALL_IN_HAND_P1) {
  632.                 currentGameState = PLAYER1_TURN;
  633.             }
  634.             else if (currentGameState == BALL_IN_HAND_P2) {
  635.                 currentGameState = PLAYER2_TURN;
  636.                 // If AI placed, aiTurnPending should trigger AI on next GameUpdate
  637.             }
  638.         }
  639.         // Logic for releasing english setting (unchanged)
  640.         if (isSettingEnglish) {
  641.             isSettingEnglish = false;
  642.         }
  643.         return 0;
  644.     }
  645.  
  646.     case WM_DESTROY:
  647.         PostQuitMessage(0);
  648.         return 0;
  649.  
  650.     default:
  651.         return DefWindowProc(hwnd, msg, wParam, lParam);
  652.     }
  653.     return 0;
  654. }
  655.  
  656. // --- Direct2D Resource Management ---
  657.  
  658. HRESULT CreateDeviceResources() {
  659.     HRESULT hr = S_OK;
  660.  
  661.     // Create Direct2D Factory
  662.     if (!pFactory) {
  663.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  664.         if (FAILED(hr)) return hr;
  665.     }
  666.  
  667.     // Create DirectWrite Factory
  668.     if (!pDWriteFactory) {
  669.         hr = DWriteCreateFactory(
  670.             DWRITE_FACTORY_TYPE_SHARED,
  671.             __uuidof(IDWriteFactory),
  672.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  673.         );
  674.         if (FAILED(hr)) return hr;
  675.     }
  676.  
  677.     // Create Text Formats
  678.     if (!pTextFormat && pDWriteFactory) {
  679.         hr = pDWriteFactory->CreateTextFormat(
  680.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  681.             16.0f, L"en-us", &pTextFormat
  682.         );
  683.         if (FAILED(hr)) return hr;
  684.         // Center align text
  685.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  686.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  687.     }
  688.     if (!pLargeTextFormat && pDWriteFactory) {
  689.         hr = pDWriteFactory->CreateTextFormat(
  690.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  691.             48.0f, L"en-us", &pLargeTextFormat
  692.         );
  693.         if (FAILED(hr)) return hr;
  694.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  695.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  696.     }
  697.  
  698.  
  699.     // Create Render Target (needs valid hwnd)
  700.     if (!pRenderTarget && hwndMain) {
  701.         RECT rc;
  702.         GetClientRect(hwndMain, &rc);
  703.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  704.  
  705.         hr = pFactory->CreateHwndRenderTarget(
  706.             D2D1::RenderTargetProperties(),
  707.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  708.             &pRenderTarget
  709.         );
  710.         if (FAILED(hr)) {
  711.             // If failed, release factories if they were created in this call
  712.             SafeRelease(&pTextFormat);
  713.             SafeRelease(&pLargeTextFormat);
  714.             SafeRelease(&pDWriteFactory);
  715.             SafeRelease(&pFactory);
  716.             pRenderTarget = nullptr; // Ensure it's null on failure
  717.             return hr;
  718.         }
  719.     }
  720.  
  721.     return hr;
  722. }
  723.  
  724. void DiscardDeviceResources() {
  725.     SafeRelease(&pRenderTarget);
  726.     SafeRelease(&pTextFormat);
  727.     SafeRelease(&pLargeTextFormat);
  728.     SafeRelease(&pDWriteFactory);
  729.     // Keep pFactory until application exit? Or release here too? Let's release.
  730.     SafeRelease(&pFactory);
  731. }
  732.  
  733. void OnResize(UINT width, UINT height) {
  734.     if (pRenderTarget) {
  735.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  736.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  737.     }
  738. }
  739.  
  740. // --- Game Initialization ---
  741. void InitGame() {
  742.     srand((unsigned int)time(NULL)); // Seed random number generator
  743.  
  744.     // --- Ensure pocketed list is clear from the absolute start ---
  745.     pocketedThisTurn.clear();
  746.  
  747.     balls.clear(); // Clear existing balls
  748.  
  749.     // Reset Player Info (Keep names set by Dialog/wWinMain)
  750.     player1Info.assignedType = BallType::NONE;
  751.     player1Info.ballsPocketedCount = 0;
  752.     player2Info.assignedType = BallType::NONE;
  753.     player2Info.ballsPocketedCount = 0;
  754.     // Note: Player names (player1Info.name, player2Info.name) should be set previously
  755.  
  756.     // Create Cue Ball (ID 0)
  757.     balls.push_back({ 0, BallType::CUE_BALL, HEADSTRING_X * 0.5f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  758.  
  759.     // --- Create Object Balls (Temporary List) ---
  760.     std::vector<Ball> objectBalls;
  761.     // Solids (1-7, Yellow)
  762.     for (int i = 1; i <= 7; ++i) {
  763.         objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  764.     }
  765.     // Stripes (9-15, Red)
  766.     for (int i = 9; i <= 15; ++i) {
  767.         objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  768.     }
  769.     // 8-Ball (ID 8) - Add it to the list to be placed
  770.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  771.  
  772.  
  773.     // --- Racking Logic ---
  774.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  775.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  776.  
  777.     // Define rack positions (0-14 indices corresponding to triangle spots)
  778.     D2D1_POINT_2F rackPositions[15];
  779.     int rackIndex = 0;
  780.     for (int row = 0; row < 5; ++row) {
  781.         for (int col = 0; col <= row; ++col) {
  782.             if (rackIndex >= 15) break;
  783.             float x = RACK_POS_X + row * spacingX;
  784.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  785.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  786.         }
  787.     }
  788.  
  789.     // Separate 8-ball
  790.     Ball eightBall;
  791.     std::vector<Ball> otherBalls; // Solids and Stripes
  792.     for (const auto& ball : objectBalls) {
  793.         if (ball.id == 8) {
  794.             eightBall = ball;
  795.         }
  796.         else {
  797.             otherBalls.push_back(ball);
  798.         }
  799.     }
  800.  
  801.     // Shuffle the other 14 balls
  802.     // Use std::shuffle if available (C++11 and later) for better randomness
  803.     // std::random_device rd;
  804.     // std::mt19937 g(rd());
  805.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  806.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  807.  
  808.     // --- Place balls into the main 'balls' vector in rack order ---
  809.  
  810.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  811.     int eightBallRackIndex = 4;
  812.     eightBall.x = rackPositions[eightBallRackIndex].x;
  813.     eightBall.y = rackPositions[eightBallRackIndex].y;
  814.     eightBall.isPocketed = false;
  815.     balls.push_back(eightBall);
  816.  
  817.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  818.     int otherBallIdx = 0;
  819.     for (int i = 0; i < 15; ++i) {
  820.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  821.  
  822.         if (otherBallIdx < otherBalls.size()) {
  823.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  824.             ballToPlace.x = rackPositions[i].x;
  825.             ballToPlace.y = rackPositions[i].y;
  826.             ballToPlace.isPocketed = false;
  827.             balls.push_back(ballToPlace); // Add to the main game vector
  828.         }
  829.     }
  830.  
  831.     // Ensure corner balls are different types (optional refinement - more complex with new logic)
  832.     // This part is harder now that balls are placed scattered. Could analyze balls at indices 10 & 14 after placement and swap if needed.
  833.     // For simplicity, we'll omit the corner-swap check for now, relying on the shuffle.
  834.  
  835.  
  836.     // --- ADDITIONS FOR AI MODE and Initial State ---
  837.     if (isPlayer2AI) {
  838.         // Name is already set based on dialog selection
  839.  
  840.         // Randomly decide who breaks (50/50 chance)
  841.         if ((rand() % 2) == 0) {
  842.             // AI (Player 2) breaks
  843.             currentPlayer = 2;
  844.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  845.             aiTurnPending = true; // Trigger AI logic
  846.         }
  847.         else {
  848.             // Player 1 (Human) breaks
  849.             currentPlayer = 1;
  850.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  851.             aiTurnPending = false; // Ensure AI doesn't act
  852.         }
  853.     }
  854.     else {
  855.         // Human vs Human, Player 1 breaks
  856.         currentPlayer = 1;
  857.         currentGameState = PRE_BREAK_PLACEMENT;
  858.         aiTurnPending = false; // No AI involved
  859.     }
  860.  
  861.     // Reset other relevant game state variables
  862.     foulCommitted = false;
  863.     gameOverMessage = L"";
  864.     firstBallPocketedAfterBreak = false;
  865.     // pocketedThisTurn.clear(); // Already cleared at the start
  866.     // Reset shot parameters and input flags
  867.     shotPower = 0.0f;
  868.     cueSpinX = 0.0f;
  869.     cueSpinY = 0.0f;
  870.     isAiming = false;
  871.     isDraggingCueBall = false;
  872.     isSettingEnglish = false;
  873.     cueAngle = 0.0f; // Reset aim angle
  874. }
  875.  
  876.  
  877. // --- Game Loop ---
  878. void GameUpdate() {
  879.     if (currentGameState == SHOT_IN_PROGRESS) {
  880.         UpdatePhysics();
  881.         CheckCollisions();
  882.         bool pocketed = CheckPockets(); // Store if any ball was pocketed
  883.  
  884.         if (!AreBallsMoving()) {
  885.             ProcessShotResults(); // Determine next state based on what happened
  886.         }
  887.     }
  888.  
  889.     // --- NEW: Check if AI needs to act ---
  890.     else if (aiTurnPending && !AreBallsMoving()) {
  891.         // Check if it's genuinely AI's turn state and not mid-shot etc.
  892.         if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING || currentGameState == PRE_BREAK_PLACEMENT) {
  893.             // Only trigger if AI is P2, it's their turn/break, and balls stopped
  894.             if (isPlayer2AI && currentPlayer == 2) {
  895.                 // Transition state to show AI is thinking
  896.                 currentGameState = AI_THINKING;
  897.                 aiTurnPending = false; // Acknowledge the pending flag
  898.  
  899.                 // --- Trigger AI Decision Making ---
  900.                 // In a real game loop, you might start a timer here or background thread.
  901.                 // For simplicity here, we call it directly. This might pause rendering
  902.                 // briefly if AI calculation is slow.
  903.                 AIMakeDecision(); // AI calculates and applies shot
  904.  
  905.                 // AIMakeDecision should end by calling ApplyShot, which sets
  906.                 // currentGameState = SHOT_IN_PROGRESS
  907.                 // If AI fails to find a shot, need to handle that (e.g., pass turn - should be rare)
  908.             }
  909.             else {
  910.                 aiTurnPending = false; // Clear flag if conditions not met (e.g. P1's turn somehow)
  911.             }
  912.         }
  913.         else {
  914.             aiTurnPending = false; // Clear flag if not in a state where AI should shoot
  915.         }
  916.     }
  917.  
  918.     // Other states (AIMING, BALL_IN_HAND, etc.) are handled by input messages
  919. }
  920.  
  921. // --- Physics and Collision ---
  922. void UpdatePhysics() {
  923.     for (size_t i = 0; i < balls.size(); ++i) {
  924.         Ball& b = balls[i];
  925.         if (!b.isPocketed) {
  926.             b.x += b.vx;
  927.             b.y += b.vy;
  928.  
  929.             // Apply friction
  930.             b.vx *= FRICTION;
  931.             b.vy *= FRICTION;
  932.  
  933.             // Stop balls if velocity is very low
  934.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  935.                 b.vx = 0;
  936.                 b.vy = 0;
  937.             }
  938.         }
  939.     }
  940. }
  941.  
  942. void CheckCollisions() {
  943.     // --- Corrected Collision Boundaries ---
  944.     // These now represent the actual edges of the playable table surface
  945.     float left = TABLE_LEFT;
  946.     float right = TABLE_RIGHT;
  947.     float top = TABLE_TOP;
  948.     float bottom = TABLE_BOTTOM;
  949.  
  950.     // Define a radius around pocket centers to check if a ball is near a pocket mouth
  951.     // Use a value slightly larger than the pocket radius to prevent clipping the edge
  952.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f; // Check slightly larger area
  953.  
  954.     for (size_t i = 0; i < balls.size(); ++i) {
  955.         Ball& b1 = balls[i];
  956.         if (b1.isPocketed) continue; // Skip balls already pocketed
  957.  
  958.         // --- Pre-calculate proximity to pocket centers ---
  959.         // This avoids recalculating distances multiple times for wall checks
  960.         bool nearPocket[6];
  961.         for (int p = 0; p < 6; ++p) {
  962.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  963.         }
  964.         // Individual pocket proximity flags for clarity in wall checks
  965.         bool nearTopLeftPocket = nearPocket[0];
  966.         bool nearTopMidPocket = nearPocket[1];
  967.         bool nearTopRightPocket = nearPocket[2];
  968.         bool nearBottomLeftPocket = nearPocket[3];
  969.         bool nearBottomMidPocket = nearPocket[4];
  970.         bool nearBottomRightPocket = nearPocket[5];
  971.  
  972.  
  973.         // --- Ball-Wall Collisions (with Pocket Avoidance) ---
  974.         bool collidedWall = false; // Track if any wall collision happened for spin effects
  975.  
  976.         // Left Wall
  977.         if (b1.x - BALL_RADIUS < left) {
  978.             // Don't bounce if near top-left or bottom-left pocket mouths
  979.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  980.                 b1.x = left + BALL_RADIUS;
  981.                 b1.vx *= -1.0f;
  982.                 collidedWall = true;
  983.             } // else: Allow ball to continue towards pocket
  984.         }
  985.         // Right Wall
  986.         if (b1.x + BALL_RADIUS > right) {
  987.             // Don't bounce if near top-right or bottom-right pocket mouths
  988.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  989.                 b1.x = right - BALL_RADIUS;
  990.                 b1.vx *= -1.0f;
  991.                 collidedWall = true;
  992.             } // else: Allow ball to continue towards pocket
  993.         }
  994.         // Top Wall
  995.         if (b1.y - BALL_RADIUS < top) {
  996.             // Don't bounce if near top-left, top-mid, or top-right pocket mouths
  997.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  998.                 b1.y = top + BALL_RADIUS;
  999.                 b1.vy *= -1.0f;
  1000.                 collidedWall = true;
  1001.             } // else: Allow ball to continue towards pocket
  1002.         }
  1003.         // Bottom Wall
  1004.         if (b1.y + BALL_RADIUS > bottom) {
  1005.             // Don't bounce if near bottom-left, bottom-mid, or bottom-right pocket mouths
  1006.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1007.                 b1.y = bottom - BALL_RADIUS;
  1008.                 b1.vy *= -1.0f;
  1009.                 collidedWall = true;
  1010.             } // else: Allow ball to continue towards pocket
  1011.         }
  1012.  
  1013.         // Optional: Apply simplified spin effect on wall collision IF a bounce occurred
  1014.         if (collidedWall) {
  1015.             // Simple spin damping/effect (can be refined)
  1016.             // Side spin affects vertical velocity on horizontal collision & vice-versa
  1017.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { // Hit L/R wall
  1018.                 b1.vy += cueSpinX * b1.vx * 0.05f; // Apply small vertical impulse based on side spin and horizontal velocity
  1019.             }
  1020.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { // Hit T/B wall
  1021.                 b1.vx -= cueSpinY * b1.vy * 0.05f; // Apply small horizontal impulse based on top/bottom spin and vertical velocity
  1022.             }
  1023.             // Dampen spin after wall hit
  1024.             cueSpinX *= 0.7f; // Increase damping maybe
  1025.             cueSpinY *= 0.7f;
  1026.         }
  1027.  
  1028.  
  1029.         // --- Ball-Ball Collisions ---
  1030.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1031.             Ball& b2 = balls[j];
  1032.             if (b2.isPocketed) continue; // Skip pocketed balls
  1033.  
  1034.             float dx = b2.x - b1.x;
  1035.             float dy = b2.y - b1.y;
  1036.             float distSq = dx * dx + dy * dy;
  1037.             float minDist = BALL_RADIUS * 2.0f;
  1038.  
  1039.             if (distSq > 0 && distSq < minDist * minDist) { // Check distance squared first
  1040.                 float dist = sqrtf(distSq);
  1041.                 float overlap = minDist - dist;
  1042.  
  1043.                 // Normalize collision vector
  1044.                 float nx = dx / dist;
  1045.                 float ny = dy / dist;
  1046.  
  1047.                 // Separate balls to prevent sticking
  1048.                 // Move each ball half the overlap distance along the collision normal
  1049.                 b1.x -= overlap * 0.5f * nx;
  1050.                 b1.y -= overlap * 0.5f * ny;
  1051.                 b2.x += overlap * 0.5f * nx;
  1052.                 b2.y += overlap * 0.5f * ny;
  1053.  
  1054.                 // Relative velocity
  1055.                 float rvx = b1.vx - b2.vx;
  1056.                 float rvy = b1.vy - b2.vy;
  1057.  
  1058.                 // Dot product of relative velocity and collision normal
  1059.                 // This represents the component of relative velocity along the collision line
  1060.                 float velAlongNormal = rvx * nx + rvy * ny;
  1061.  
  1062.                 // Only resolve collision if balls are moving towards each other (dot product > 0)
  1063.                 if (velAlongNormal > 0) {
  1064.                     // Calculate impulse scalar (simplified - assumes equal mass, perfect elasticity=1.0)
  1065.                    // For perfect elastic collision, the impulse magnitude needed is velAlongNormal.
  1066.                    // Each ball gets half the impulse if masses are equal, but since we apply to both in opposite directions along the normal,
  1067.                    // the change in velocity for each along the normal is 'velAlongNormal'.
  1068.                     float impulse = velAlongNormal; // Simplified impulse magnitude along normal
  1069.  
  1070.                     // Apply impulse to velocities along the collision normal
  1071.                     b1.vx -= impulse * nx;
  1072.                     b1.vy -= impulse * ny;
  1073.                     b2.vx += impulse * nx;
  1074.                     b2.vy += impulse * ny;
  1075.  
  1076.                     // Apply spin transfer/effect (Very simplified)
  1077.                     if (b1.id == 0 || b2.id == 0) { // If cue ball involved
  1078.                         float spinEffectFactor = 0.08f; // Reduced factor maybe
  1079.                         // Simple model: Apply a small velocity change perpendicular to the normal based on spin
  1080.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor; // Spin effect
  1081.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor; // Spin effect (check signs/logic)
  1082.  
  1083.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1084.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1085.  
  1086.                         // Dampen spin after transfer
  1087.                         cueSpinX *= 0.85f;
  1088.                         cueSpinY *= 0.85f;
  1089.                     }
  1090.                 }
  1091.             }
  1092.         } // End ball-ball collision loop
  1093.     } // End loop through balls
  1094. } // End CheckCollisions
  1095.  
  1096.  
  1097. bool CheckPockets() {
  1098.     bool ballPocketed = false;
  1099.     for (size_t i = 0; i < balls.size(); ++i) {
  1100.         Ball& b = balls[i];
  1101.         if (!b.isPocketed) {
  1102.             for (int p = 0; p < 6; ++p) {
  1103.                 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
  1104.                 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
  1105.                     b.isPocketed = true;
  1106.                     b.vx = b.vy = 0;
  1107.                     pocketedThisTurn.push_back(b.id); // Record pocketed ball ID
  1108.                     ballPocketed = true;
  1109.                     break; // No need to check other pockets for this ball
  1110.                 }
  1111.             }
  1112.         }
  1113.     }
  1114.     return ballPocketed;
  1115. }
  1116.  
  1117. bool AreBallsMoving() {
  1118.     for (size_t i = 0; i < balls.size(); ++i) {
  1119.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1120.             return true;
  1121.         }
  1122.     }
  1123.     return false;
  1124. }
  1125.  
  1126. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1127.     Ball* cueBall = GetCueBall();
  1128.     if (cueBall) {
  1129.         // Reset position to a default (AI/Human might move it)
  1130.         cueBall->x = HEADSTRING_X * 0.5f;
  1131.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1132.         cueBall->vx = 0;
  1133.         cueBall->vy = 0;
  1134.         cueBall->isPocketed = false;
  1135.  
  1136.         // Set state based on who gets ball-in-hand
  1137.         if (currentPlayer == 1) { // Player 1 caused foul, Player 2 gets ball-in-hand
  1138.             if (isPlayer2AI) {
  1139.                 // AI gets ball-in-hand. Set state and trigger AI.
  1140.                 currentGameState = PLAYER2_TURN; // State remains P2 Turn
  1141.                 aiTurnPending = true; // AI will handle placement in its logic
  1142.             }
  1143.             else {
  1144.                 // Human Player 2 gets ball-in-hand
  1145.                 currentGameState = BALL_IN_HAND_P2;
  1146.             }
  1147.         }
  1148.         else { // Player 2 caused foul, Player 1 gets ball-in-hand
  1149.             currentGameState = BALL_IN_HAND_P1;
  1150.             aiTurnPending = false; // Ensure AI flag off if P1 gets ball-in-hand
  1151.         }
  1152.     }
  1153. }
  1154.  
  1155.  
  1156. // --- Game Logic ---
  1157.  
  1158. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1159.     Ball* cueBall = GetCueBall();
  1160.     if (cueBall) {
  1161.         cueBall->vx = cosf(angle) * power;
  1162.         cueBall->vy = sinf(angle) * power;
  1163.  
  1164.         // Apply English (Spin) - Simplified effect
  1165.         // Top/Bottom spin affects initial roll slightly
  1166.         cueBall->vx += sinf(angle) * spinY * 0.5f; // Small effect perpendicular to shot dir
  1167.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1168.         // Side spin affects initial direction slightly
  1169.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1170.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1171.  
  1172.         // Store spin for later use in collisions/cushions (could decay over time too)
  1173.         cueSpinX = spinX;
  1174.         cueSpinY = spinY;
  1175.     }
  1176. }
  1177.  
  1178.  
  1179. void ProcessShotResults() {
  1180.     bool cueBallPocketed = false;
  1181.     bool eightBallPocketed = false;
  1182.     bool legalBallPocketed = false; // Player's own ball type
  1183.     bool opponentBallPocketed = false; // Opponent's ball type
  1184.     bool anyNonCueBallPocketed = false;
  1185.     BallType firstPocketedType = BallType::NONE; // Type of the first object ball pocketed
  1186.     int firstPocketedId = -1; // ID of the first object ball pocketed
  1187.  
  1188.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1189.     PlayerInfo& opponentPlayerInfo = (currentPlayer == 1) ? player2Info : player1Info;
  1190.  
  1191.     // Analyze pocketed balls from this shot sequence
  1192.     for (int pocketedId : pocketedThisTurn) {
  1193.         Ball* b = GetBallById(pocketedId);
  1194.         if (!b) continue; // Should not happen
  1195.  
  1196.         if (b->id == 0) {
  1197.             cueBallPocketed = true;
  1198.         }
  1199.         else if (b->id == 8) {
  1200.             eightBallPocketed = true;
  1201.         }
  1202.         else {
  1203.             anyNonCueBallPocketed = true;
  1204.             // Record the FIRST object ball pocketed in this turn
  1205.             if (firstPocketedId == -1) {
  1206.                 firstPocketedId = b->id;
  1207.                 firstPocketedType = b->type;
  1208.             }
  1209.  
  1210.             // Check if ball matches player's assigned type (if already assigned)
  1211.             if (currentPlayerInfo.assignedType != BallType::NONE) {
  1212.                 if (b->type == currentPlayerInfo.assignedType) {
  1213.                     legalBallPocketed = true;
  1214.                 }
  1215.                 else if (b->type == opponentPlayerInfo.assignedType) {
  1216.                     opponentBallPocketed = true; // Pocketed opponent's ball
  1217.                 }
  1218.             }
  1219.         }
  1220.     }
  1221.  
  1222.     // --- Game Over Checks --- (Unchanged)
  1223.     if (eightBallPocketed) {
  1224.         CheckGameOverConditions(eightBallPocketed, cueBallPocketed);
  1225.         if (currentGameState == GAME_OVER) return; // Stop processing if game ended
  1226.     }
  1227.  
  1228.     // --- Foul Checks --- (Unchanged)
  1229.     bool turnFoul = false;
  1230.     if (cueBallPocketed) {
  1231.         foulCommitted = true;
  1232.         turnFoul = true;
  1233.     }
  1234.     // (Other foul checks like wrong ball first, no rail after contact, etc. could be added here)
  1235.  
  1236.  
  1237.     // --- State Transitions ---
  1238.  
  1239.     // 1. Break Shot Results (Assigning Colors)
  1240.     //    Condition: Colors not assigned AND at least one object ball pocketed AND no scratch
  1241.     if (player1Info.assignedType == BallType::NONE && anyNonCueBallPocketed && !cueBallPocketed)
  1242.     {
  1243.         // --- Added Safeguard ---
  1244.         // Ensure the recorded 'firstPocketedType' corresponds to an actual pocketed ball ID this turn.
  1245.         bool firstTypeVerified = false;
  1246.         for (int id : pocketedThisTurn) {
  1247.             if (id == firstPocketedId) {
  1248.                 firstTypeVerified = true;
  1249.                 break;
  1250.             }
  1251.         }
  1252.  
  1253.         // Only assign types if the first recorded pocketed ball type is valid and verified
  1254.         if (firstTypeVerified && (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE))
  1255.         {
  1256.             AssignPlayerBallTypes(firstPocketedType);
  1257.  
  1258.             // Update ball counts based on ALL balls pocketed this turn after assignment
  1259.             player1Info.ballsPocketedCount = 0;
  1260.             player2Info.ballsPocketedCount = 0;
  1261.             for (int id : pocketedThisTurn) {
  1262.                 Ball* b = GetBallById(id);
  1263.                 if (b && b->id != 0 && b->id != 8) { // Ignore cue and 8-ball for counts
  1264.                     if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  1265.                     else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  1266.                 }
  1267.             }
  1268.  
  1269.             // Determine if player continues turn: Did they pocket their *newly assigned* type?
  1270.             bool pocketedOwnAssignedType = false;
  1271.             for (int id : pocketedThisTurn) {
  1272.                 Ball* b = GetBallById(id);
  1273.                 if (b && b->id != 0 && b->id != 8 && b->type == currentPlayerInfo.assignedType) {
  1274.                     pocketedOwnAssignedType = true;
  1275.                     break;
  1276.                 }
  1277.             }
  1278.  
  1279.             if (pocketedOwnAssignedType) {
  1280.                 // Continue turn
  1281.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1282.                 // If AI's turn, ensure flag is set to trigger next move
  1283.                 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  1284.             }
  1285.             else {
  1286.                 // Switch turns if they didn't pocket their assigned type on the assigning shot
  1287.                 SwitchTurns();
  1288.             }
  1289.         }
  1290.         else {
  1291.             // If only 8-ball was pocketed on break (and no scratch), or something went wrong.
  1292.             // Re-spot 8-ball was handled in CheckGameOverConditions.
  1293.             // Treat as end of turn, switch players.
  1294.             SwitchTurns();
  1295.         }
  1296.  
  1297.     }
  1298.     // 2. Normal Play Results (Colors already assigned)
  1299.     else {
  1300.         // Update pocketed counts for assigned types
  1301.         // (Do this even if foul, as balls are off the table)
  1302.         int p1NewlyPocketed = 0;
  1303.         int p2NewlyPocketed = 0;
  1304.         for (int id : pocketedThisTurn) {
  1305.             Ball* b = GetBallById(id);
  1306.             if (!b || b->id == 0 || b->id == 8) continue;
  1307.             if (b->type == player1Info.assignedType) p1NewlyPocketed++;
  1308.             else if (b->type == player2Info.assignedType) p2NewlyPocketed++;
  1309.         }
  1310.         // Only update counts if not already game over state (prevents double counting on winning 8ball shot)
  1311.         if (currentGameState != GAME_OVER) {
  1312.             player1Info.ballsPocketedCount += p1NewlyPocketed;
  1313.             player2Info.ballsPocketedCount += p2NewlyPocketed;
  1314.         }
  1315.  
  1316.  
  1317.         // Decide next turn based on foul or legal pocket
  1318.         if (turnFoul) {
  1319.             // Pass turn, give opponent ball-in-hand
  1320.             SwitchTurns();
  1321.             RespawnCueBall(false); // Ball in hand for opponent
  1322.         }
  1323.         else if (legalBallPocketed) {
  1324.             // Player legally pocketed their own ball, continue turn
  1325.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1326.             // If AI's turn, make sure it knows to go again
  1327.             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  1328.         }
  1329.         else {
  1330.             // No legal ball pocketed or only opponent ball pocketed without foul.
  1331.             SwitchTurns();
  1332.         }
  1333.     }
  1334.  
  1335.     // --- Cleanup for next shot ---
  1336.     // Clear the list of balls pocketed *in this specific shot sequence*
  1337.     pocketedThisTurn.clear();
  1338. }
  1339.  
  1340. void AssignPlayerBallTypes(BallType firstPocketedType) {
  1341.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  1342.         if (currentPlayer == 1) {
  1343.             player1Info.assignedType = firstPocketedType;
  1344.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1345.         }
  1346.         else {
  1347.             player2Info.assignedType = firstPocketedType;
  1348.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  1349.         }
  1350.     }
  1351.     // If 8-ball was first (illegal on break generally), rules vary.
  1352.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  1353.     // Or assign based on what *else* was pocketed, if anything.
  1354.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  1355. }
  1356.  
  1357. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  1358.     if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
  1359.  
  1360.     PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
  1361.     bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
  1362.  
  1363.     // Loss Conditions:
  1364.     // 1. Pocket 8-ball AND scratch (pocket cue ball)
  1365.     // 2. Pocket 8-ball before clearing own color group
  1366.     if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
  1367.         gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
  1368.         currentGameState = GAME_OVER;
  1369.     }
  1370.     // Win Condition:
  1371.     // 1. Pocket 8-ball legally after clearing own color group
  1372.     else if (playerClearedBalls) {
  1373.         gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
  1374.         currentGameState = GAME_OVER;
  1375.     }
  1376.     // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
  1377.     // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
  1378.     else if (player1Info.assignedType == BallType::NONE) {
  1379.         Ball* eightBall = GetBallById(8);
  1380.         if (eightBall) {
  1381.             eightBall->isPocketed = false;
  1382.             // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
  1383.             eightBall->x = RACK_POS_X;
  1384.             eightBall->y = RACK_POS_Y;
  1385.             eightBall->vx = eightBall->vy = 0;
  1386.             // Check overlap and nudge if necessary (simplified)
  1387.         }
  1388.         // Apply foul rules if cue ball was also pocketed
  1389.         if (cueBallPocketed) {
  1390.             foulCommitted = true;
  1391.             // Don't switch turns on break scratch + 8ball pocket? Rules vary.
  1392.             // Let's make it a foul, switch turns, ball in hand.
  1393.             SwitchTurns();
  1394.             RespawnCueBall(false); // Ball in hand for opponent
  1395.         }
  1396.         else {
  1397.             // Just respawned 8ball, continue turn or switch based on other balls pocketed.
  1398.             // Let ProcessShotResults handle turn logic based on other pocketed balls.
  1399.         }
  1400.         // Prevent immediate game over message by returning here
  1401.         return;
  1402.     }
  1403.  
  1404.  
  1405. }
  1406.  
  1407.  
  1408. void SwitchTurns() {
  1409.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  1410.     // Reset aiming state for the new player
  1411.     isAiming = false;
  1412.     shotPower = 0;
  1413.     // Reset foul flag before new turn *really* starts (AI might take over)
  1414.     // Foul flag is mainly for display, gets cleared before human/AI shot
  1415.     // foulCommitted = false; // Probably better to clear before ApplyShot
  1416.  
  1417.     // Set the correct state based on who's turn it is
  1418.     if (currentPlayer == 1) {
  1419.         currentGameState = PLAYER1_TURN;
  1420.         aiTurnPending = false; // Ensure AI flag is off for P1
  1421.     }
  1422.     else { // Player 2's turn
  1423.         if (isPlayer2AI) {
  1424.             currentGameState = PLAYER2_TURN; // State indicates it's P2's turn
  1425.             aiTurnPending = true;           // Set flag for GameUpdate to trigger AI
  1426.             // AI will handle Ball-in-Hand logic if necessary within its decision making
  1427.         }
  1428.         else {
  1429.             currentGameState = PLAYER2_TURN; // Human P2
  1430.             aiTurnPending = false;
  1431.         }
  1432.     }
  1433. }
  1434.  
  1435. // --- Helper Functions ---
  1436.  
  1437. Ball* GetBallById(int id) {
  1438.     for (size_t i = 0; i < balls.size(); ++i) {
  1439.         if (balls[i].id == id) {
  1440.             return &balls[i];
  1441.         }
  1442.     }
  1443.     return nullptr;
  1444. }
  1445.  
  1446. Ball* GetCueBall() {
  1447.     return GetBallById(0);
  1448. }
  1449.  
  1450. float GetDistance(float x1, float y1, float x2, float y2) {
  1451.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  1452. }
  1453.  
  1454. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  1455.     float dx = x2 - x1;
  1456.     float dy = y2 - y1;
  1457.     return dx * dx + dy * dy;
  1458. }
  1459.  
  1460. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  1461.     // Basic bounds check (inside cushions)
  1462.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  1463.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  1464.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  1465.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  1466.  
  1467.     if (x < left || x > right || y < top || y > bottom) {
  1468.         return false;
  1469.     }
  1470.  
  1471.     // Check headstring restriction if needed
  1472.     if (checkHeadstring && x >= HEADSTRING_X) {
  1473.         return false;
  1474.     }
  1475.  
  1476.     // Check overlap with other balls
  1477.     for (size_t i = 0; i < balls.size(); ++i) {
  1478.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  1479.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  1480.                 return false; // Overlapping another ball
  1481.             }
  1482.         }
  1483.     }
  1484.  
  1485.     return true;
  1486. }
  1487.  
  1488.  
  1489. template <typename T>
  1490. void SafeRelease(T** ppT) {
  1491.     if (*ppT) {
  1492.         (*ppT)->Release();
  1493.         *ppT = nullptr;
  1494.     }
  1495. }
  1496.  
  1497. // --- NEW AI Implementation Functions ---
  1498.  
  1499. // Main entry point for AI turn
  1500. void AIMakeDecision() {
  1501.     Ball* cueBall = GetCueBall();
  1502.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return; // Safety checks
  1503.  
  1504.     // Handle Ball-in-Hand placement first if necessary
  1505.     if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BALL_IN_HAND_P2) {
  1506.         AIPlaceCueBall();
  1507.         // After placement, state should transition to PLAYER2_TURN or BREAKING
  1508.         currentGameState = (player1Info.assignedType == BallType::NONE) ? BREAKING : PLAYER2_TURN;
  1509.     }
  1510.  
  1511.     // Now find the best shot from the current position
  1512.     AIShotInfo bestShot = AIFindBestShot();
  1513.  
  1514.     if (bestShot.possible) {
  1515.         // Add slight delay maybe? For now, shoot immediately.
  1516.         // Apply calculated shot
  1517.         ApplyShot(bestShot.power, bestShot.angle, 0.0f, 0.0f); // AI doesn't use spin yet
  1518.  
  1519.         // Set state to shot in progress (ApplyShot might do this already)
  1520.         currentGameState = SHOT_IN_PROGRESS;
  1521.         foulCommitted = false; // Reset foul flag for AI shot
  1522.         pocketedThisTurn.clear(); // Clear previous pockets
  1523.     }
  1524.     else {
  1525.         // AI couldn't find any shot (highly unlikely with simple logic, but possible)
  1526.         // Safety shot? Push cue ball gently? Forfeit turn?
  1527.         // Simplest: Just tap the cue ball gently forward as a safety/pass.
  1528.         ApplyShot(MAX_SHOT_POWER * 0.1f, 0.0f, 0.0f, 0.0f); // Gentle tap forward
  1529.         currentGameState = SHOT_IN_PROGRESS;
  1530.         foulCommitted = false;
  1531.         pocketedThisTurn.clear();
  1532.         // NOTE: This might cause a foul if no ball is hit. Harder AI would handle this better.
  1533.     }
  1534.     aiTurnPending = false; // Ensure flag is off after decision
  1535. }
  1536.  
  1537. // AI logic for placing cue ball during ball-in-hand
  1538. void AIPlaceCueBall() {
  1539.     Ball* cueBall = GetCueBall();
  1540.     if (!cueBall) return;
  1541.  
  1542.     // Simple Strategy: Find the easiest possible shot for the AI's ball type
  1543.     // Place the cue ball directly behind that target ball, aiming straight at a pocket.
  1544.     // (More advanced: find spot offering multiple options or safety)
  1545.  
  1546.     AIShotInfo bestPlacementShot = { false };
  1547.     D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
  1548.  
  1549.     BallType targetType = player2Info.assignedType;
  1550.     bool canTargetAnyPlacement = false; // Local scope variable for placement logic
  1551.     if (targetType == BallType::NONE) {
  1552.         canTargetAnyPlacement = true;
  1553.     }
  1554.     bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1555.     if (target8Ball) targetType = BallType::EIGHT_BALL;
  1556.  
  1557.  
  1558.     for (auto& targetBall : balls) {
  1559.         if (targetBall.isPocketed || targetBall.id == 0) continue;
  1560.  
  1561.         // Determine if current ball is a valid target for placement consideration
  1562.         bool currentBallIsValidTarget = false;
  1563.         if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
  1564.         else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
  1565.         else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
  1566.  
  1567.         if (!currentBallIsValidTarget) continue; // Skip if not a valid target
  1568.  
  1569.         for (int p = 0; p < 6; ++p) {
  1570.             // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
  1571.             float targetToPocketX = pocketPositions[p].x - targetBall.x;
  1572.             float targetToPocketY = pocketPositions[p].y - targetBall.y;
  1573.             float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1574.             if (dist < 1.0f) continue; // Avoid division by zero
  1575.  
  1576.             float idealAngle = atan2f(targetToPocketY, targetToPocketX);
  1577.             // Place cue ball slightly behind target ball along this line
  1578.             float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
  1579.             D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
  1580.                 targetBall.x - cosf(idealAngle) * placeDist,
  1581.                 targetBall.y - sinf(idealAngle) * placeDist
  1582.             );
  1583.  
  1584.             // Check if this placement is valid (on table, behind headstring if break, not overlapping)
  1585.             bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);
  1586.             if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
  1587.                 // Is path from potentialPlacePos to targetBall clear?
  1588.                 // Use D2D1::Point2F() factory function here
  1589.                 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
  1590.                     // Is path from targetBall to pocket clear?
  1591.                     // Use D2D1::Point2F() factory function here
  1592.                     if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
  1593.                         // This seems like a good potential placement. Score it?
  1594.                         // Easy AI: Just take the first valid one found.
  1595.                         bestPlacePos = potentialPlacePos;
  1596.                         goto placement_found; // Use goto for simplicity in non-OOP structure
  1597.                     }
  1598.                 }
  1599.             }
  1600.         }
  1601.     }
  1602.  
  1603. placement_found:
  1604.     // Place the cue ball at the best found position (or default if none found)
  1605.     cueBall->x = bestPlacePos.x;
  1606.     cueBall->y = bestPlacePos.y;
  1607.     cueBall->vx = 0;
  1608.     cueBall->vy = 0;
  1609. }
  1610.  
  1611.  
  1612. // AI finds the best shot available on the table
  1613. AIShotInfo AIFindBestShot() {
  1614.     AIShotInfo bestShotOverall = { false };
  1615.     Ball* cueBall = GetCueBall();
  1616.     if (!cueBall) return bestShotOverall;
  1617.  
  1618.     // Determine target ball type for AI (Player 2)
  1619.     BallType targetType = player2Info.assignedType;
  1620.     bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
  1621.     if (targetType == BallType::NONE) {
  1622.         // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
  1623.         // Or, more simply, treat any ball as a potential target to make *a* pocket
  1624.         canTargetAny = true; // Simplification: allow targeting any non-8 ball.
  1625.         // A better rule is hit lowest numbered ball first on break follow-up.
  1626.     }
  1627.  
  1628.     // Check if AI needs to shoot the 8-ball
  1629.     bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1630.  
  1631.  
  1632.     // Iterate through all potential target balls
  1633.     for (auto& potentialTarget : balls) {
  1634.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
  1635.  
  1636.         // Check if this ball is a valid target
  1637.         bool isValidTarget = false;
  1638.         if (target8Ball) {
  1639.             isValidTarget = (potentialTarget.id == 8);
  1640.         }
  1641.         else if (canTargetAny) {
  1642.             isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
  1643.         }
  1644.         else { // Colors assigned, not yet shooting 8-ball
  1645.             isValidTarget = (potentialTarget.type == targetType);
  1646.         }
  1647.  
  1648.         if (!isValidTarget) continue; // Skip if not a valid target for this turn
  1649.  
  1650.         // Now, check all pockets for this target ball
  1651.         for (int p = 0; p < 6; ++p) {
  1652.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  1653.             currentShot.involves8Ball = (potentialTarget.id == 8);
  1654.  
  1655.             if (currentShot.possible) {
  1656.                 // Compare scores to find the best shot
  1657.                 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  1658.                     bestShotOverall = currentShot;
  1659.                 }
  1660.             }
  1661.         }
  1662.     } // End loop through potential target balls
  1663.  
  1664.     // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
  1665.     // need a safety strategy. Current simple AI just takes best found or taps cue ball.
  1666.  
  1667.     return bestShotOverall;
  1668. }
  1669.  
  1670.  
  1671. // Evaluate a potential shot at a specific target ball towards a specific pocket
  1672. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  1673.     AIShotInfo shotInfo;
  1674.     shotInfo.possible = false; // Assume not possible initially
  1675.     shotInfo.targetBall = targetBall;
  1676.     shotInfo.pocketIndex = pocketIndex;
  1677.  
  1678.     Ball* cueBall = GetCueBall();
  1679.     if (!cueBall || !targetBall) return shotInfo;
  1680.  
  1681.     // --- Define local state variables needed for legality checks ---
  1682.     BallType aiAssignedType = player2Info.assignedType;
  1683.     bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
  1684.     bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
  1685.     // ---
  1686.  
  1687.     // 1. Calculate Ghost Ball position
  1688.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  1689.  
  1690.     // 2. Calculate Angle from Cue Ball to Ghost Ball
  1691.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  1692.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  1693.     if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
  1694.     shotInfo.angle = atan2f(dy, dx);
  1695.  
  1696.     // Basic angle validity check (optional)
  1697.     if (!IsValidAIAimAngle(shotInfo.angle)) {
  1698.         // Maybe log this or handle edge cases
  1699.     }
  1700.  
  1701.     // 3. Check Path: Cue Ball -> Ghost Ball Position
  1702.     // Use D2D1::Point2F() factory function here
  1703.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  1704.         return shotInfo; // Path blocked
  1705.     }
  1706.  
  1707.     // 4. Check Path: Target Ball -> Pocket
  1708.     // Use D2D1::Point2F() factory function here
  1709.     if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
  1710.         return shotInfo; // Path blocked
  1711.     }
  1712.  
  1713.     // 5. Check First Ball Hit Legality
  1714.     float firstHitDistSq = -1.0f;
  1715.     // Use D2D1::Point2F() factory function here
  1716.     Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
  1717.  
  1718.     if (!firstHit) {
  1719.         return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
  1720.     }
  1721.  
  1722.     // Check if the first ball hit is the intended target ball
  1723.     if (firstHit->id != targetBall->id) {
  1724.         // Allow hitting slightly off target if it's very close to ghost ball pos
  1725.         float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
  1726.         // Allow a tolerance roughly half the ball radius squared
  1727.         if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
  1728.             // First hit is significantly different from the target point.
  1729.             // This shot path leads to hitting the wrong ball first.
  1730.             return shotInfo; // Foul or unintended shot
  1731.         }
  1732.         // If first hit is not target, but very close, allow it for now (might still be foul based on type).
  1733.     }
  1734.  
  1735.     // Check legality of the *first ball actually hit* based on game rules
  1736.     if (!canTargetAny) { // Colors are assigned (or should be)
  1737.         if (mustTarget8Ball) { // Must hit 8-ball first
  1738.             if (firstHit->id != 8) {
  1739.                 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
  1740.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1741.             }
  1742.         }
  1743.         else { // Must hit own ball type first
  1744.             if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
  1745.                 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
  1746.                 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
  1747.             }
  1748.             else if (firstHit->id == 8) {
  1749.                 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
  1750.                 // Keep shot possible for now
  1751.             }
  1752.         }
  1753.     }
  1754.     // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
  1755.  
  1756.  
  1757.     // 6. Calculate Score & Power (Difficulty affects this)
  1758.     shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
  1759.  
  1760.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  1761.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  1762.  
  1763.     // Simple Score: Shorter shots are better, straighter shots are slightly better.
  1764.     float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
  1765.  
  1766.     // Angle Score: Calculate cut angle
  1767.     // Vector Cue -> Ghost
  1768.     float v1x = shotInfo.ghostBallPos.x - cueBall->x;
  1769.     float v1y = shotInfo.ghostBallPos.y - cueBall->y;
  1770.     // Vector Target -> Pocket
  1771.     float v2x = pocketPositions[pocketIndex].x - targetBall->x;
  1772.     float v2y = pocketPositions[pocketIndex].y - targetBall->y;
  1773.     // Normalize vectors
  1774.     float mag1 = sqrtf(v1x * v1x + v1y * v1y);
  1775.     float mag2 = sqrtf(v2x * v2x + v2y * v2y);
  1776.     float angleScoreFactor = 0.5f; // Default if vectors are zero len
  1777.     if (mag1 > 0.1f && mag2 > 0.1f) {
  1778.         v1x /= mag1; v1y /= mag1;
  1779.         v2x /= mag2; v2y /= mag2;
  1780.         // Dot product gives cosine of angle between cue ball path and target ball path
  1781.         float dotProduct = v1x * v2x + v1y * v2y;
  1782.         // Straighter shot (dot product closer to 1) gets higher score
  1783.         angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
  1784.     }
  1785.     angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
  1786.  
  1787.     shotInfo.score = distanceScore * angleScoreFactor;
  1788.  
  1789.     // Bonus for pocketing 8-ball legally
  1790.     if (mustTarget8Ball && targetBall->id == 8) {
  1791.         shotInfo.score *= 10.0; // Strongly prefer the winning shot
  1792.     }
  1793.  
  1794.     // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
  1795.  
  1796.     // 7. Calculate Power
  1797.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  1798.  
  1799.     // 8. Add Inaccuracy based on Difficulty (same as before)
  1800.     float angleError = 0.0f;
  1801.     float powerErrorFactor = 1.0f;
  1802.  
  1803.     switch (aiDifficulty) {
  1804.     case EASY:
  1805.         angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
  1806.         powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
  1807.         shotInfo.power *= 0.8f;
  1808.         break;
  1809.     case MEDIUM:
  1810.         angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
  1811.         powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
  1812.         break;
  1813.     case HARD:
  1814.         angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
  1815.         powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
  1816.         break;
  1817.     }
  1818.     shotInfo.angle += angleError;
  1819.     shotInfo.power *= powerErrorFactor;
  1820.     shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
  1821.  
  1822.     return shotInfo;
  1823. }
  1824.  
  1825.  
  1826. // Calculates required power (simplified)
  1827. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  1828.     // Basic model: Power needed increases with total distance the balls need to travel.
  1829.     // Need enough power for cue ball to reach target AND target to reach pocket.
  1830.     float totalDist = cueToGhostDist + targetToPocketDist;
  1831.  
  1832.     // Map distance to power (needs tuning)
  1833.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  1834.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  1835.  
  1836.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  1837.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  1838.  
  1839.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  1840.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  1841. }
  1842.  
  1843. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  1844. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  1845.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  1846.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  1847.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  1848.  
  1849.     if (dist < 1.0f) { // Target is basically in the pocket
  1850.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  1851.         // For simplicity, return a point slightly behind center along the reverse line.
  1852.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  1853.     }
  1854.  
  1855.     // Normalize direction vector from target to pocket
  1856.     float nx = targetToPocketX / dist;
  1857.     float ny = targetToPocketY / dist;
  1858.  
  1859.     // Ghost ball position is diameter distance *behind* the target ball along this line
  1860.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  1861.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  1862.  
  1863.     return D2D1::Point2F(ghostX, ghostY);
  1864. }
  1865.  
  1866. // Checks if line segment is clear of obstructing balls
  1867. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  1868.     float dx = end.x - start.x;
  1869.     float dy = end.y - start.y;
  1870.     float segmentLenSq = dx * dx + dy * dy;
  1871.  
  1872.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  1873.  
  1874.     for (const auto& ball : balls) {
  1875.         if (ball.isPocketed) continue;
  1876.         if (ball.id == ignoredBallId1) continue;
  1877.         if (ball.id == ignoredBallId2) continue;
  1878.  
  1879.         // Check distance from ball center to the line segment
  1880.         float ballToStartX = ball.x - start.x;
  1881.         float ballToStartY = ball.y - start.y;
  1882.  
  1883.         // Project ball center onto the line defined by the segment
  1884.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  1885.  
  1886.         D2D1_POINT_2F closestPointOnLine;
  1887.         if (dot < 0) { // Closest point is start point
  1888.             closestPointOnLine = start;
  1889.         }
  1890.         else if (dot > 1) { // Closest point is end point
  1891.             closestPointOnLine = end;
  1892.         }
  1893.         else { // Closest point is along the segment
  1894.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  1895.         }
  1896.  
  1897.         // Check if the closest point is within collision distance (ball radius + path radius)
  1898.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  1899.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  1900.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  1901.             return false; // Path is blocked
  1902.         }
  1903.     }
  1904.     return true; // No obstructions found
  1905. }
  1906.  
  1907. // Finds the first ball hit along a path (simplified)
  1908. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  1909.     Ball* hitBall = nullptr;
  1910.     hitDistSq = -1.0f; // Initialize hit distance squared
  1911.     float minCollisionDistSq = -1.0f;
  1912.  
  1913.     float cosA = cosf(angle);
  1914.     float sinA = sinf(angle);
  1915.  
  1916.     for (auto& ball : balls) {
  1917.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  1918.  
  1919.         float dx = ball.x - start.x;
  1920.         float dy = ball.y - start.y;
  1921.  
  1922.         // Project vector from start->ball onto the aim direction vector
  1923.         float dot = dx * cosA + dy * sinA;
  1924.  
  1925.         if (dot > 0) { // Ball is generally in front
  1926.             // Find closest point on aim line to the ball's center
  1927.             float closestPointX = start.x + dot * cosA;
  1928.             float closestPointY = start.y + dot * sinA;
  1929.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  1930.  
  1931.             // Check if the aim line passes within the ball's radius
  1932.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  1933.                 // Calculate distance from start to the collision point on the ball's circumference
  1934.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  1935.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  1936.  
  1937.                 if (collisionDist > 0) { // Ensure collision is in front
  1938.                     float collisionDistSq = collisionDist * collisionDist;
  1939.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  1940.                         minCollisionDistSq = collisionDistSq;
  1941.                         hitBall = &ball; // Found a closer hit ball
  1942.                     }
  1943.                 }
  1944.             }
  1945.         }
  1946.     }
  1947.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  1948.     return hitBall;
  1949. }
  1950.  
  1951. // Basic check for reasonable AI aim angles (optional)
  1952. bool IsValidAIAimAngle(float angle) {
  1953.     // Placeholder - could check for NaN or infinity if calculations go wrong
  1954.     return isfinite(angle);
  1955. }
  1956.  
  1957. // --- Drawing Functions ---
  1958.  
  1959. void OnPaint() {
  1960.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  1961.  
  1962.     if (SUCCEEDED(hr)) {
  1963.         pRenderTarget->BeginDraw();
  1964.         DrawScene(pRenderTarget); // Pass render target
  1965.         hr = pRenderTarget->EndDraw();
  1966.  
  1967.         if (hr == D2DERR_RECREATE_TARGET) {
  1968.             DiscardDeviceResources();
  1969.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  1970.             // But the timer loop will trigger redraw anyway.
  1971.         }
  1972.     }
  1973.     // If CreateDeviceResources failed, EndDraw might not be called.
  1974.     // Consider handling this more robustly if needed.
  1975. }
  1976.  
  1977. void DrawScene(ID2D1RenderTarget* pRT) {
  1978.     if (!pRT) return;
  1979.  
  1980.     pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  1981.  
  1982.     DrawTable(pRT);
  1983.     DrawBalls(pRT);
  1984.     DrawAimingAids(pRT); // Includes cue stick if aiming
  1985.     DrawUI(pRT);
  1986.     DrawPowerMeter(pRT);
  1987.     DrawSpinIndicator(pRT);
  1988.     DrawPocketedBallsIndicator(pRT);
  1989.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  1990.  
  1991.      // Draw Game Over Message
  1992.     if (currentGameState == GAME_OVER && pTextFormat) {
  1993.         ID2D1SolidColorBrush* pBrush = nullptr;
  1994.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  1995.         if (pBrush) {
  1996.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  1997.             pRT->DrawText(
  1998.                 gameOverMessage.c_str(),
  1999.                 (UINT32)gameOverMessage.length(),
  2000.                 pTextFormat, // Use large format maybe?
  2001.                 &layoutRect,
  2002.                 pBrush
  2003.             );
  2004.             SafeRelease(&pBrush);
  2005.         }
  2006.     }
  2007.  
  2008. }
  2009.  
  2010. void DrawTable(ID2D1RenderTarget* pRT) {
  2011.     ID2D1SolidColorBrush* pBrush = nullptr;
  2012.  
  2013.     // Draw Table Bed (Green Felt)
  2014.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  2015.     if (!pBrush) return;
  2016.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  2017.     pRT->FillRectangle(&tableRect, pBrush);
  2018.     SafeRelease(&pBrush);
  2019.  
  2020.     // Draw Cushions (Red Border)
  2021.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  2022.     if (!pBrush) return;
  2023.     // Top Cushion (split by middle pocket)
  2024.     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);
  2025.     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);
  2026.     // Bottom Cushion (split by middle pocket)
  2027.     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);
  2028.     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);
  2029.     // Left Cushion
  2030.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2031.     // Right Cushion
  2032.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  2033.     SafeRelease(&pBrush);
  2034.  
  2035.  
  2036.     // Draw Pockets (Black Circles)
  2037.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  2038.     if (!pBrush) return;
  2039.     for (int i = 0; i < 6; ++i) {
  2040.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  2041.         pRT->FillEllipse(&ellipse, pBrush);
  2042.     }
  2043.     SafeRelease(&pBrush);
  2044.  
  2045.     // Draw Headstring Line (White)
  2046.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush);
  2047.     if (!pBrush) return;
  2048.     pRT->DrawLine(
  2049.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  2050.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  2051.         pBrush,
  2052.         1.0f // Line thickness
  2053.     );
  2054.     SafeRelease(&pBrush);
  2055. }
  2056.  
  2057.  
  2058. void DrawBalls(ID2D1RenderTarget* pRT) {
  2059.     ID2D1SolidColorBrush* pBrush = nullptr;
  2060.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  2061.  
  2062.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  2063.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  2064.  
  2065.     if (!pBrush || !pStripeBrush) {
  2066.         SafeRelease(&pBrush);
  2067.         SafeRelease(&pStripeBrush);
  2068.         return;
  2069.     }
  2070.  
  2071.  
  2072.     for (size_t i = 0; i < balls.size(); ++i) {
  2073.         const Ball& b = balls[i];
  2074.         if (!b.isPocketed) {
  2075.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  2076.  
  2077.             // Set main ball color
  2078.             pBrush->SetColor(b.color);
  2079.             pRT->FillEllipse(&ellipse, pBrush);
  2080.  
  2081.             // Draw Stripe if applicable
  2082.             if (b.type == BallType::STRIPE) {
  2083.                 // Draw a white band across the middle (simplified stripe)
  2084.                 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);
  2085.                 // Need to clip this rectangle to the ellipse bounds - complex!
  2086.                 // Alternative: Draw two colored arcs leaving a white band.
  2087.                 // Simplest: Draw a white circle inside, slightly smaller.
  2088.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  2089.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  2090.                 pBrush->SetColor(b.color); // Set back to stripe color
  2091.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  2092.  
  2093.                 // Let's try drawing a thick white line across
  2094.                 // This doesn't look great. Just drawing solid red for stripes for now.
  2095.             }
  2096.  
  2097.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  2098.             // if (b.id != 0 && pTextFormat) {
  2099.             //     std::wstring numStr = std::to_wstring(b.id);
  2100.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  2101.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  2102.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  2103.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  2104.             //     // Create a smaller text format...
  2105.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  2106.             //     SafeRelease(&pNumBrush);
  2107.             // }
  2108.         }
  2109.     }
  2110.  
  2111.     SafeRelease(&pBrush);
  2112.     SafeRelease(&pStripeBrush);
  2113. }
  2114.  
  2115.  
  2116. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  2117.     // Condition check at start (Unchanged)
  2118.     if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  2119.         currentGameState != BREAKING && currentGameState != AIMING)
  2120.     {
  2121.         return;
  2122.     }
  2123.  
  2124.     Ball* cueBall = GetCueBall();
  2125.     if (!cueBall || cueBall->isPocketed) return;
  2126.  
  2127.     ID2D1SolidColorBrush* pBrush = nullptr;
  2128.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2129.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  2130.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  2131.  
  2132.     if (!pRT) return;
  2133.  
  2134.     // Create Brushes and Styles (Error checking unchanged)
  2135.     HRESULT hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  2136.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  2137.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  2138.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  2139.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  2140.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  2141.     if (pFactory) {
  2142.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  2143.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  2144.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  2145.         if FAILED(hr) { pDashedStyle = nullptr; }
  2146.     }
  2147.  
  2148.  
  2149.     // --- Aiming Line & Cue Stick ---
  2150.     // --- MODIFIED: Stick Length and Thickness ---
  2151.     const float baseStickLength = 150.0f;
  2152.     const float baseStickThickness = 4.0f;
  2153.     float stickLength = baseStickLength * 1.4f; // Approximately 1.4x longer
  2154.     float stickThickness = baseStickThickness * 1.5f; // Approximately 1.5x thicker
  2155.  
  2156.     float stickAngle = cueAngle + PI;
  2157.  
  2158.     // Power Offset calculation (Unchanged)
  2159.     float powerOffset = 0.0f;
  2160.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2161.         powerOffset = shotPower * 5.0f;
  2162.     }
  2163.  
  2164.     // Stick geometry calculation (Unchanged logic, uses new length)
  2165.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  2166.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  2167.  
  2168.  
  2169.     // --- MODIFIED: Draw Cue Stick with new thickness ---
  2170.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness); // Use new thickness variable
  2171.  
  2172.  
  2173.     // --- Projection Lines --- (Unchanged logic)
  2174.     float projectionLength = TABLE_WIDTH + TABLE_HEIGHT;
  2175.     D2D1_POINT_2F aimEndPoint = D2D1::Point2F(cueBall->x + cosf(cueAngle) * projectionLength, cueBall->y + sinf(cueAngle) * projectionLength);
  2176.  
  2177.     // Find first hit ball (Unchanged logic)
  2178.     Ball* hitBall = nullptr;
  2179.     float minDistSq = -1.0f;
  2180.     D2D1_POINT_2F collisionPoint = D2D1::Point2F(0, 0); // Initialize
  2181.     for (size_t i = 0; i < balls.size(); ++i) {
  2182.         // ... (rest of hit ball finding logic is unchanged) ...
  2183.         Ball& b = balls[i];
  2184.         if (b.id == 0 || b.isPocketed) continue;
  2185.  
  2186.         float dx = b.x - cueBall->x;
  2187.         float dy = b.y - cueBall->y;
  2188.         float dot = dx * cosf(cueAngle) + dy * sinf(cueAngle);
  2189.  
  2190.         if (dot > 0) {
  2191.             float closestPointX = cueBall->x + dot * cosf(cueAngle);
  2192.             float closestPointY = cueBall->y + dot * sinf(cueAngle);
  2193.             float distSq = GetDistanceSq(b.x, b.y, closestPointX, closestPointY);
  2194.  
  2195.             if (distSq < BALL_RADIUS * BALL_RADIUS) {
  2196.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  2197.                 float collisionDist = dot - backDist;
  2198.  
  2199.                 if (collisionDist > 0 && (hitBall == nullptr || collisionDist * collisionDist < minDistSq)) {
  2200.                     minDistSq = collisionDist * collisionDist;
  2201.                     hitBall = &b;
  2202.                     collisionPoint = D2D1::Point2F(cueBall->x + collisionDist * cosf(cueAngle), cueBall->y + collisionDist * sinf(cueAngle));
  2203.                 }
  2204.             }
  2205.         }
  2206.     }
  2207.  
  2208.  
  2209.     // Draw Aiming Line & Target Circle (Unchanged logic)
  2210.     D2D1_POINT_2F lineEnd = hitBall ? collisionPoint : aimEndPoint;
  2211.     pRT->DrawLine(D2D1::Point2F(cueBall->x, cueBall->y), lineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2212.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(lineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  2213.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  2214.  
  2215.     // Draw Projections if ball hit (Unchanged logic)
  2216.     if (hitBall) {
  2217.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(collisionPoint, BALL_RADIUS, BALL_RADIUS);
  2218.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  2219.         float hitAngle = atan2f(hitBall->y - collisionPoint.y, hitBall->x - collisionPoint.x);
  2220.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  2221.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(hitBall->x + cosf(hitAngle) * 50.0f, hitBall->y + sinf(hitAngle) * 50.0f);
  2222.         pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  2223.     }
  2224.  
  2225.     // Release resources (Unchanged)
  2226.     SafeRelease(&pBrush);
  2227.     SafeRelease(&pGhostBrush);
  2228.     SafeRelease(&pCueBrush);
  2229.     SafeRelease(&pDashedStyle);
  2230. }
  2231.  
  2232.  
  2233. void DrawUI(ID2D1RenderTarget* pRT) {
  2234.     if (!pTextFormat || !pLargeTextFormat) return;
  2235.  
  2236.     ID2D1SolidColorBrush* pBrush = nullptr;
  2237.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  2238.     if (!pBrush) return;
  2239.  
  2240.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  2241.     float uiTop = TABLE_TOP - 80;
  2242.     float uiHeight = 60;
  2243.     float p1Left = TABLE_LEFT;
  2244.     float p1Width = 150;
  2245.     float p2Left = TABLE_RIGHT - p1Width;
  2246.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  2247.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  2248.  
  2249.     // Player 1 Info Text (Unchanged)
  2250.     std::wostringstream oss1;
  2251.     oss1 << player1Info.name.c_str() << L"\n";
  2252.     if (player1Info.assignedType != BallType::NONE) {
  2253.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2254.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  2255.     }
  2256.     else {
  2257.         oss1 << L"(Undecided)";
  2258.     }
  2259.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  2260.  
  2261.     // Player 2 Info Text (Unchanged)
  2262.     std::wostringstream oss2;
  2263.     oss2 << player2Info.name.c_str() << L"\n";
  2264.     if (player2Info.assignedType != BallType::NONE) {
  2265.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  2266.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  2267.     }
  2268.     else {
  2269.         oss2 << L"(Undecided)";
  2270.     }
  2271.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  2272.  
  2273.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  2274.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  2275.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  2276.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2277.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  2278.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  2279.         float arrowTipX, arrowBackX;
  2280.  
  2281.         if (currentPlayer == 1) {
  2282.             // Player 1: Arrow left of P1 box, pointing right
  2283.             arrowBackX = p1Rect.left - 15.0f; // Position left of the box
  2284.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  2285.             // Define points for right-pointing arrow
  2286.             D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  2287.             D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  2288.             D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  2289.  
  2290.             ID2D1PathGeometry* pPath = nullptr;
  2291.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  2292.                 ID2D1GeometrySink* pSink = nullptr;
  2293.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  2294.                     pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  2295.                     pSink->AddLine(pt2);
  2296.                     pSink->AddLine(pt3);
  2297.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  2298.                     pSink->Close();
  2299.                     SafeRelease(&pSink);
  2300.                     pRT->FillGeometry(pPath, pArrowBrush);
  2301.                 }
  2302.                 SafeRelease(&pPath);
  2303.             }
  2304.         }
  2305.         else { // Player 2
  2306.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  2307.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  2308.             arrowBackX = p2Rect.left - 15.0f; // Position left of the box
  2309.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  2310.             // Define points for right-pointing arrow
  2311.             D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  2312.             D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  2313.             D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  2314.  
  2315.             ID2D1PathGeometry* pPath = nullptr;
  2316.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  2317.                 ID2D1GeometrySink* pSink = nullptr;
  2318.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  2319.                     pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  2320.                     pSink->AddLine(pt2);
  2321.                     pSink->AddLine(pt3);
  2322.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  2323.                     pSink->Close();
  2324.                     SafeRelease(&pSink);
  2325.                     pRT->FillGeometry(pPath, pArrowBrush);
  2326.                 }
  2327.                 SafeRelease(&pPath);
  2328.             }
  2329.         }
  2330.         SafeRelease(&pArrowBrush);
  2331.     }
  2332.  
  2333.  
  2334.     // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  2335.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  2336.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  2337.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  2338.         if (pFoulBrush && pLargeTextFormat) {
  2339.             // Calculate Rect for bottom-middle area
  2340.             float foulWidth = 200.0f; // Adjust width as needed
  2341.             float foulHeight = 60.0f;
  2342.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  2343.             // Position below the pocketed balls bar
  2344.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  2345.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  2346.  
  2347.             // --- Set text alignment to center for foul text ---
  2348.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2349.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2350.  
  2351.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  2352.  
  2353.             // --- Restore default alignment for large text if needed elsewhere ---
  2354.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  2355.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2356.  
  2357.             SafeRelease(&pFoulBrush);
  2358.         }
  2359.     }
  2360.  
  2361.     // Show AI Thinking State (Unchanged from previous step)
  2362.     if (currentGameState == AI_THINKING && pTextFormat) {
  2363.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  2364.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  2365.         if (pThinkingBrush) {
  2366.             D2D1_RECT_F thinkingRect = p2Rect;
  2367.             thinkingRect.top += 20; // Offset within P2 box
  2368.             // Ensure default text alignment for this
  2369.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2370.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2371.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  2372.             SafeRelease(&pThinkingBrush);
  2373.         }
  2374.     }
  2375.  
  2376.     SafeRelease(&pBrush);
  2377. }
  2378.  
  2379. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  2380.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  2381.     ID2D1SolidColorBrush* pFillBrush = nullptr;
  2382.  
  2383.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  2384.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LimeGreen), &pFillBrush);
  2385.  
  2386.     if (!pBorderBrush || !pFillBrush) {
  2387.         SafeRelease(&pBorderBrush);
  2388.         SafeRelease(&pFillBrush);
  2389.         return;
  2390.     }
  2391.  
  2392.     // Draw Border
  2393.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 1.0f);
  2394.  
  2395.     // Calculate Fill Height
  2396.     float fillRatio = 0;
  2397.     if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  2398.         fillRatio = shotPower / MAX_SHOT_POWER;
  2399.     }
  2400.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  2401.     D2D1_RECT_F fillRect = D2D1::RectF(
  2402.         powerMeterRect.left, powerMeterRect.bottom - fillHeight,
  2403.         powerMeterRect.right, powerMeterRect.bottom
  2404.     );
  2405.  
  2406.     // Draw Fill
  2407.     pRT->FillRectangle(&fillRect, pFillBrush);
  2408.  
  2409.     SafeRelease(&pBorderBrush);
  2410.     SafeRelease(&pFillBrush);
  2411. }
  2412.  
  2413. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  2414.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  2415.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  2416.  
  2417.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  2418.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  2419.  
  2420.     if (!pWhiteBrush || !pRedBrush) {
  2421.         SafeRelease(&pWhiteBrush);
  2422.         SafeRelease(&pRedBrush);
  2423.         return;
  2424.     }
  2425.  
  2426.     // Draw White Ball Background
  2427.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  2428.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  2429.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  2430.  
  2431.  
  2432.     // Draw Red Dot for Spin Position
  2433.     float dotRadius = 4.0f;
  2434.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  2435.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  2436.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  2437.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  2438.  
  2439.     SafeRelease(&pWhiteBrush);
  2440.     SafeRelease(&pRedBrush);
  2441. }
  2442.  
  2443.  
  2444. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  2445.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  2446.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  2447.  
  2448.     // Ensure render target is valid before proceeding
  2449.     if (!pRT) return;
  2450.  
  2451.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  2452.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  2453.  
  2454.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  2455.     if (FAILED(hr)) {
  2456.         SafeRelease(&pBgBrush);
  2457.         SafeRelease(&pBallBrush);
  2458.         return; // Exit if brush creation fails
  2459.     }
  2460.  
  2461.     // Draw the background bar (rounded rect)
  2462.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  2463.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  2464.  
  2465.     // --- Draw small circles for pocketed balls inside the bar ---
  2466.  
  2467.     // Calculate dimensions based on the bar's height for better scaling
  2468.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  2469.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  2470.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  2471.     float padding = spacing * 0.75f; // Add padding from the edges
  2472.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  2473.  
  2474.     // Starting X positions with padding
  2475.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  2476.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  2477.  
  2478.     int p1DrawnCount = 0;
  2479.     int p2DrawnCount = 0;
  2480.     const int maxBallsToShow = 7; // Max balls per player in the bar
  2481.  
  2482.     for (const auto& b : balls) {
  2483.         if (b.isPocketed) {
  2484.             // Skip cue ball and 8-ball in this indicator
  2485.             if (b.id == 0 || b.id == 8) continue;
  2486.  
  2487.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  2488.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  2489.  
  2490.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  2491.                 pBallBrush->SetColor(b.color);
  2492.                 // Draw P1 balls from left to right
  2493.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2494.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2495.                 p1DrawnCount++;
  2496.             }
  2497.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  2498.                 pBallBrush->SetColor(b.color);
  2499.                 // Draw P2 balls from right to left
  2500.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  2501.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  2502.                 p2DrawnCount++;
  2503.             }
  2504.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  2505.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  2506.         }
  2507.     }
  2508.  
  2509.     SafeRelease(&pBgBrush);
  2510.     SafeRelease(&pBallBrush);
  2511. }
  2512.  
  2513. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  2514.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  2515.         return; // Only show when placing/dragging
  2516.     }
  2517.  
  2518.     Ball* cueBall = GetCueBall();
  2519.     if (!cueBall) return;
  2520.  
  2521.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  2522.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  2523.  
  2524.     if (pGhostBrush) {
  2525.         D2D1_POINT_2F drawPos;
  2526.         if (isDraggingCueBall) {
  2527.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2528.         }
  2529.         else {
  2530.             // If not dragging but in placement state, show at current ball pos
  2531.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  2532.         }
  2533.  
  2534.         // Check if the placement is valid before drawing differently?
  2535.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2536.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  2537.  
  2538.         if (!isValid) {
  2539.             // Maybe draw red outline if invalid placement?
  2540.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  2541.         }
  2542.  
  2543.  
  2544.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  2545.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  2546.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  2547.  
  2548.         SafeRelease(&pGhostBrush);
  2549.     }
  2550. }
  2551. ```
  2552.  
  2553. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  2554. ```resource.h
  2555. //{{NO_DEPENDENCIES}}
  2556. // Microsoft Visual C++ generated include file.
  2557. // Used by Yahoo-8Ball-Pool-Clone.rc
  2558. //
  2559. #define IDI_ICON1                       101
  2560. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  2561. #define IDD_NEWGAMEDLG 106
  2562. #define IDC_RADIO_2P   1003
  2563. #define IDC_RADIO_CPU  1005
  2564. #define IDC_GROUP_AI   1006
  2565. #define IDC_RADIO_EASY 1007
  2566. #define IDC_RADIO_MEDIUM 1008
  2567. #define IDC_RADIO_HARD 1009
  2568. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  2569.  
  2570. // Next default values for new objects
  2571. //
  2572. #ifdef APSTUDIO_INVOKED
  2573. #ifndef APSTUDIO_READONLY_SYMBOLS
  2574. #define _APS_NEXT_RESOURCE_VALUE        102
  2575. #define _APS_NEXT_COMMAND_VALUE         40001
  2576. #define _APS_NEXT_CONTROL_VALUE         1001
  2577. #define _APS_NEXT_SYMED_VALUE           101
  2578. #endif
  2579. #endif
  2580.  
  2581. ```
  2582.  
  2583. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  2584. ```Yahoo-8Ball-Pool-Clone.rc
  2585. // Microsoft Visual C++ generated resource script.
  2586. //
  2587. #include "resource.h"
  2588.  
  2589. #define APSTUDIO_READONLY_SYMBOLS
  2590. /////////////////////////////////////////////////////////////////////////////
  2591. //
  2592. // Generated from the TEXTINCLUDE 2 resource.
  2593. //
  2594. #include "winres.h"
  2595.  
  2596. /////////////////////////////////////////////////////////////////////////////
  2597. #undef APSTUDIO_READONLY_SYMBOLS
  2598.  
  2599. /////////////////////////////////////////////////////////////////////////////
  2600. // English (United States) resources
  2601.  
  2602. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  2603. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  2604. #pragma code_page(1252)
  2605.  
  2606. #ifdef APSTUDIO_INVOKED
  2607. /////////////////////////////////////////////////////////////////////////////
  2608. //
  2609. // TEXTINCLUDE
  2610. //
  2611.  
  2612. 1 TEXTINCLUDE
  2613. BEGIN
  2614.     "resource.h\0"
  2615. END
  2616.  
  2617. 2 TEXTINCLUDE
  2618. BEGIN
  2619.     "#include ""winres.h""\r\n"
  2620.     "\0"
  2621. END
  2622.  
  2623. 3 TEXTINCLUDE
  2624. BEGIN
  2625.     "\r\n"
  2626.     "\0"
  2627. END
  2628.  
  2629. #endif    // APSTUDIO_INVOKED
  2630.  
  2631.  
  2632. /////////////////////////////////////////////////////////////////////////////
  2633. //
  2634. // Icon
  2635. //
  2636.  
  2637. // Icon with lowest ID value placed first to ensure application icon
  2638. // remains consistent on all systems.
  2639. IDI_ICON1               ICON                    "D:\\Download\\cpp-projekt\\FuzenOp_SiloTest\\icons\\shell32_277.ico"
  2640.  
  2641. #endif    // English (United States) resources
  2642. /////////////////////////////////////////////////////////////////////////////
  2643.  
  2644.  
  2645.  
  2646. #ifndef APSTUDIO_INVOKED
  2647. /////////////////////////////////////////////////////////////////////////////
  2648. //
  2649. // Generated from the TEXTINCLUDE 3 resource.
  2650. //
  2651.  
  2652.  
  2653. /////////////////////////////////////////////////////////////////////////////
  2654. #endif    // not APSTUDIO_INVOKED
  2655.  
  2656. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  2657.  
  2658. /////////////////////////////////////////////////////////////////////////////
  2659. //
  2660. // Dialog
  2661. //
  2662.  
  2663. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 130 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs)
  2664. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  2665. CAPTION "New 8-Ball Game"
  2666. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  2667. BEGIN
  2668. // --- Game Mode Selection ---
  2669. // Group Box for Game Mode (Optional visually, but helps structure)
  2670. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  2671.  
  2672. // "2 Player" Radio Button (First in this group)
  2673. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  2674. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  2675.  
  2676. // "Human vs CPU" Radio Button
  2677. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  2678. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  2679.  
  2680.  
  2681. // --- AI Difficulty Selection (Inside its own Group Box) ---
  2682. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  2683.  
  2684. // "Easy" Radio Button (First in the AI group)
  2685. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  2686. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  2687.  
  2688. // "Medium" Radio Button
  2689. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  2690. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  2691.  
  2692. // "Hard" Radio Button
  2693. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  2694. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  2695.  
  2696.  
  2697. // --- Standard Buttons ---
  2698. DEFPUSHBUTTON   "Start", IDOK, 55, 105, 50, 14 // Default button (Enter key)
  2699. PUSHBUTTON      "Cancel", IDCANCEL, 115, 105, 50, 14
  2700. END
  2701. ```
Advertisement
Add Comment
Please, Sign In to add comment