alien_fx_fiend

2D StickPool C++ D2D (Added Hot Swappable 5 Table Colors Presets GUI !!)

Aug 4th, 2025
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 246.72 KB | Source Code | 0 0
  1. ==++ Here's the full source for (file 1/3 (No OOP-based)) "Pool-Game-CloneV18.cpp"::: ++==
  2. ```Pool-Game-CloneV18.cpp
  3.    #define WIN32_LEAN_AND_MEAN
  4.    #define NOMINMAX
  5.    #include <windows.h>
  6.    #include <d2d1.h>
  7.    #include <dwrite.h>
  8.    #include <fstream> // For file I/O
  9.    #include <iostream> // For some basic I/O, though not strictly necessary for just file ops
  10.    #include <vector>
  11.    #include <cmath>
  12.    #include <string>
  13.    #include <sstream> // Required for wostringstream
  14.    #include <algorithm> // Required for std::max, std::min
  15.    #include <ctime>    // Required for srand, time
  16.    #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  17.    #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  18.    #include <mmsystem.h> // For PlaySound
  19.    #include <tchar.h> //midi func
  20.    #include <thread>
  21.    #include <atomic>
  22.    #include "resource.h"
  23.  
  24.    #ifndef HAS_STD_CLAMP
  25.    template <typename T>
  26.    T clamp(const T& v, const T& lo, const T& hi)
  27.    {
  28.        return (v < lo) ? lo : (v > hi) ? hi : v;
  29.    }
  30.    namespace std { using ::clamp; }   // inject into std:: for seamless use
  31.    #define HAS_STD_CLAMP
  32.    #endif
  33.  
  34.    #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  35.    #pragma comment(lib, "d2d1.lib")
  36.    #pragma comment(lib, "dwrite.lib")
  37.    #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  38.  
  39.    // --- Constants ---
  40.    const float PI = 3.1415926535f;
  41.    const float BALL_RADIUS = 10.0f;
  42.    const float TABLE_LEFT = 100.0f;
  43.    const float TABLE_TOP = 100.0f;
  44.    const float TABLE_WIDTH = 700.0f;
  45.    const float TABLE_HEIGHT = 350.0f;
  46.    const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  47.    const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  48.    const float CUSHION_THICKNESS = 20.0f;
  49.    const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  50.    const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  51.    const float MAX_SHOT_POWER = 15.0f;
  52.    const float FRICTION = 0.985f; // Friction factor per frame
  53.    const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  54.    const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  55.    const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  56.    const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  57.    const UINT ID_TIMER = 1;
  58.    const int TARGET_FPS = 60; // Target frames per second for timer
  59.  
  60.    // --- Enums ---
  61.    // --- MODIFIED/NEW Enums ---
  62.    enum GameState {
  63.        SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  64.        PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  65.        BREAKING,           // Player is aiming/shooting the break shot
  66.        CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  67.        CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  68.        AIMING,             // Player is aiming
  69.        AI_THINKING,        // NEW: AI is calculating its move
  70.        SHOT_IN_PROGRESS,   // Balls are moving
  71.        ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  72.        PLAYER1_TURN,
  73.        PLAYER2_TURN,
  74.        BALL_IN_HAND_P1,
  75.        BALL_IN_HAND_P2,
  76.        GAME_OVER
  77.    };
  78.  
  79.    enum BallType {
  80.        NONE,
  81.        SOLID,  // Yellow (1-7)
  82.        STRIPE, // Red (9-15)
  83.        EIGHT_BALL, // Black (8)
  84.        CUE_BALL // White (0)
  85.    };
  86.  
  87.    // NEW Enums for Game Mode and AI Difficulty
  88.    enum GameMode {
  89.        HUMAN_VS_HUMAN,
  90.        HUMAN_VS_AI
  91.    };
  92.  
  93.    enum AIDifficulty {
  94.        EASY,
  95.        MEDIUM,
  96.        HARD
  97.    };
  98.  
  99.    enum OpeningBreakMode {
  100.        CPU_BREAK,
  101.        P1_BREAK,
  102.        FLIP_COIN_BREAK
  103.    };
  104.  
  105.    // NEW: Enum and arrays for table color options
  106.    enum TableColor {
  107.        INDIGO,
  108.        TAN,
  109.        TEAL,
  110.        GREEN,
  111.        RED        
  112.    };
  113.  
  114.    // --- Structs ---
  115.    struct Ball {
  116.        int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  117.        BallType type;
  118.        float x, y;
  119.        float vx, vy;
  120.        D2D1_COLOR_F color;
  121.        bool isPocketed;
  122.    };
  123.  
  124.    struct PlayerInfo {
  125.        BallType assignedType;
  126.        int ballsPocketedCount;
  127.        std::wstring name;
  128.    };
  129.  
  130.    // --- Global Variables ---
  131.  
  132.    // Direct2D & DirectWrite
  133.    ID2D1Factory* pFactory = nullptr;
  134.    //ID2D1Factory* g_pD2DFactory = nullptr;
  135.    ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  136.    IDWriteFactory* pDWriteFactory = nullptr;
  137.    IDWriteTextFormat* pTextFormat = nullptr;
  138.    IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  139.    IDWriteTextFormat* pBallNumFormat = nullptr;
  140.  
  141.    // Game State
  142.    HWND hwndMain = nullptr;
  143.    GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  144.    std::vector<Ball> balls;
  145.    int currentPlayer = 1; // 1 or 2
  146.    PlayerInfo player1Info = { BallType::NONE, 0, L"Vince Woods"/*"Player 1"*/ };
  147.    PlayerInfo player2Info = { BallType::NONE, 0, L"Virtus Pro"/*"CPU"*/ }; // Default P2 name
  148.    bool foulCommitted = false;
  149.    std::wstring gameOverMessage = L"";
  150.    bool firstBallPocketedAfterBreak = false;
  151.    std::vector<int> pocketedThisTurn;
  152.    // --- NEW: 8-Ball Pocket Call Globals ---
  153.    int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  154.    int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  155.    int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  156.    std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  157.         // --- NEW: Remember which pocket the 8?ball actually went into last shot
  158.    int lastEightBallPocketIndex = -1;
  159.    //int lastPocketedIndex = -1; // pocket index (0–5) of the last ball pocketed
  160.    int called = -1;
  161.    bool cueBallPocketed = false;
  162.  
  163.    // --- NEW: Foul Tracking Globals ---
  164.    int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  165.    bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  166.    bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  167.    // --- End New Foul Tracking Globals ---
  168.  
  169.    // NEW Game Mode/AI Globals
  170.    GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  171.    AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  172.    OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  173.    bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  174.    bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  175.    // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  176.    // NEW: Flag to indicate if the current shot is the opening break of the game
  177.    bool isOpeningBreakShot = false;
  178.  
  179.    // NEW: For AI shot planning and visualization
  180.    struct AIPlannedShot {
  181.        float angle;
  182.        float power;
  183.        float spinX;
  184.        float spinY;
  185.        bool isValid; // Is there a valid shot planned?
  186.    };
  187.    AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  188.     bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  189.     int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  190.     const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  191.  
  192.     // Input & Aiming
  193.     POINT ptMouse = { 0, 0 };
  194.     bool isAiming = false;
  195.     bool isDraggingCueBall = false;
  196.     // --- ENSURE THIS LINE EXISTS HERE ---
  197.     bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  198.     // --- End Ensure ---
  199.     bool isSettingEnglish = false;
  200.     D2D1_POINT_2F aimStartPoint = { 0, 0 };
  201.     float cueAngle = 0.0f;
  202.     float shotPower = 0.0f;
  203.     float cueSpinX = 0.0f; // Range -1 to 1
  204.     float cueSpinY = 0.0f; // Range -1 to 1
  205.     float pocketFlashTimer = 0.0f;
  206.     bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  207.     int draggingBallId = -1;
  208.     bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  209.     MCIDEVICEID midiDeviceID = 0; //midi func
  210.     std::atomic<bool> isMusicPlaying(false); //midi func
  211.     std::thread musicThread; //midi func
  212.     void StartMidi(HWND hwnd, const TCHAR* midiPath);
  213.     void StopMidi();
  214.  
  215.     // NEW: Global for selected table color and definitions
  216.     TableColor selectedTableColor = INDIGO; // Default color
  217.     const WCHAR * tableColorNames[] = { L"Indigo", L"Tan", L"Teal", L"Green", L"Red" };
  218.     const D2D1_COLOR_F tableColorValues[] = {
  219.     D2D1::ColorF(0.05f, 0.09f, 0.28f),       // Indigo
  220.     D2D1::ColorF(0.3529f, 0.3137f, 0.2196f), // Tan
  221.     D2D1::ColorF(0.0f, 0.4f, 0.4392f),       // Teal
  222.     D2D1::ColorF(0.1608f, 0.4000f, 0.1765f), // Green
  223.     D2D1::ColorF(0.3882f, 0.1059f, 0.10196f) // Red
  224.     };
  225.  
  226.     // UI Element Positions
  227.     D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  228.     D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  229.     D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  230.     float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  231.     D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  232.  
  233.     // Corrected Pocket Center Positions (aligned with table corners/edges)
  234.     const D2D1_POINT_2F pocketPositions[6] = {
  235.         {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  236.         {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  237.         {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  238.         {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  239.         {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  240.         {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  241.     };
  242.  
  243.     // Colors
  244.     //const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.5f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f) (uncomment this l8r if needbe)
  245.     // This is now a variable that can be changed, not a constant.
  246.     D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.05f, 0.09f, 0.28f); // Default to Indigo
  247.     //const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.1f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
  248.     /*
  249.     MPool: *Darker tan= (0.3529f, 0.3137f, 0.2196f) *Indigo= (0.05f, 0.09f, 0.28f) xPurple= (0.1922f, 0.2941f, 0.4118f); xTan= (0.5333f, 0.4706f, 0.3569f); (Red= (0.3882f, 0.1059f, 0.10196f); *Green(default)= (0.1608f, 0.4000f, 0.1765f); *Teal= (0.0f, 0.4f, 0.4392f) + Teal40%reduction= (0.0f, 0.3333f, 0.4235f);
  250.     Hex: Teal=#00abc2 Tan=#7c6d53 Teal2=#03adc2 xPurple=#314b69 ?Tan=#88785b Red=#631b1a
  251.     */
  252.     const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  253.     //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  254.     const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  255.     const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  256.     const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  257.     const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Goldenrod); // Solids = Yellow Goldenrod
  258.     const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::DarkOrchid);   // Stripes = Red DarkOrchid
  259.     const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  260.     const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  261.     const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  262.     //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  263.     const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  264.     const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  265.  
  266.     // --------------------------------------------------------------------
  267. //  Realistic colours for each id (0-15)
  268. //  0 = cue-ball (white) | 1-7 solids | 8 = eight-ball | 9-15 stripes
  269. // --------------------------------------------------------------------
  270.     static const D2D1_COLOR_F BALL_COLORS[16] =
  271.     {
  272.         D2D1::ColorF(D2D1::ColorF::White),          // 0  cue
  273.         D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 1  yellow
  274.         D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 2  blue
  275.         D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 3  red
  276.         D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 4  purple
  277.         D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 5  orange
  278.         D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 6  green
  279.         D2D1::ColorF(0.50f, 0.05f, 0.05f),          // 7  maroon / burgundy
  280.         D2D1::ColorF(D2D1::ColorF::Black),          // 8  black
  281.         D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 9  (yellow stripe)
  282.         D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 10 blue stripe
  283.         D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 11 red stripe
  284.         D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 12 purple stripe
  285.         D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 13 orange stripe
  286.         D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 14 green stripe
  287.         D2D1::ColorF(0.50f, 0.05f, 0.05f)           // 15 maroon stripe
  288.     };
  289.  
  290.     // Quick helper
  291.     inline D2D1_COLOR_F GetBallColor(int id)
  292.     {
  293.         return (id >= 0 && id < 16) ? BALL_COLORS[id]
  294.             : D2D1::ColorF(D2D1::ColorF::White);
  295.     }
  296.  
  297.     // --- Forward Declarations ---
  298.     HRESULT CreateDeviceResources();
  299.     void DiscardDeviceResources();
  300.     void OnPaint();
  301.     void OnResize(UINT width, UINT height);
  302.     void InitGame();
  303.     void GameUpdate();
  304.     void UpdatePhysics();
  305.     void CheckCollisions();
  306.     bool CheckPockets(); // Returns true if any ball was pocketed
  307.     void ProcessShotResults();
  308.     void ApplyShot(float power, float angle, float spinX, float spinY);
  309.     void RespawnCueBall(bool behindHeadstring);
  310.     bool AreBallsMoving();
  311.     void SwitchTurns();
  312.     //bool AssignPlayerBallTypes(BallType firstPocketedType);
  313.     bool AssignPlayerBallTypes(BallType firstPocketedType,
  314.         bool creditShooter = true);
  315.     void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  316.     Ball* GetBallById(int id);
  317.     Ball* GetCueBall();
  318.     //void PlayGameMusic(HWND hwnd); //midi func
  319.     void AIBreakShot();
  320.  
  321.     // Drawing Functions
  322.     void DrawScene(ID2D1RenderTarget* pRT);
  323.     void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  324.     void DrawBalls(ID2D1RenderTarget* pRT);
  325.     void DrawCueStick(ID2D1RenderTarget* pRT);
  326.     void DrawAimingAids(ID2D1RenderTarget* pRT);
  327.     void DrawUI(ID2D1RenderTarget* pRT);
  328.     void DrawPowerMeter(ID2D1RenderTarget* pRT);
  329.     void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  330.     void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  331.     void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  332.     // NEW
  333.     void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  334.  
  335.     // Helper Functions
  336.     float GetDistance(float x1, float y1, float x2, float y2);
  337.     float GetDistanceSq(float x1, float y1, float x2, float y2);
  338.     bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  339.     template <typename T> void SafeRelease(T** ppT);
  340.     // --- NEW HELPER FORWARD DECLARATIONS ---
  341.     bool IsPlayerOnEightBall(int player);
  342.     void CheckAndTransitionToPocketChoice(int playerID);
  343.     // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  344.     float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  345.     // --- End Forward Declaration ---
  346.     bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection); // Keep this if present
  347.  
  348.     // --- NEW Forward Declarations ---
  349.  
  350.     // AI Related
  351.     struct AIShotInfo; // Define below
  352.     void TriggerAIMove();
  353.     void AIMakeDecision();
  354.     void AIPlaceCueBall();
  355.     AIShotInfo AIFindBestShot();
  356.     AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  357.     bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  358.     Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  359.     float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  360.     D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  361.     bool IsValidAIAimAngle(float angle); // Basic check
  362.  
  363.     // Dialog Related
  364.     INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  365.     void ShowNewGameDialog(HINSTANCE hInstance);
  366.     void LoadSettings(); // For deserialization
  367.     void SaveSettings(); // For serialization
  368.     const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  369.     void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  370.  
  371.     // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  372.     LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  373.  
  374.     // --- NEW Struct for AI Shot Evaluation ---
  375.     struct AIShotInfo {
  376.         bool possible = false;          // Is this shot considered viable?
  377.         Ball* targetBall = nullptr;     // Which ball to hit
  378.         int pocketIndex = -1;           // Which pocket to aim for (0-5)
  379.         D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  380.         float angle = 0.0f;             // Calculated shot angle
  381.         float power = 0.0f;             // Calculated shot power
  382.         float score = -1.0f;            // Score for this shot (higher is better)
  383.         bool involves8Ball = false;     // Is the target the 8-ball?
  384.         float spinX = 0.0f;
  385.         float spinY = 0.0f;
  386.     };
  387.  
  388.     /*
  389.     table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  390.     rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  391.     gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  392.     winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  393.     headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  394.     bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  395.     */
  396.  
  397.     // --- NEW Settings Serialization Functions ---
  398.     void SaveSettings() {
  399.         std::ofstream outFile(SETTINGS_FILE_NAME);
  400.         if (outFile.is_open()) {
  401.             outFile << static_cast<int>(gameMode) << std::endl;
  402.             outFile << static_cast<int>(aiDifficulty) << std::endl;
  403.             outFile << static_cast<int>(openingBreakMode) << std::endl;
  404.             outFile << static_cast<int>(selectedTableColor) << std::endl;
  405.             outFile.close();
  406.         }
  407.         // else: Handle error, e.g., log or silently fail
  408.     }
  409.  
  410.     void LoadSettings() {
  411.         std::ifstream inFile(SETTINGS_FILE_NAME);
  412.         if (inFile.is_open()) {
  413.             int gm, aid, obm;
  414.             if (inFile >> gm) {
  415.                 gameMode = static_cast<GameMode>(gm);
  416.             }
  417.             if (inFile >> aid) {
  418.                 aiDifficulty = static_cast<AIDifficulty>(aid);
  419.             }
  420.             if (inFile >> obm) {
  421.                 openingBreakMode = static_cast<OpeningBreakMode>(obm);
  422.             }
  423.             int tc;
  424.             if (inFile >> tc) {
  425.                 selectedTableColor = static_cast<TableColor>(tc);
  426.             }
  427.             inFile.close();
  428.  
  429.             // Validate loaded settings (optional, but good practice)
  430.             if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  431.             if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  432.             if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  433.         }
  434.         // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  435.     }
  436.     // --- End Settings Serialization Functions ---
  437.  
  438.     // --- NEW Dialog Procedure ---
  439.     INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  440.         switch (message) {
  441.         case WM_INITDIALOG:
  442.         {
  443.             // --- ACTION 4: Center Dialog Box ---
  444.     // Optional: Force centering if default isn't working
  445.             RECT rcDlg, rcOwner, rcScreen;
  446.             HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  447.             if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  448.  
  449.             GetWindowRect(hwndOwner, &rcOwner);
  450.             GetWindowRect(hDlg, &rcDlg);
  451.             CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  452.  
  453.             // Offset the owner rect relative to the screen if it's not the desktop
  454.             if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  455.                 OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  456.                 OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  457.                 OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  458.             }
  459.  
  460.  
  461.             // Calculate centered position
  462.             int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  463.             int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  464.  
  465.             // Ensure it stays within screen bounds (optional safety)
  466.             x = std::max(static_cast<int>(rcScreen.left), x);
  467.             y = std::max(static_cast<int>(rcScreen.top), y);
  468.             if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  469.                 x = rcScreen.right - (rcDlg.right - rcDlg.left);
  470.             if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  471.                 y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  472.  
  473.  
  474.             // Set the dialog position
  475.             SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  476.  
  477.             // --- End Centering Code ---
  478.  
  479.             // Set initial state based on current global settings (or defaults)
  480.             CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  481.  
  482.             CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  483.                 (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  484.  
  485.             // Enable/Disable AI group based on initial mode
  486.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  487.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  488.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  489.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  490.             // Set initial state for Opening Break Mode
  491.             CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  492.                 (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  493.             // Enable/Disable Opening Break group based on initial mode
  494.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  495.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  496.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  497.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  498.             // --- NEW: Populate the Table Color ComboBox ---
  499.             HWND hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  500.             for (int i = 0; i < 5; ++i) {
  501.                 SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM)tableColorNames[i]);
  502.             }
  503.             // Set the initial selection based on the loaded/default setting
  504.             SendMessage(hCombo, CB_SETCURSEL, (WPARAM)selectedTableColor, 0);
  505.         }
  506.         return (INT_PTR)TRUE;
  507.  
  508.         case WM_COMMAND:
  509.         { // Add an opening brace to create a new scope for the entire case.
  510.             HWND hCombo;
  511.             int selectedIndex;
  512.             switch (LOWORD(wParam)) {
  513.             case IDC_RADIO_2P:
  514.             case IDC_RADIO_CPU:
  515.             {
  516.                 bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  517.                 // Enable/Disable AI group controls based on selection
  518.                 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  519.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  520.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  521.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  522.                 // Also enable/disable Opening Break Mode group
  523.                 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  524.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  525.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  526.                 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  527.             }
  528.             return (INT_PTR)TRUE;
  529.  
  530.             case IDOK:
  531.                 // Retrieve selected options and store in global variables
  532.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  533.                     gameMode = HUMAN_VS_AI;
  534.                     if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  535.                     else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  536.                     else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  537.  
  538.                     if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  539.                     else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  540.                     else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  541.                 }
  542.                 else {
  543.                     gameMode = HUMAN_VS_HUMAN;
  544.                     // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  545.                 }
  546.  
  547.                 // --- NEW: Retrieve selected table color ---
  548.                 hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  549.                 selectedIndex = (int)SendMessage(hCombo, CB_GETCURSEL, 0, 0);
  550.                 if (selectedIndex != CB_ERR) {
  551.                     selectedTableColor = static_cast<TableColor>(selectedIndex);
  552.                 }
  553.  
  554.                 SaveSettings(); // Save settings when OK is pressed
  555.                 EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  556.                 return (INT_PTR)TRUE;
  557.  
  558.             case IDCANCEL: // Handle Cancel or closing the dialog
  559.                 // Optionally, could reload settings here if you want cancel to revert to previously saved state
  560.                 EndDialog(hDlg, IDCANCEL);
  561.                 return (INT_PTR)TRUE;
  562.             }
  563.         } // Add a closing brace for the new scope.
  564.         break; // End WM_COMMAND
  565.         }
  566.         return (INT_PTR)FALSE; // Default processing
  567.     }
  568.  
  569.     // --- NEW Helper to Show Dialog ---
  570.     void ShowNewGameDialog(HINSTANCE hInstance) {
  571.         if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  572.             // User clicked Start, reset game with new settings
  573.             isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  574.             if (isPlayer2AI) {
  575.                 switch (aiDifficulty) {
  576.                 case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  577.                 case MEDIUM: player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  578.                 case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  579.                 }
  580.             }
  581.             else {
  582.                 player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  583.             }
  584.             // Update window title
  585.             std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  586.             if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  587.             else windowTitle += L" (Human vs " + player2Info.name + L")";
  588.             SetWindowText(hwndMain, windowTitle.c_str());
  589.  
  590.             // --- NEW: Apply the selected table color ---
  591.                 TABLE_COLOR = tableColorValues[selectedTableColor];
  592.  
  593.             InitGame(); // Re-initialize game logic & board
  594.             InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  595.         }
  596.         else {
  597.             // User cancelled dialog - maybe just resume game? Or exit?
  598.             // For simplicity, we do nothing, game continues as it was.
  599.             // To exit on cancel from F2, would need more complex state management.
  600.         }
  601.     }
  602.  
  603.     // --- NEW Reset Game Function ---
  604.     void ResetGame(HINSTANCE hInstance) {
  605.         // Call the helper function to show the dialog and re-init if OK clicked
  606.         ShowNewGameDialog(hInstance);
  607.     }
  608.  
  609.     // --- WinMain ---
  610.     int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  611.         if (FAILED(CoInitialize(NULL))) {
  612.             MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  613.             return -1;
  614.         }
  615.  
  616.         // --- NEW: Load settings at startup ---
  617.         LoadSettings();
  618.  
  619.         // --- NEW: Show configuration dialog FIRST ---
  620.         if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  621.             // User cancelled the dialog
  622.             CoUninitialize();
  623.             return 0; // Exit gracefully if dialog cancelled
  624.         }
  625.         // Global gameMode and aiDifficulty are now set by the DialogProc
  626.  
  627.         // --- Apply the selected table color to the global before anything else draws ---
  628.         TABLE_COLOR = tableColorValues[selectedTableColor];
  629.  
  630.         // Set AI flag based on game mode
  631.         isPlayer2AI = (gameMode == HUMAN_VS_AI);
  632.         if (isPlayer2AI) {
  633.             switch (aiDifficulty) {
  634.             case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  635.             case MEDIUM:player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  636.             case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  637.             }
  638.         }
  639.         else {
  640.             player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  641.         }
  642.         // --- End of Dialog Logic ---
  643.  
  644.  
  645.         WNDCLASS wc = { };
  646.         wc.lpfnWndProc = WndProc;
  647.         wc.hInstance = hInstance;
  648.         wc.lpszClassName = L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/;
  649.         wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  650.         wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  651.         wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  652.  
  653.         if (!RegisterClass(&wc)) {
  654.             MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  655.             CoUninitialize();
  656.             return -1;
  657.         }
  658.  
  659.         // --- ACTION 4: Calculate Centered Window Position ---
  660.         const int WINDOW_WIDTH = 1000; // Define desired width
  661.         const int WINDOW_HEIGHT = 700; // Define desired height
  662.         int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  663.         int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  664.         int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  665.         int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  666.  
  667.         // --- Change Window Title based on mode ---
  668.         std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  669.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  670.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  671.  
  672.         DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  673.  
  674.         hwndMain = CreateWindowEx(
  675.             0, L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/, windowTitle.c_str(), dwStyle,
  676.             windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  677.             NULL, NULL, hInstance, NULL
  678.         );
  679.  
  680.         if (!hwndMain) {
  681.             MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  682.             CoUninitialize();
  683.             return -1;
  684.         }
  685.  
  686.         // Initialize Direct2D Resources AFTER window creation
  687.         if (FAILED(CreateDeviceResources())) {
  688.             MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  689.             DestroyWindow(hwndMain);
  690.             CoUninitialize();
  691.             return -1;
  692.         }
  693.  
  694.         InitGame(); // Initialize game state AFTER resources are ready & mode is set
  695.         Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  696.         StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  697.         //PlayGameMusic(hwndMain); //midi func
  698.  
  699.         ShowWindow(hwndMain, nCmdShow);
  700.         UpdateWindow(hwndMain);
  701.  
  702.         if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  703.             MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  704.             DestroyWindow(hwndMain);
  705.             CoUninitialize();
  706.             return -1;
  707.         }
  708.  
  709.         MSG msg = { };
  710.         // --- Modified Main Loop ---
  711.         // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  712.         // or gets reset to it via F2. The main loop runs normally once game starts.
  713.         while (GetMessage(&msg, NULL, 0, 0)) {
  714.             // We might need modeless dialog handling here if F2 shows dialog
  715.             // while window is active, but DialogBoxParam is modal.
  716.             // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  717.             // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  718.             TranslateMessage(&msg);
  719.             DispatchMessage(&msg);
  720.         }
  721.  
  722.  
  723.         KillTimer(hwndMain, ID_TIMER);
  724.         DiscardDeviceResources();
  725.         SaveSettings(); // Save settings on exit
  726.         CoUninitialize();
  727.  
  728.         return (int)msg.wParam;
  729.     }
  730.  
  731.     // --- WndProc ---
  732.     LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  733.         // Declare cueBall pointer once at the top, used in multiple cases
  734.         // For clarity, often better to declare within each case where needed.
  735.         Ball* cueBall = nullptr; // Initialize to nullptr
  736.         switch (msg) {
  737.         case WM_CREATE:
  738.             // Resources are now created in WinMain after CreateWindowEx
  739.             return 0;
  740.  
  741.         case WM_PAINT:
  742.             OnPaint();
  743.             // Validate the entire window region after painting
  744.             ValidateRect(hwnd, NULL);
  745.             return 0;
  746.  
  747.         case WM_SIZE: {
  748.             UINT width = LOWORD(lParam);
  749.             UINT height = HIWORD(lParam);
  750.             OnResize(width, height);
  751.             return 0;
  752.         }
  753.  
  754.         case WM_TIMER:
  755.             if (wParam == ID_TIMER) {
  756.                 GameUpdate(); // Update game logic and physics
  757.                 InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  758.             }
  759.             return 0;
  760.  
  761.             // --- NEW: Handle F2 Key for Reset ---
  762.             // --- MODIFIED: Handle More Keys ---
  763.         case WM_KEYDOWN:
  764.         { // Add scope for variable declarations
  765.  
  766.             // --- FIX: Get Cue Ball pointer for this scope ---
  767.             cueBall = GetCueBall();
  768.             // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
  769.             // --- End Fix ---
  770.  
  771.             // Check which player can interact via keyboard (Humans only)
  772.             bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  773.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  774.  
  775.             // --- F1 / F2 Keys (Always available) ---
  776.             if (wParam == VK_F2) {
  777.                 HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  778.                 ResetGame(hInstance); // Call reset function
  779.                 return 0; // Indicate key was processed
  780.             }
  781.             else if (wParam == VK_F1) {
  782.                 MessageBox(hwnd,
  783.                     L"Direct2D-based StickPool game made in C++ from scratch (4827+ lines of code)\n" // Update line count if needed {2764+ lines}
  784.                     L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  785.                     L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  786.                     L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions. Midnight Pool 4. 'BLISS' Game Engine.\n"
  787.                     L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  788.                     L"About This Game", MB_OK | MB_ICONINFORMATION);
  789.                 return 0; // Indicate key was processed
  790.             }
  791.  
  792.             // Check for 'M' key (uppercase or lowercase)
  793.                 // Toggle music with "M"
  794.             if (wParam == 'M' || wParam == 'm') {
  795.                 //static bool isMusicPlaying = false;
  796.                 if (isMusicPlaying) {
  797.                     // Stop the music
  798.                     StopMidi();
  799.                     isMusicPlaying = false;
  800.                 }
  801.                 else {
  802.                     // Build the MIDI file path
  803.                     TCHAR midiPath[MAX_PATH];
  804.                     GetModuleFileName(NULL, midiPath, MAX_PATH);
  805.                     // Keep only the directory part
  806.                     TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  807.                     if (lastBackslash != NULL) {
  808.                         *(lastBackslash + 1) = '\0';
  809.                     }
  810.                     // Append the MIDI filename
  811.                     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
  812.  
  813.                     // Start playing MIDI
  814.                     StartMidi(hwndMain, midiPath);
  815.                     isMusicPlaying = true;
  816.                 }
  817.             }
  818.  
  819.  
  820.             // --- Player Interaction Keys (Only if allowed) ---
  821.             if (canPlayerControl) {
  822.                 // --- Get Shift Key State ---
  823.                 bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  824.                 float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
  825.                 float powerStep = 0.2f; // Power step (Adjust as needed)
  826.  
  827.                 switch (wParam) {
  828.                 case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
  829.                     if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  830.                         cueAngle -= angleStep;
  831.                         // Normalize angle (keep between 0 and 2*PI)
  832.                         if (cueAngle < 0) cueAngle += 2 * PI;
  833.                         // Ensure state shows aiming visuals if turn just started
  834.                         if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  835.                         isAiming = false; // Keyboard adjust doesn't use mouse aiming state
  836.                         isDraggingStick = false;
  837.                         keyboardAimingActive = true;
  838.                     }
  839.                     break;
  840.  
  841.                 case VK_RIGHT: // Rotate Cue Stick Clockwise
  842.                     if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  843.                         cueAngle += angleStep;
  844.                         // Normalize angle (keep between 0 and 2*PI)
  845.                         if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  846.                         // Ensure state shows aiming visuals if turn just started
  847.                         if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  848.                         isAiming = false;
  849.                         isDraggingStick = false;
  850.                         keyboardAimingActive = true;
  851.                     }
  852.                     break;
  853.  
  854.                 case VK_UP: // Decrease Shot Power
  855.                     if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  856.                         shotPower -= powerStep;
  857.                         if (shotPower < 0.0f) shotPower = 0.0f;
  858.                         // Ensure state shows aiming visuals if turn just started
  859.                         if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  860.                         isAiming = true; // Keyboard adjust doesn't use mouse aiming state
  861.                         isDraggingStick = false;
  862.                         keyboardAimingActive = true;
  863.                     }
  864.                     break;
  865.  
  866.                 case VK_DOWN: // Increase Shot Power
  867.                     if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  868.                         shotPower += powerStep;
  869.                         if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  870.                         // Ensure state shows aiming visuals if turn just started
  871.                         if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  872.                         isAiming = true;
  873.                         isDraggingStick = false;
  874.                         keyboardAimingActive = true;
  875.                     }
  876.                     break;
  877.  
  878.                 case VK_SPACE: // Trigger Shot
  879.                     if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  880.                         && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  881.                     {
  882.                         if (shotPower > 0.15f) { // Use same threshold as mouse
  883.                            // Reset foul flags BEFORE applying shot
  884.                             firstHitBallIdThisShot = -1;
  885.                             cueHitObjectBallThisShot = false;
  886.                             railHitAfterContact = false;
  887.  
  888.                             // Play sound & Apply Shot
  889.                             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  890.                             ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  891.  
  892.                             // Update State
  893.                             currentGameState = SHOT_IN_PROGRESS;
  894.                             foulCommitted = false;
  895.                             pocketedThisTurn.clear();
  896.                             shotPower = 0; // Reset power after shooting
  897.                             isAiming = false; isDraggingStick = false; // Reset aiming flags
  898.                             keyboardAimingActive = false;
  899.                         }
  900.                     }
  901.                     break;
  902.  
  903.                 case VK_ESCAPE: // Cancel Aim/Shot Setup
  904.                     if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  905.                     {
  906.                         shotPower = 0.0f;
  907.                         isAiming = false;
  908.                         isDraggingStick = false;
  909.                         keyboardAimingActive = false;
  910.                         // Revert to basic turn state if not breaking
  911.                         if (currentGameState != BREAKING) {
  912.                             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  913.                         }
  914.                         //if (currentPlayer == 1) calledPocketP1 = -1;
  915.                         //else                  calledPocketP2 = -1;
  916.                     }
  917.                     break;
  918.  
  919.                 case 'G': // Toggle Cheat Mode
  920.                     cheatModeEnabled = !cheatModeEnabled;
  921.                     if (cheatModeEnabled)
  922.                         MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
  923.                     else
  924.                         MessageBeep(MB_OK); // Play a different beep when disabling
  925.                     break;
  926.  
  927.                 default:
  928.                     // Allow default processing for other keys if needed
  929.                     // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
  930.                     break;
  931.                 } // End switch(wParam) for player controls
  932.                 return 0; // Indicate player control key was processed
  933.             } // End if(canPlayerControl)
  934.         } // End scope for WM_KEYDOWN case
  935.         // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
  936.         // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
  937.         return 0;
  938.  
  939.         case WM_MOUSEMOVE: {
  940.             ptMouse.x = LOWORD(lParam);
  941.             ptMouse.y = HIWORD(lParam);
  942.  
  943.             // --- NEW LOGIC: Handle Pocket Hover ---
  944.             if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  945.                 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  946.                 int oldHover = currentlyHoveredPocket;
  947.                 currentlyHoveredPocket = -1; // Reset
  948.                 for (int i = 0; i < 6; ++i) {
  949.                     if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  950.                         currentlyHoveredPocket = i;
  951.                         break;
  952.                     }
  953.                 }
  954.                 if (oldHover != currentlyHoveredPocket) {
  955.                     InvalidateRect(hwnd, NULL, FALSE);
  956.                 }
  957.                 // Do NOT return 0 here, allow normal mouse angle update to continue
  958.             }
  959.             // --- END NEW LOGIC ---
  960.  
  961.  
  962.             cueBall = GetCueBall(); // Declare and get cueBall pointer
  963.  
  964.             if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  965.                 Ball* ball = GetBallById(draggingBallId);
  966.                 if (ball) {
  967.                     ball->x = (float)ptMouse.x;
  968.                     ball->y = (float)ptMouse.y;
  969.                     ball->vx = ball->vy = 0.0f;
  970.                 }
  971.                 return 0;
  972.             }
  973.  
  974.             if (!cueBall) return 0;
  975.  
  976.             // Update Aiming Logic (Check player turn)
  977.             if (isDraggingCueBall &&
  978.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  979.                     (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  980.                     currentGameState == PRE_BREAK_PLACEMENT))
  981.             {
  982.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  983.                 // Tentative position update
  984.                 cueBall->x = (float)ptMouse.x;
  985.                 cueBall->y = (float)ptMouse.y;
  986.                 cueBall->vx = cueBall->vy = 0;
  987.             }
  988.             else if ((isAiming || isDraggingStick) &&
  989.                 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  990.                     (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  991.             {
  992.                 //NEW2 MOUSEBOUND CODE = START
  993.                     /*// Clamp mouse inside table bounds during aiming
  994.                     if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
  995.                 if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
  996.                 if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
  997.                 if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
  998.                 //NEW2 MOUSEBOUND CODE = END
  999.                 // Aiming drag updates angle and power
  1000.                 float dx = (float)ptMouse.x - cueBall->x;
  1001.                 float dy = (float)ptMouse.y - cueBall->y;
  1002.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1003.                 //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  1004.                 //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  1005.                 if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
  1006.                     float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  1007.                     shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  1008.                 }
  1009.             }
  1010.             else if (isSettingEnglish &&
  1011.                 ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  1012.                     (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  1013.             {
  1014.                 // Setting English
  1015.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1016.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1017.                 float dist = GetDistance(dx, dy, 0, 0);
  1018.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1019.                 cueSpinX = dx / spinIndicatorRadius;
  1020.                 cueSpinY = dy / spinIndicatorRadius;
  1021.             }
  1022.             else {
  1023.                 //DISABLE PERM AIMING = START
  1024.                 /*// Update visual angle even when not aiming/dragging (Check player turn)
  1025.                 bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
  1026.                     (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
  1027.                     currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
  1028.  
  1029.                 if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
  1030.                 {
  1031.                     // NEW MOUSEBOUND CODE = START
  1032.                         // Only update cue angle if mouse is inside the playable table area
  1033.                     if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
  1034.                         ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
  1035.                     {
  1036.                         // NEW MOUSEBOUND CODE = END
  1037.                         Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
  1038.                         if (cb) {
  1039.                             float dx = (float)ptMouse.x - cb->x;
  1040.                             float dy = (float)ptMouse.y - cb->y;
  1041.                             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1042.                         }
  1043.                     } //NEW MOUSEBOUND CODE LINE = DISABLE
  1044.                 }*/
  1045.                 //DISABLE PERM AIMING = END
  1046.             }
  1047.             return 0;
  1048.         } // End WM_MOUSEMOVE
  1049.  
  1050.         case WM_LBUTTONDOWN: {
  1051.             ptMouse.x = LOWORD(lParam);
  1052.             ptMouse.y = HIWORD(lParam);
  1053.  
  1054.             // --- FOOLPROOF FIX: This block implements the two-stage pocket selection ---
  1055.             if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1056.                 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1057.  
  1058.                 int clickedPocketIndex = -1;
  1059.                 // STAGE 1, STEP 1: Check if the click was on any of the 6 pockets
  1060.                 for (int i = 0; i < 6; ++i) {
  1061.                     if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1062.                         clickedPocketIndex = i;
  1063.                         break;
  1064.                     }
  1065.                 }
  1066.  
  1067.                 if (clickedPocketIndex != -1) {
  1068.                     // STAGE 1, STEP 2: Player clicked on a pocket. Update the choice.
  1069.                     // We DO NOT change the game state here. This allows re-selection.
  1070.                     if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1071.                     else calledPocketP2 = clickedPocketIndex;
  1072.                     InvalidateRect(hwnd, NULL, FALSE); // Redraw to show the arrow has moved.
  1073.                     return 0; // Consume the click and stay in CHOOSING_POCKET state.
  1074.                 }
  1075.  
  1076.                 // STAGE 2, STEP 1: Check if the player is clicking the cue ball to confirm.
  1077.                 Ball* cueBall = GetCueBall();
  1078.                 int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1079.                 if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1080.                     // STAGE 2, STEP 2: A pocket has been selected, and the player now clicks the cue ball.
  1081.                     // NOW we transition to the normal aiming state.
  1082.                     currentGameState = AIMING; // Go to a generic aiming state.
  1083.                     pocketCallMessage = L""; // Clear the "Choose a pocket..." message.
  1084.                     isAiming = true; // Prepare for aiming.
  1085.                     aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable.
  1086.                     return 0;
  1087.                 }
  1088.  
  1089.                 // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1090.                 return 0;
  1091.             }
  1092.  
  1093.             /*// --- FOOLPROOF FIX: This block handles re-selectable pocket choice ---
  1094.             if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1095.                 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1096.  
  1097.                 int clickedPocketIndex = -1;
  1098.                 // Check if the click was on any of the 6 pockets
  1099.                 for (int i = 0; i < 6; ++i) {
  1100.                     if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1101.                         clickedPocketIndex = i;
  1102.                         break;
  1103.                     }
  1104.                 }
  1105.  
  1106.                 if (clickedPocketIndex != -1) { // Player clicked on a pocket
  1107.                     // FIX: Update the called pocket, but DO NOT change the game state.
  1108.                     // This allows the player to click another pocket to change their mind.
  1109.                     if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1110.                     else calledPocketP2 = clickedPocketIndex;
  1111.                     InvalidateRect(hwnd, NULL, FALSE); // Redraw to show updated arrow
  1112.                     return 0; // Consume the click and stay in CHOOSING_POCKET state
  1113.                 }
  1114.  
  1115.                 // FIX: Add new logic to CONFIRM the choice by clicking the cue ball.
  1116.                 Ball* cueBall = GetCueBall();
  1117.                 int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1118.                 if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1119.                     // A pocket has been selected, and the player now clicks the cue ball.
  1120.                     // NOW we transition to the normal aiming state.
  1121.                     currentGameState = AIMING; // Go to aiming, not PLAYER1_TURN
  1122.                     pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  1123.                     isAiming = true; // Prepare for aiming
  1124.                     aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1125.                     return 0;
  1126.                 }
  1127.  
  1128.                 // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1129.                 return 0;
  1130.             }*/
  1131.  
  1132.             /*// --- handle pocket re-selection when choosing 8-ball pocket ---
  1133.             if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1)
  1134.                 || (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI))
  1135.             {
  1136.                 POINT pt = { LOWORD(lParam), HIWORD(lParam) };
  1137.                 for (int i = 0; i < 6; ++i) {
  1138.                     float dx = pt.x - pocketPositions[i].x;
  1139.                     float dy = pt.y - pocketPositions[i].y;
  1140.                     if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1141.                         // 1) Record the call
  1142.                         if (currentPlayer == 1) calledPocketP1 = i;
  1143.                         else                  calledPocketP2 = i;
  1144.                         // 2) Clear any prompt text
  1145.                         pocketCallMessage.clear();
  1146.                         // 3) Return to normal aiming state
  1147.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1148.                         // 4) Redraw (arrow stays because calledPocketP* >= 0)
  1149.                         InvalidateRect(hwnd, NULL, FALSE);
  1150.                         return 0; // consume click
  1151.                     }
  1152.                 }
  1153.                 return 0; // clicked outside ? stay in pocket?call until a valid pocket is chosen
  1154.             }*/
  1155.  
  1156.             // … rest of your click?to?aim logic …
  1157.  
  1158.             //replaced /w new code
  1159.             /*
  1160.             // --- FIX: Add this entire block at the top of WM_LBUTTONDOWN ---
  1161.     // This handles input specifically for the pocket selection state.
  1162.             if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  1163.                 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  1164.  
  1165.                 int clickedPocketIndex = -1;
  1166.                 // Check if the click was on any of the 6 pockets
  1167.                 for (int i = 0; i < 6; ++i) {
  1168.                     if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  1169.                         clickedPocketIndex = i;
  1170.                         break;
  1171.                     }
  1172.                 }
  1173.  
  1174.                 if (clickedPocketIndex != -1) {
  1175.                     // A pocket was clicked. Update the selection but STAY in the choosing state.
  1176.                     // This allows the player to click another pocket to change their mind.
  1177.                     if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  1178.                     else calledPocketP2 = clickedPocketIndex;
  1179.                     InvalidateRect(hwnd, NULL, FALSE); // Redraw to show the arrow has moved.
  1180.                     return 0; // Consume the click and wait for the next action.
  1181.                 }
  1182.  
  1183.                 // If the player clicks the CUE BALL, that confirms their pocket selection.
  1184.                 Ball* cueBall = GetCueBall();
  1185.                 int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1186.                 if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1187.                     // A pocket has been selected, and the player now clicks the cue ball.
  1188.                     // NOW we transition to the normal aiming state.
  1189.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1190.                     pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  1191.                     isAiming = true; // Prepare for aiming
  1192.                     aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable
  1193.                     return 0;
  1194.                 }
  1195.  
  1196.                 // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1197.                 return 0;
  1198.             }
  1199.             // --- END OF THE NEW BLOCK ---
  1200.             */
  1201.             //new code ends here
  1202.  
  1203.             if (cheatModeEnabled) {
  1204.                 // Allow dragging any ball freely
  1205.                 for (Ball& ball : balls) {
  1206.                     float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  1207.                     if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
  1208.                         isDraggingCueBall = true;
  1209.                         draggingBallId = ball.id;
  1210.                         if (ball.id == 0) {
  1211.                             // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
  1212.                             if (currentPlayer == 1)
  1213.                                 currentGameState = BALL_IN_HAND_P1;
  1214.                             else if (currentPlayer == 2 && !isPlayer2AI)
  1215.                                 currentGameState = BALL_IN_HAND_P2;
  1216.                         }
  1217.                         return 0;
  1218.                     }
  1219.                 }
  1220.             }
  1221.  
  1222.             Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer            
  1223.  
  1224.             // Check which player is allowed to interact via mouse click
  1225.             bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  1226.             // Define states where interaction is generally allowed
  1227.             bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  1228.                 currentGameState == AIMING || currentGameState == BREAKING ||
  1229.                 currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  1230.                 currentGameState == PRE_BREAK_PLACEMENT);
  1231.  
  1232.             // Check Spin Indicator first (Allow if player's turn/aim phase)
  1233.             if (canPlayerClickInteract && canInteractState) {
  1234.                 float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  1235.                 if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  1236.                     isSettingEnglish = true;
  1237.                     float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1238.                     float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1239.                     float dist = GetDistance(dx, dy, 0, 0);
  1240.                     if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1241.                     cueSpinX = dx / spinIndicatorRadius;
  1242.                     cueSpinY = dy / spinIndicatorRadius;
  1243.                     isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  1244.                     return 0;
  1245.                 }
  1246.             }
  1247.  
  1248.             if (!cueBall) return 0;
  1249.  
  1250.             // Check Ball-in-Hand placement/drag
  1251.             bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1252.             bool isPlayerAllowedToPlace = (isPlacingBall &&
  1253.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1254.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1255.                     (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
  1256.  
  1257.             if (isPlayerAllowedToPlace) {
  1258.                 float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1259.                 if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  1260.                     isDraggingCueBall = true;
  1261.                     isAiming = false; isDraggingStick = false;
  1262.                 }
  1263.                 else {
  1264.                     bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1265.                     if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  1266.                         cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  1267.                         cueBall->vx = 0; cueBall->vy = 0;
  1268.                         isDraggingCueBall = false;
  1269.                         // Transition state
  1270.                         if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1271.                         else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1272.                         else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1273.                         cueAngle = 0.0f;
  1274.                     }
  1275.                 }
  1276.                 return 0;
  1277.             }
  1278.  
  1279.             // Check for starting Aim (Cue Ball OR Stick)
  1280.             bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  1281.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  1282.  
  1283.             if (canAim) {
  1284.                 const float stickDrawLength = 150.0f * 1.4f;
  1285.                 float currentStickAngle = cueAngle + PI;
  1286.                 D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  1287.                 D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  1288.                 float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  1289.                 float stickClickThresholdSq = 36.0f;
  1290.                 float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1291.                 float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  1292.  
  1293.                 bool clickedStick = (distToStickSq < stickClickThresholdSq);
  1294.                 bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  1295.  
  1296.                 if (clickedStick || clickedCueArea) {
  1297.                     isDraggingStick = clickedStick && !clickedCueArea;
  1298.                     isAiming = clickedCueArea;
  1299.                     aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1300.                     shotPower = 0;
  1301.                     float dx = (float)ptMouse.x - cueBall->x;
  1302.                     float dy = (float)ptMouse.y - cueBall->y;
  1303.                     if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1304.                     if (currentGameState != BREAKING) currentGameState = AIMING;
  1305.                 }
  1306.             }
  1307.             return 0;
  1308.         } // End WM_LBUTTONDOWN
  1309.  
  1310.  
  1311.         case WM_LBUTTONUP: {
  1312.             // --- FOOLPROOF FIX for Cheat Mode Scoring ---
  1313.             if (cheatModeEnabled && draggingBallId != -1) {
  1314.                 Ball* b = GetBallById(draggingBallId);
  1315.                 if (b) {
  1316.                     for (int p = 0; p < 6; ++p) {
  1317.                         float dx = b->x - pocketPositions[p].x;
  1318.                         float dy = b->y - pocketPositions[p].y;
  1319.                         if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1320.                             // --- This is the new, "smarter" logic ---
  1321.                             b->isPocketed = true; // Pocket the ball visually.
  1322.  
  1323.                             // If the table is open, assign types based on this cheated ball.
  1324.                             if (player1Info.assignedType == BallType::NONE && b->id != 0 && b->id != 8) {
  1325.                                 AssignPlayerBallTypes(b->type, false);
  1326.                             }
  1327.  
  1328.                             // Now, correctly update the score for the right player.
  1329.                             if (b->id != 0 && b->id != 8) {
  1330.                                 if (b->type == player1Info.assignedType) {
  1331.                                     player1Info.ballsPocketedCount++;
  1332.                                 }
  1333.                                 else if (b->type == player2Info.assignedType) {
  1334.                                     player2Info.ballsPocketedCount++;
  1335.                                 }
  1336.                             }
  1337.                             break; // Stop checking pockets.
  1338.                         }
  1339.                     }
  1340.                 }
  1341.             }
  1342.  
  1343.             /*if (cheatModeEnabled && draggingBallId != -1) {
  1344.                 Ball* b = GetBallById(draggingBallId);
  1345.                 if (b) {
  1346.                     for (int p = 0; p < 6; ++p) {
  1347.                         float dx = b->x - pocketPositions[p].x;
  1348.                         float dy = b->y - pocketPositions[p].y;
  1349.                         if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1350.                             // --- Assign ball type on first cheat-pocket if table still open ---
  1351.                             if (player1Info.assignedType == BallType::NONE
  1352.                                 && player2Info.assignedType == BallType::NONE
  1353.                                 && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  1354.                             {
  1355.                                 // In cheat mode, let's just assign to the current player
  1356.                                 AssignPlayerBallTypes(b->type);
  1357.                             }
  1358.                             b->isPocketed = true;
  1359.                             pocketedThisTurn.push_back(b->id);
  1360.  
  1361.                             // --- FIX FOR CHEAT MODE SCORING ---
  1362.                             // Immediately increment the correct player's count based on ball type,
  1363.                             // not whose turn it is.
  1364.                             if (b->id != 0 && b->id != 8) {
  1365.                                 if (b->type == player1Info.assignedType) {
  1366.                                     player1Info.ballsPocketedCount++;
  1367.                                 }
  1368.                                 else if (b->type == player2Info.assignedType) {
  1369.                                     player2Info.ballsPocketedCount++;
  1370.                                 }
  1371.                             }
  1372.                             // --- END FIX ---
  1373.                             // --- NEW: If this was the 7th ball, trigger the arrow call UI ---
  1374.                             if (b->id != 8) {
  1375.                                 PlayerInfo& shooter = (currentPlayer == 1 ? player1Info : player2Info);
  1376.                                 if (shooter.ballsPocketedCount >= 7
  1377.                                     && calledPocketP1 < 0
  1378.                                     && calledPocketP2 < 0)
  1379.                                 {
  1380.                                     currentGameState = (currentPlayer == 1)
  1381.                                         ? CHOOSING_POCKET_P1
  1382.                                         : CHOOSING_POCKET_P2;
  1383.                                 }
  1384.                                 else {
  1385.                                     // For any other cheat?pocket, keep the turn so you can continue aiming
  1386.                                     currentGameState = (currentPlayer == 1)
  1387.                                         ? PLAYER1_TURN
  1388.                                         : PLAYER2_TURN;
  1389.                                 }
  1390.                             }
  1391.                             // --- NEW: If it was the 8-Ball, award instant victory ---
  1392.                             else {
  1393.                                 currentGameState = GAME_OVER;
  1394.                                 gameOverMessage = (currentPlayer == 1 ? player1Info.name : player2Info.name)
  1395.                                     + std::wstring(L" Wins!");
  1396.                             }
  1397.                             break;
  1398.                         }
  1399.                     }
  1400.                 }
  1401.             }*/
  1402.  
  1403.             ptMouse.x = LOWORD(lParam);
  1404.             ptMouse.y = HIWORD(lParam);
  1405.  
  1406.             Ball* cueBall = GetCueBall(); // Get cueBall pointer
  1407.  
  1408.             // Check for releasing aim drag (Stick OR Cue Ball)
  1409.             if ((isAiming || isDraggingStick) &&
  1410.                 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  1411.                     (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  1412.             {
  1413.                 bool wasAiming = isAiming;
  1414.                 bool wasDraggingStick = isDraggingStick;
  1415.                 isAiming = false; isDraggingStick = false;
  1416.  
  1417.                 if (shotPower > 0.15f) { // Check power threshold
  1418.                     if (currentGameState != AI_THINKING) {
  1419.                         firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
  1420.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1421.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  1422.                         currentGameState = SHOT_IN_PROGRESS;
  1423.                         foulCommitted = false; pocketedThisTurn.clear();
  1424.                     }
  1425.                 }
  1426.                 else if (currentGameState != AI_THINKING) { // Revert state if power too low
  1427.                     if (currentGameState == BREAKING) { /* Still breaking */ }
  1428.                     else {
  1429.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1430.                         if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  1431.                     }
  1432.                 }
  1433.                 shotPower = 0; // Reset power indicator regardless
  1434.             }
  1435.  
  1436.             // Handle releasing cue ball drag (placement)
  1437.             if (isDraggingCueBall) {
  1438.                 isDraggingCueBall = false;
  1439.                 // Check player allowed to place
  1440.                 bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1441.                 bool isPlayerAllowed = (isPlacingState &&
  1442.                     ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1443.                         (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1444.                         (currentGameState == PRE_BREAK_PLACEMENT)));
  1445.  
  1446.                 if (isPlayerAllowed && cueBall) {
  1447.                     bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1448.                     if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  1449.                         // Finalize position already set by mouse move
  1450.                         // Transition state
  1451.                         if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1452.                         else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1453.                         else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1454.                         cueAngle = 0.0f;
  1455.                         /* ----------------------------------------------------
  1456.                         If the player who now has the turn is already on the
  1457.                         8-ball, immediately switch to pocket-selection state.
  1458.                         ---------------------------------------------------- */
  1459.                         if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  1460.                         {
  1461.                             CheckAndTransitionToPocketChoice(currentPlayer);
  1462.                         }
  1463.                     }
  1464.                     else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
  1465.                 }
  1466.             }
  1467.  
  1468.             // Handle releasing english setting
  1469.             if (isSettingEnglish) {
  1470.                 isSettingEnglish = false;
  1471.             }
  1472.             return 0;
  1473.         } // End WM_LBUTTONUP
  1474.  
  1475.         case WM_DESTROY:
  1476.             isMusicPlaying = false;
  1477.             if (midiDeviceID != 0) {
  1478.                 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  1479.                 midiDeviceID = 0;
  1480.                 SaveSettings(); // Save settings on exit
  1481.             }
  1482.             PostQuitMessage(0);
  1483.             return 0;
  1484.  
  1485.         default:
  1486.             return DefWindowProc(hwnd, msg, wParam, lParam);
  1487.         }
  1488.         return 0;
  1489.     }
  1490.  
  1491.     // --- Direct2D Resource Management ---
  1492.  
  1493.     HRESULT CreateDeviceResources() {
  1494.         HRESULT hr = S_OK;
  1495.  
  1496.         // Create Direct2D Factory
  1497.         if (!pFactory) {
  1498.             hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  1499.             if (FAILED(hr)) return hr;
  1500.         }
  1501.  
  1502.         // Create DirectWrite Factory
  1503.         if (!pDWriteFactory) {
  1504.             hr = DWriteCreateFactory(
  1505.                 DWRITE_FACTORY_TYPE_SHARED,
  1506.                 __uuidof(IDWriteFactory),
  1507.                 reinterpret_cast<IUnknown**>(&pDWriteFactory)
  1508.             );
  1509.             if (FAILED(hr)) return hr;
  1510.         }
  1511.  
  1512.         // Create Text Formats
  1513.         if (!pTextFormat && pDWriteFactory) {
  1514.             hr = pDWriteFactory->CreateTextFormat(
  1515.                 L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1516.                 16.0f, L"en-us", &pTextFormat
  1517.             );
  1518.             if (FAILED(hr)) return hr;
  1519.             // Center align text
  1520.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1521.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1522.         }
  1523.         if (!pLargeTextFormat && pDWriteFactory) {
  1524.             hr = pDWriteFactory->CreateTextFormat(
  1525.                 L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1526.                 48.0f, L"en-us", &pLargeTextFormat
  1527.             );
  1528.             if (FAILED(hr)) return hr;
  1529.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  1530.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1531.         }
  1532.  
  1533.         if (!pBallNumFormat && pDWriteFactory)
  1534.         {
  1535.             hr = pDWriteFactory->CreateTextFormat(
  1536.                 L"Segoe UI", nullptr,
  1537.                 DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1538.                 10.0f,                       // << small size for ball decals
  1539.                 L"en-us",
  1540.                 &pBallNumFormat);
  1541.             if (SUCCEEDED(hr))
  1542.             {
  1543.                 pBallNumFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1544.                 pBallNumFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1545.             }
  1546.         }
  1547.  
  1548.  
  1549.         // Create Render Target (needs valid hwnd)
  1550.         if (!pRenderTarget && hwndMain) {
  1551.             RECT rc;
  1552.             GetClientRect(hwndMain, &rc);
  1553.             D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  1554.  
  1555.             hr = pFactory->CreateHwndRenderTarget(
  1556.                 D2D1::RenderTargetProperties(),
  1557.                 D2D1::HwndRenderTargetProperties(hwndMain, size),
  1558.                 &pRenderTarget
  1559.             );
  1560.             if (FAILED(hr)) {
  1561.                 // If failed, release factories if they were created in this call
  1562.                 SafeRelease(&pTextFormat);
  1563.                 SafeRelease(&pLargeTextFormat);
  1564.                 SafeRelease(&pDWriteFactory);
  1565.                 SafeRelease(&pFactory);
  1566.                 pRenderTarget = nullptr; // Ensure it's null on failure
  1567.                 return hr;
  1568.             }
  1569.         }
  1570.  
  1571.         return hr;
  1572.     }
  1573.  
  1574.     void DiscardDeviceResources() {
  1575.         SafeRelease(&pRenderTarget);
  1576.         SafeRelease(&pTextFormat);
  1577.         SafeRelease(&pLargeTextFormat);
  1578.         SafeRelease(&pBallNumFormat);            // NEW
  1579.         SafeRelease(&pDWriteFactory);
  1580.         // Keep pFactory until application exit? Or release here too? Let's release.
  1581.         SafeRelease(&pFactory);
  1582.     }
  1583.  
  1584.     void OnResize(UINT width, UINT height) {
  1585.         if (pRenderTarget) {
  1586.             D2D1_SIZE_U size = D2D1::SizeU(width, height);
  1587.             pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  1588.         }
  1589.     }
  1590.  
  1591.     // --- Game Initialization ---
  1592.     void InitGame() {
  1593.         srand((unsigned int)time(NULL)); // Seed random number generator
  1594.         isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  1595.         aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  1596.         aiIsDisplayingAim = false;
  1597.         aiAimDisplayFramesLeft = 0;
  1598.         // ... (rest of InitGame())
  1599.  
  1600.         // --- Ensure pocketed list is clear from the absolute start ---
  1601.         pocketedThisTurn.clear();
  1602.  
  1603.         balls.clear(); // Clear existing balls
  1604.  
  1605.         // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  1606.         player1Info.assignedType = BallType::NONE;
  1607.         player1Info.ballsPocketedCount = 0;
  1608.         // Player 1 Name usually remains "Player 1"
  1609.         player2Info.assignedType = BallType::NONE;
  1610.         player2Info.ballsPocketedCount = 0;
  1611.         // Player 2 Name is set based on gameMode in ShowNewGameDialog
  1612.             // --- Reset any 8?Ball call state on new game ---
  1613.         lastEightBallPocketIndex = -1;
  1614.         calledPocketP1 = -1;
  1615.         calledPocketP2 = -1;
  1616.         pocketCallMessage = L"";
  1617.         aiPlannedShotDetails.isValid = false; // THIS IS THE CRITICAL FIX: Reset the AI's plan.
  1618.  
  1619.         // Create Cue Ball (ID 0)
  1620.         // Initial position will be set during PRE_BREAK_PLACEMENT state
  1621.         balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  1622.  
  1623.         // --- Create Object Balls (Temporary List) ---
  1624.         std::vector<Ball> objectBalls;
  1625.         // Solids (1-7, Yellow)
  1626.         for (int i = 1; i <= 7; ++i) {
  1627.             //objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  1628.             objectBalls.push_back({ i, BallType::SOLID, 0,0,0,0,
  1629.                         GetBallColor(i), false });
  1630.         }
  1631.         // Stripes (9-15, Red)
  1632.         for (int i = 9; i <= 15; ++i) {
  1633.             //objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  1634.             objectBalls.push_back({ i, BallType::STRIPE, 0,0,0,0,
  1635.                         GetBallColor(i), false });
  1636.         }
  1637.         // 8-Ball (ID 8) - Add it to the list to be placed
  1638.         //objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  1639.         objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0,0,0,0,
  1640.               GetBallColor(8), false });
  1641.  
  1642.  
  1643.         // --- Racking Logic (Improved) ---
  1644.         float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  1645.         float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  1646.  
  1647.         // Define rack positions (0-14 indices corresponding to triangle spots)
  1648.         D2D1_POINT_2F rackPositions[15];
  1649.         int rackIndex = 0;
  1650.         for (int row = 0; row < 5; ++row) {
  1651.             for (int col = 0; col <= row; ++col) {
  1652.                 if (rackIndex >= 15) break;
  1653.                 float x = RACK_POS_X + row * spacingX;
  1654.                 float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  1655.                 rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  1656.             }
  1657.         }
  1658.  
  1659.         // Separate 8-ball
  1660.         Ball eightBall;
  1661.         std::vector<Ball> otherBalls; // Solids and Stripes
  1662.         bool eightBallFound = false;
  1663.         for (const auto& ball : objectBalls) {
  1664.             if (ball.id == 8) {
  1665.                 eightBall = ball;
  1666.                 eightBallFound = true;
  1667.             }
  1668.             else {
  1669.                 otherBalls.push_back(ball);
  1670.             }
  1671.         }
  1672.         // Ensure 8 ball was actually created (should always be true)
  1673.         if (!eightBallFound) {
  1674.             // Handle error - perhaps recreate it? For now, proceed.
  1675.             eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  1676.         }
  1677.  
  1678.  
  1679.         // Shuffle the other 14 balls
  1680.         // Use std::shuffle if available (C++11 and later) for better randomness
  1681.         // std::random_device rd;
  1682.         // std::mt19937 g(rd());
  1683.         // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  1684.         std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  1685.  
  1686.         // --- Place balls into the main 'balls' vector in rack order ---
  1687.         // Important: Add the cue ball (already created) first.
  1688.         // (Cue ball added at the start of the function now)
  1689.  
  1690.         // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  1691.         int eightBallRackIndex = 4;
  1692.         eightBall.x = rackPositions[eightBallRackIndex].x;
  1693.         eightBall.y = rackPositions[eightBallRackIndex].y;
  1694.         eightBall.vx = 0;
  1695.         eightBall.vy = 0;
  1696.         eightBall.isPocketed = false;
  1697.         balls.push_back(eightBall); // Add 8 ball to the main vector
  1698.  
  1699.         // 2. Place the shuffled Solids and Stripes in the remaining spots
  1700.         size_t otherBallIdx = 0;
  1701.         //int otherBallIdx = 0;
  1702.         for (int i = 0; i < 15; ++i) {
  1703.             if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  1704.  
  1705.             if (otherBallIdx < otherBalls.size()) {
  1706.                 Ball& ballToPlace = otherBalls[otherBallIdx++];
  1707.                 ballToPlace.x = rackPositions[i].x;
  1708.                 ballToPlace.y = rackPositions[i].y;
  1709.                 ballToPlace.vx = 0;
  1710.                 ballToPlace.vy = 0;
  1711.                 ballToPlace.isPocketed = false;
  1712.                 balls.push_back(ballToPlace); // Add to the main game vector
  1713.             }
  1714.         }
  1715.         // --- End Racking Logic ---
  1716.  
  1717.  
  1718.         // --- Determine Who Breaks and Initial State ---
  1719.         if (isPlayer2AI) {
  1720.             /*// AI Mode: Randomly decide who breaks
  1721.             if ((rand() % 2) == 0) {
  1722.                 // AI (Player 2) breaks
  1723.                 currentPlayer = 2;
  1724.                 currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  1725.                 aiTurnPending = true; // Trigger AI logic
  1726.             }
  1727.             else {
  1728.                 // Player 1 (Human) breaks
  1729.                 currentPlayer = 1;
  1730.                 currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  1731.                 aiTurnPending = false;*/
  1732.             switch (openingBreakMode) {
  1733.             case CPU_BREAK:
  1734.                 currentPlayer = 2; // AI breaks
  1735.                 currentGameState = PRE_BREAK_PLACEMENT;
  1736.                 aiTurnPending = true;
  1737.                 break;
  1738.             case P1_BREAK:
  1739.                 currentPlayer = 1; // Player 1 breaks
  1740.                 currentGameState = PRE_BREAK_PLACEMENT;
  1741.                 aiTurnPending = false;
  1742.                 break;
  1743.             case FLIP_COIN_BREAK:
  1744.                 if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  1745.                     currentPlayer = 2; // AI breaks
  1746.                     currentGameState = PRE_BREAK_PLACEMENT;
  1747.                     aiTurnPending = true;
  1748.                 }
  1749.                 else {
  1750.                     currentPlayer = 1; // Player 1 breaks
  1751.                     currentGameState = PRE_BREAK_PLACEMENT;
  1752.                     aiTurnPending = false;
  1753.                 }
  1754.                 break;
  1755.             default: // Fallback to CPU break
  1756.                 currentPlayer = 2;
  1757.                 currentGameState = PRE_BREAK_PLACEMENT;
  1758.                 aiTurnPending = true;
  1759.                 break;
  1760.             }
  1761.         }
  1762.         else {
  1763.             // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  1764.             currentPlayer = 1;
  1765.             currentGameState = PRE_BREAK_PLACEMENT;
  1766.             aiTurnPending = false; // No AI involved
  1767.         }
  1768.  
  1769.         // Reset other relevant game state variables
  1770.         foulCommitted = false;
  1771.         gameOverMessage = L"";
  1772.         firstBallPocketedAfterBreak = false;
  1773.         // pocketedThisTurn cleared at start
  1774.         // Reset shot parameters and input flags
  1775.         shotPower = 0.0f;
  1776.         cueSpinX = 0.0f;
  1777.         cueSpinY = 0.0f;
  1778.         isAiming = false;
  1779.         isDraggingCueBall = false;
  1780.         isSettingEnglish = false;
  1781.         cueAngle = 0.0f; // Reset aim angle
  1782.     }
  1783.  
  1784.  
  1785.     // --------------------------------------------------------------------------------
  1786.     // Full GameUpdate(): integrates AI call?pocket ? aim ? shoot (no omissions)
  1787.     // --------------------------------------------------------------------------------
  1788.     void GameUpdate() {
  1789.         // --- 1) Handle an in?flight shot ---
  1790.         if (currentGameState == SHOT_IN_PROGRESS) {
  1791.             UpdatePhysics();
  1792.             // ? clear old 8?ball pocket info before any new pocket checks
  1793.             //lastEightBallPocketIndex = -1;
  1794.             CheckCollisions();
  1795.             CheckPockets(); // FIX: This line was missing. It's essential to check for pocketed balls every frame.
  1796.  
  1797.             if (AreBallsMoving()) {
  1798.                 isAiming = false;
  1799.                 aiIsDisplayingAim = false;
  1800.             }
  1801.  
  1802.             if (!AreBallsMoving()) {
  1803.                 ProcessShotResults();
  1804.             }
  1805.             return;
  1806.         }
  1807.  
  1808.         // --- 2) CPU’s turn (table is static) ---
  1809.         if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  1810.             // ??? If we've just auto?entered AI_THINKING for the 8?ball call, actually make the decision ???
  1811.             if (currentGameState == AI_THINKING && aiTurnPending) {
  1812.                 aiTurnPending = false;        // consume the pending flag
  1813.                 AIMakeDecision();             // CPU calls its pocket or plans its shot
  1814.                 return;                       // done this tick
  1815.             }
  1816.  
  1817.             // ??? Automate the AI pocket?selection click ???
  1818.             if (currentGameState == CHOOSING_POCKET_P2) {
  1819.                 // AI immediately confirms its call and moves to thinking/shooting
  1820.                 currentGameState = AI_THINKING;
  1821.                 aiTurnPending = true;
  1822.                 return; // process on next tick
  1823.             }
  1824.             // 2A) If AI is displaying its aim line, count down then shoot
  1825.             if (aiIsDisplayingAim) {
  1826.                 aiAimDisplayFramesLeft--;
  1827.                 if (aiAimDisplayFramesLeft <= 0) {
  1828.                     aiIsDisplayingAim = false;
  1829.                     if (aiPlannedShotDetails.isValid) {
  1830.                         firstHitBallIdThisShot = -1;
  1831.                         cueHitObjectBallThisShot = false;
  1832.                         railHitAfterContact = false;
  1833.                         std::thread([](const TCHAR* soundName) {
  1834.                             PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  1835.                             }, TEXT("cue.wav")).detach();
  1836.  
  1837.                             ApplyShot(
  1838.                                 aiPlannedShotDetails.power,
  1839.                                 aiPlannedShotDetails.angle,
  1840.                                 aiPlannedShotDetails.spinX,
  1841.                                 aiPlannedShotDetails.spinY
  1842.                             );
  1843.                             aiPlannedShotDetails.isValid = false;
  1844.                     }
  1845.                     currentGameState = SHOT_IN_PROGRESS;
  1846.                     foulCommitted = false;
  1847.                     pocketedThisTurn.clear();
  1848.                 }
  1849.                 return;
  1850.             }
  1851.  
  1852.             // 2B) Immediately after calling pocket, transition into AI_THINKING
  1853.             if (currentGameState == CHOOSING_POCKET_P2 && aiTurnPending) {
  1854.                 // Start thinking/shooting right away—no human click required
  1855.                 currentGameState = AI_THINKING;
  1856.                 aiTurnPending = false;
  1857.                 AIMakeDecision();
  1858.                 return;
  1859.             }
  1860.  
  1861.             // 2C) If AI has pending actions (break, ball?in?hand, or normal turn)
  1862.             if (aiTurnPending) {
  1863.                 if (currentGameState == BALL_IN_HAND_P2) {
  1864.                     AIPlaceCueBall();
  1865.                     currentGameState = AI_THINKING;
  1866.                     aiTurnPending = false;
  1867.                     AIMakeDecision();
  1868.                 }
  1869.                 else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  1870.                     AIBreakShot();
  1871.                 }
  1872.                 else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  1873.                     currentGameState = AI_THINKING;
  1874.                     aiTurnPending = false;
  1875.                     AIMakeDecision();
  1876.                 }
  1877.                 return;
  1878.             }
  1879.         }
  1880.     }
  1881.  
  1882.  
  1883.     // --- Physics and Collision ---
  1884.     void UpdatePhysics() {
  1885.         for (size_t i = 0; i < balls.size(); ++i) {
  1886.             Ball& b = balls[i];
  1887.             if (!b.isPocketed) {
  1888.                 b.x += b.vx;
  1889.                 b.y += b.vy;
  1890.  
  1891.                 // Apply friction
  1892.                 b.vx *= FRICTION;
  1893.                 b.vy *= FRICTION;
  1894.  
  1895.                 // Stop balls if velocity is very low
  1896.                 if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  1897.                     b.vx = 0;
  1898.                     b.vy = 0;
  1899.                 }
  1900.  
  1901.                 /* -----------------------------------------------------------------
  1902.        Additional clamp to guarantee the ball never escapes the table.
  1903.        The existing wall–collision code can momentarily disable the
  1904.        reflection test while the ball is close to a pocket mouth;
  1905.        that rare case allowed it to ‘slide’ through the cushion and
  1906.        leave the board.  We therefore enforce a final boundary check
  1907.        after the normal physics step.
  1908.        ----------------------------------------------------------------- */
  1909.                 const float leftBound = TABLE_LEFT + BALL_RADIUS;
  1910.                 const float rightBound = TABLE_RIGHT - BALL_RADIUS;
  1911.                 const float topBound = TABLE_TOP + BALL_RADIUS;
  1912.                 const float bottomBound = TABLE_BOTTOM - BALL_RADIUS;
  1913.  
  1914.                 if (b.x < leftBound) { b.x = leftBound;   b.vx = fabsf(b.vx); }
  1915.                 if (b.x > rightBound) { b.x = rightBound;  b.vx = -fabsf(b.vx); }
  1916.                 if (b.y < topBound) { b.y = topBound;    b.vy = fabsf(b.vy); }
  1917.                 if (b.y > bottomBound) { b.y = bottomBound; b.vy = -fabsf(b.vy); }
  1918.             }
  1919.         }
  1920.     }
  1921.  
  1922.     void CheckCollisions() {
  1923.         float left = TABLE_LEFT;
  1924.         float right = TABLE_RIGHT;
  1925.         float top = TABLE_TOP;
  1926.         float bottom = TABLE_BOTTOM;
  1927.         const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
  1928.  
  1929.         // --- Reset Per-Frame Sound Flags ---
  1930.         bool playedWallSoundThisFrame = false;
  1931.         bool playedCollideSoundThisFrame = false;
  1932.         // ---
  1933.  
  1934.         for (size_t i = 0; i < balls.size(); ++i) {
  1935.             Ball& b1 = balls[i];
  1936.             if (b1.isPocketed) continue;
  1937.  
  1938.             bool nearPocket[6];
  1939.             for (int p = 0; p < 6; ++p) {
  1940.                 nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  1941.             }
  1942.             bool nearTopLeftPocket = nearPocket[0];
  1943.             bool nearTopMidPocket = nearPocket[1];
  1944.             bool nearTopRightPocket = nearPocket[2];
  1945.             bool nearBottomLeftPocket = nearPocket[3];
  1946.             bool nearBottomMidPocket = nearPocket[4];
  1947.             bool nearBottomRightPocket = nearPocket[5];
  1948.  
  1949.             bool collidedWallThisBall = false;
  1950.  
  1951.             // --- Ball-Wall Collisions ---
  1952.             // (Check logic unchanged, added sound calls and railHitAfterContact update)
  1953.             // Left Wall
  1954.             if (b1.x - BALL_RADIUS < left) {
  1955.                 if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1956.                     b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1957.                     if (!playedWallSoundThisFrame) {
  1958.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1959.                         playedWallSoundThisFrame = true;
  1960.                     }
  1961.                     if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1962.                 }
  1963.             }
  1964.             // Right Wall
  1965.             if (b1.x + BALL_RADIUS > right) {
  1966.                 if (!nearTopRightPocket && !nearBottomRightPocket) {
  1967.                     b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1968.                     if (!playedWallSoundThisFrame) {
  1969.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1970.                         playedWallSoundThisFrame = true;
  1971.                     }
  1972.                     if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1973.                 }
  1974.             }
  1975.             // Top Wall
  1976.             if (b1.y - BALL_RADIUS < top) {
  1977.                 if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1978.                     b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1979.                     if (!playedWallSoundThisFrame) {
  1980.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1981.                         playedWallSoundThisFrame = true;
  1982.                     }
  1983.                     if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1984.                 }
  1985.             }
  1986.             // Bottom Wall
  1987.             if (b1.y + BALL_RADIUS > bottom) {
  1988.                 if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1989.                     b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1990.                     if (!playedWallSoundThisFrame) {
  1991.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1992.                         playedWallSoundThisFrame = true;
  1993.                     }
  1994.                     if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1995.                 }
  1996.             }
  1997.  
  1998.             // Spin effect (Unchanged)
  1999.             if (collidedWallThisBall) {
  2000.                 if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  2001.                 if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  2002.                 cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  2003.             }
  2004.  
  2005.  
  2006.             // --- Ball-Ball Collisions ---
  2007.             for (size_t j = i + 1; j < balls.size(); ++j) {
  2008.                 Ball& b2 = balls[j];
  2009.                 if (b2.isPocketed) continue;
  2010.  
  2011.                 float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  2012.                 float distSq = dx * dx + dy * dy;
  2013.                 float minDist = BALL_RADIUS * 2.0f;
  2014.  
  2015.                 if (distSq > 1e-6 && distSq < minDist * minDist) {
  2016.                     float dist = sqrtf(distSq);
  2017.                     float overlap = minDist - dist;
  2018.                     float nx = dx / dist; float ny = dy / dist;
  2019.  
  2020.                     // Separation (Unchanged)
  2021.                     b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  2022.                     b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  2023.  
  2024.                     float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  2025.                     float velAlongNormal = rvx * nx + rvy * ny;
  2026.  
  2027.                     if (velAlongNormal > 0) { // Colliding
  2028.                         // --- Play Ball Collision Sound ---
  2029.                         if (!playedCollideSoundThisFrame) {
  2030.                             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  2031.                             playedCollideSoundThisFrame = true; // Set flag
  2032.                         }
  2033.                         // --- End Sound ---
  2034.  
  2035.                         // --- NEW: Track First Hit and Cue/Object Collision ---
  2036.                         if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
  2037.                             if (b1.id == 0) { // Cue ball hit b2 first
  2038.                                 firstHitBallIdThisShot = b2.id;
  2039.                                 cueHitObjectBallThisShot = true;
  2040.                             }
  2041.                             else if (b2.id == 0) { // Cue ball hit b1 first
  2042.                                 firstHitBallIdThisShot = b1.id;
  2043.                                 cueHitObjectBallThisShot = true;
  2044.                             }
  2045.                             // If neither is cue ball, doesn't count as first hit for foul purposes
  2046.                         }
  2047.                         else if (b1.id == 0 || b2.id == 0) {
  2048.                             // Track subsequent cue ball collisions with object balls
  2049.                             cueHitObjectBallThisShot = true;
  2050.                         }
  2051.                         // --- End First Hit Tracking ---
  2052.  
  2053.  
  2054.                         // Impulse (Unchanged)
  2055.                         float impulse = velAlongNormal;
  2056.                         b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  2057.                         b2.vx += impulse * nx; b2.vy += impulse * ny;
  2058.  
  2059.                         // Spin Transfer (Unchanged)
  2060.                         if (b1.id == 0 || b2.id == 0) {
  2061.                             float spinEffectFactor = 0.08f;
  2062.                             b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  2063.                             b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  2064.                             b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  2065.                             b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  2066.                             cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  2067.                         }
  2068.                     }
  2069.                 }
  2070.             } // End ball-ball loop
  2071.         } // End ball loop
  2072.     } // End CheckCollisions
  2073.  
  2074.  
  2075.     bool CheckPockets() {
  2076.         bool anyPocketed = false;
  2077.         // FIX: Declare a local flag to ensure the sound only plays ONCE per function call.
  2078.         bool ballPocketedThisCheck = false;
  2079.         // For each ball not already pocketed:
  2080.         for (auto& b : balls) {
  2081.             if (b.isPocketed)
  2082.                 continue;
  2083.  
  2084.             // Check against each pocket
  2085.             for (int p = 0; p < 6; ++p) {
  2086.                 float dx = b.x - pocketPositions[p].x;
  2087.                 float dy = b.y - pocketPositions[p].y;
  2088.                 if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  2089.                     // It's in the pocket—remove it from play
  2090.                     // If it's the 8?ball, remember which pocket it went into
  2091.                     if (b.id == 8) {
  2092.                         lastEightBallPocketIndex = p;   // <-- Must set here!
  2093.                     }
  2094.                     b.isPocketed = true;
  2095.                     b.vx = b.vy = 0.0f;           // kill any movement
  2096.                     pocketedThisTurn.push_back(b.id);
  2097.                     anyPocketed = true;
  2098.  
  2099.                     // --- FIX: Insert your sound logic here ---
  2100.                     // The 'if' guard prevents multiple sounds on a multi-ball break.
  2101.                     if (!ballPocketedThisCheck) {
  2102.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  2103.                         ballPocketedThisCheck = true;
  2104.                     }
  2105.                     // --- End Sound Fix ---
  2106.  
  2107.                     break;  // no need to check other pockets for this ball
  2108.                 }
  2109.             }
  2110.         }
  2111.         return anyPocketed;
  2112.     }
  2113.  
  2114.     bool AreBallsMoving() {
  2115.         for (size_t i = 0; i < balls.size(); ++i) {
  2116.             if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  2117.                 return true;
  2118.             }
  2119.         }
  2120.         return false;
  2121.     }
  2122.  
  2123.     void RespawnCueBall(bool behindHeadstring) {
  2124.         Ball* cueBall = GetCueBall();
  2125.         if (cueBall) {
  2126.             // Determine the initial target position
  2127.             float targetX, targetY;
  2128.             if (behindHeadstring) {
  2129.                 targetX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  2130.                 targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2131.             }
  2132.             else {
  2133.                 targetX = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  2134.                 targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  2135.             }
  2136.  
  2137.             // FOOLPROOF FIX: Check if the target spot is valid. If not, nudge it until it is.
  2138.             int attempts = 0;
  2139.             while (!IsValidCueBallPosition(targetX, targetY, behindHeadstring) && attempts < 100) {
  2140.                 // If the spot is occupied, try nudging the ball slightly.
  2141.                 targetX += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  2142.                 targetY += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  2143.                 // Clamp to stay within reasonable bounds
  2144.                 targetX = std::max(TABLE_LEFT + BALL_RADIUS, std::min(targetX, TABLE_RIGHT - BALL_RADIUS));
  2145.                 targetY = std::max(TABLE_TOP + BALL_RADIUS, std::min(targetY, TABLE_BOTTOM - BALL_RADIUS));
  2146.                 attempts++;
  2147.             }
  2148.  
  2149.             // Set the final, valid position.
  2150.             cueBall->x = targetX;
  2151.             cueBall->y = targetY;
  2152.             cueBall->vx = 0;
  2153.             cueBall->vy = 0;
  2154.             cueBall->isPocketed = false;
  2155.  
  2156.             // Set the correct game state for ball-in-hand.
  2157.             if (currentPlayer == 1) {
  2158.                 currentGameState = BALL_IN_HAND_P1;
  2159.                 aiTurnPending = false;
  2160.             }
  2161.             else {
  2162.                 currentGameState = BALL_IN_HAND_P2;
  2163.                 if (isPlayer2AI) {
  2164.                     aiTurnPending = true;
  2165.                 }
  2166.             }
  2167.         }
  2168.     }
  2169.  
  2170.  
  2171.     // --- Game Logic ---
  2172.  
  2173.     void ApplyShot(float power, float angle, float spinX, float spinY) {
  2174.         Ball* cueBall = GetCueBall();
  2175.         if (cueBall) {
  2176.  
  2177.             // --- Play Cue Strike Sound (Threaded) ---
  2178.             if (power > 0.1f) { // Only play if it's an audible shot
  2179.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2180.             }
  2181.             // --- End Sound ---
  2182.  
  2183.             cueBall->vx = cosf(angle) * power;
  2184.             cueBall->vy = sinf(angle) * power;
  2185.  
  2186.             // Apply English (Spin) - Simplified effect (Unchanged)
  2187.             cueBall->vx += sinf(angle) * spinY * 0.5f;
  2188.             cueBall->vy -= cosf(angle) * spinY * 0.5f;
  2189.             cueBall->vx -= cosf(angle) * spinX * 0.5f;
  2190.             cueBall->vy -= sinf(angle) * spinX * 0.5f;
  2191.  
  2192.             // Store spin (Unchanged)
  2193.             cueSpinX = spinX;
  2194.             cueSpinY = spinY;
  2195.  
  2196.             // --- Reset Foul Tracking flags for the new shot ---
  2197.             // (Also reset in LBUTTONUP, but good to ensure here too)
  2198.             firstHitBallIdThisShot = -1;      // No ball hit yet
  2199.             cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  2200.             railHitAfterContact = false;     // No rail hit after contact yet
  2201.             // --- End Reset ---
  2202.  
  2203.                     // If this was the opening break shot, clear the flag
  2204.             if (isOpeningBreakShot) {
  2205.                 isOpeningBreakShot = false; // Mark opening break as taken
  2206.             }
  2207.         }
  2208.     }
  2209.  
  2210.  
  2211.     // ---------------------------------------------------------------------
  2212.     //  ProcessShotResults()
  2213.     // ---------------------------------------------------------------------
  2214.     void ProcessShotResults() {
  2215.         bool cueBallPocketed = false;
  2216.         bool eightBallPocketed = false;
  2217.         bool playerContinuesTurn = false;
  2218.  
  2219.         // --- Step 1: Update Ball Counts FIRST (THE CRITICAL FIX) ---
  2220.         // We must update the score before any other game logic runs.
  2221.         PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  2222.         int ownBallsPocketedThisTurn = 0;
  2223.  
  2224.         for (int id : pocketedThisTurn) {
  2225.             Ball* b = GetBallById(id);
  2226.             if (!b) continue;
  2227.  
  2228.             if (b->id == 0) {
  2229.                 cueBallPocketed = true;
  2230.             }
  2231.             else if (b->id == 8) {
  2232.                 eightBallPocketed = true;
  2233.             }
  2234.             else {
  2235.                 // This is a numbered ball. Update the pocketed count for the correct player.
  2236.                 if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) {
  2237.                     player1Info.ballsPocketedCount++;
  2238.                 }
  2239.                 else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) {
  2240.                     player2Info.ballsPocketedCount++;
  2241.                 }
  2242.  
  2243.                 if (b->type == shootingPlayer.assignedType) {
  2244.                     ownBallsPocketedThisTurn++;
  2245.                 }
  2246.             }
  2247.         }
  2248.  
  2249.         if (ownBallsPocketedThisTurn > 0) {
  2250.             playerContinuesTurn = true;
  2251.         }
  2252.  
  2253.         // --- Step 2: Handle Game-Ending 8-Ball Shot ---
  2254.         // Now that the score is updated, this check will have the correct information.
  2255.         if (eightBallPocketed) {
  2256.             CheckGameOverConditions(true, cueBallPocketed);
  2257.             if (currentGameState == GAME_OVER) {
  2258.                 pocketedThisTurn.clear();
  2259.                 return;
  2260.             }
  2261.         }
  2262.  
  2263.         // --- Step 3: Check for Fouls ---
  2264.         bool turnFoul = false;
  2265.         if (cueBallPocketed) {
  2266.             turnFoul = true;
  2267.         }
  2268.         else {
  2269.             Ball* firstHit = GetBallById(firstHitBallIdThisShot);
  2270.             if (!firstHit) { // Rule: Hitting nothing is a foul.
  2271.                 turnFoul = true;
  2272.             }
  2273.             else { // Rule: Hitting the wrong ball type is a foul.
  2274.                 if (player1Info.assignedType != BallType::NONE) { // Colors are assigned.
  2275.                     // We check if the player WAS on the 8-ball BEFORE this shot.
  2276.                     bool wasOnEightBall = (shootingPlayer.assignedType != BallType::NONE && (shootingPlayer.ballsPocketedCount - ownBallsPocketedThisTurn) >= 7);
  2277.                     if (wasOnEightBall) {
  2278.                         if (firstHit->id != 8) turnFoul = true;
  2279.                     }
  2280.                     else {
  2281.                         if (firstHit->type != shootingPlayer.assignedType) turnFoul = true;
  2282.                     }
  2283.                 }
  2284.             }
  2285.         } //reenable below disabled for debugging
  2286.         //if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
  2287.             //turnFoul = true;
  2288.         //}
  2289.         foulCommitted = turnFoul;
  2290.  
  2291.         // --- Step 4: Final State Transition ---
  2292.         if (foulCommitted) {
  2293.             SwitchTurns();
  2294.             RespawnCueBall(false);
  2295.         }
  2296.         else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed) {
  2297.             // Assign types on the break.
  2298.             for (int id : pocketedThisTurn) {
  2299.                 Ball* b = GetBallById(id);
  2300.                 if (b && b->type != BallType::EIGHT_BALL) {
  2301.                     AssignPlayerBallTypes(b->type);
  2302.                     break;
  2303.                 }
  2304.             }
  2305.             CheckAndTransitionToPocketChoice(currentPlayer);
  2306.         }
  2307.         else if (playerContinuesTurn) {
  2308.             // The player's turn continues. Now the check will work correctly.
  2309.             CheckAndTransitionToPocketChoice(currentPlayer);
  2310.         }
  2311.         else {
  2312.             SwitchTurns();
  2313.         }
  2314.  
  2315.         pocketedThisTurn.clear();
  2316.     }
  2317.  
  2318.     /*
  2319.     // --- Step 3: Final State Transition ---
  2320.     if (foulCommitted) {
  2321.         SwitchTurns();
  2322.         RespawnCueBall(false);
  2323.     }
  2324.     else if (playerContinuesTurn) {
  2325.         CheckAndTransitionToPocketChoice(currentPlayer);
  2326.     }
  2327.     else {
  2328.         SwitchTurns();
  2329.     }
  2330.  
  2331.     pocketedThisTurn.clear();
  2332.     } */
  2333.  
  2334.     //  Assign groups AND optionally give the shooter his first count.
  2335.     bool AssignPlayerBallTypes(BallType firstPocketedType, bool creditShooter /*= true*/)
  2336.     {
  2337.         if (firstPocketedType != SOLID && firstPocketedType != STRIPE)
  2338.             return false;                                 // safety
  2339.  
  2340.         /* ---------------------------------------------------------
  2341.            1.  Decide the groups
  2342.         --------------------------------------------------------- */
  2343.         if (currentPlayer == 1)
  2344.         {
  2345.             player1Info.assignedType = firstPocketedType;
  2346.             player2Info.assignedType =
  2347.                 (firstPocketedType == SOLID) ? STRIPE : SOLID;
  2348.         }
  2349.         else
  2350.         {
  2351.             player2Info.assignedType = firstPocketedType;
  2352.             player1Info.assignedType =
  2353.                 (firstPocketedType == SOLID) ? STRIPE : SOLID;
  2354.         }
  2355.  
  2356.         /* ---------------------------------------------------------
  2357.            2.  Count the very ball that made the assignment
  2358.         --------------------------------------------------------- */
  2359.         if (creditShooter)
  2360.         {
  2361.             if (currentPlayer == 1)
  2362.                 ++player1Info.ballsPocketedCount;
  2363.             else
  2364.                 ++player2Info.ballsPocketedCount;
  2365.         }
  2366.         return true;
  2367.     }
  2368.  
  2369.     /*bool AssignPlayerBallTypes(BallType firstPocketedType) {
  2370.         if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  2371.             if (currentPlayer == 1) {
  2372.                 player1Info.assignedType = firstPocketedType;
  2373.                 player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2374.             }
  2375.             else {
  2376.                 player2Info.assignedType = firstPocketedType;
  2377.                 player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2378.             }
  2379.             return true; // Assignment was successful
  2380.         }
  2381.         return false; // No assignment made (e.g., 8-ball was pocketed on break)
  2382.     }*/
  2383.     // If 8-ball was first (illegal on break generally), rules vary.
  2384.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  2385.     // Or assign based on what *else* was pocketed, if anything.
  2386.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  2387.  
  2388.  
  2389.     // --- Called in ProcessShotResults() after pocket detection ---
  2390.     void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2391.     {
  2392.         // Only care if the 8?ball really went in:
  2393.         if (!eightBallPocketed) return;
  2394.  
  2395.         // Who’s shooting now?
  2396.         PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2397.         PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2398.  
  2399.         // Which pocket did we CALL?
  2400.         int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2401.         // Which pocket did it ACTUALLY fall into?
  2402.         int actual = lastEightBallPocketIndex;
  2403.  
  2404.         // Check legality: must have called a pocket ?0, must match actual,
  2405.         // must have pocketed all 7 of your balls first, and must not have scratched.
  2406.         bool legal = (called >= 0)
  2407.             && (called == actual)
  2408.             && (shooter.ballsPocketedCount >= 7)
  2409.             && (!cueBallPocketed);
  2410.  
  2411.         // Build a message that shows both values for debugging/tracing:
  2412.         if (legal) {
  2413.             gameOverMessage = shooter.name
  2414.                 + L" Wins! "
  2415.                 + L"(Called: " + std::to_wstring(called)
  2416.                 + L", Actual: " + std::to_wstring(actual) + L")";
  2417.         }
  2418.         else {
  2419.             gameOverMessage = opponent.name
  2420.                 + L" Wins! (Illegal 8-Ball) "
  2421.                 + L"(Called: " + std::to_wstring(called)
  2422.                 + L", Actual: " + std::to_wstring(actual) + L")";
  2423.         }
  2424.  
  2425.         currentGameState = GAME_OVER;
  2426.     }
  2427.  
  2428.  
  2429.  
  2430.     /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2431.         if (!eightBallPocketed) return;
  2432.  
  2433.         PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  2434.         PlayerInfo& opponentPlayer = (currentPlayer == 1) ? player2Info : player1Info;
  2435.  
  2436.         // Handle 8-ball on break: re-spot and continue.
  2437.         if (player1Info.assignedType == BallType::NONE) {
  2438.             Ball* b = GetBallById(8);
  2439.             if (b) { b->isPocketed = false; b->x = RACK_POS_X; b->y = RACK_POS_Y; b->vx = b->vy = 0; }
  2440.             if (cueBallPocketed) foulCommitted = true;
  2441.             return;
  2442.         }
  2443.  
  2444.         // --- FOOLPROOF WIN/LOSS LOGIC ---
  2445.         bool wasOnEightBall = IsPlayerOnEightBall(currentPlayer);
  2446.         int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2447.         int actualPocket = -1;
  2448.  
  2449.         // Find which pocket the 8-ball actually went into.
  2450.         for (int id : pocketedThisTurn) {
  2451.             if (id == 8) {
  2452.                 Ball* b = GetBallById(8); // This ball is already marked as pocketed, but we need its last coords.
  2453.                 if (b) {
  2454.                     for (int p_idx = 0; p_idx < 6; ++p_idx) {
  2455.                         // Check last known position against pocket centers
  2456.                         if (GetDistanceSq(b->x, b->y, pocketPositions[p_idx].x, pocketPositions[p_idx].y) < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2457.                             actualPocket = p_idx;
  2458.                             break;
  2459.                         }
  2460.                     }
  2461.                 }
  2462.                 break;
  2463.             }
  2464.         }
  2465.  
  2466.         // Evaluate win/loss based on a clear hierarchy of rules.
  2467.         if (!wasOnEightBall) {
  2468.             gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball Pocketed Early)";
  2469.         }
  2470.         else if (cueBallPocketed) {
  2471.             gameOverMessage = opponentPlayer.name + L" Wins! (Scratched on 8-Ball)";
  2472.         }
  2473.         else if (calledPocket == -1) {
  2474.             gameOverMessage = opponentPlayer.name + L" Wins! (Pocket Not Called)";
  2475.         }
  2476.         else if (actualPocket != calledPocket) {
  2477.             gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball in Wrong Pocket)";
  2478.         }
  2479.         else {
  2480.             // WIN! All loss conditions failed, this must be a legal win.
  2481.             gameOverMessage = shootingPlayer.name + L" Wins!";
  2482.         }
  2483.  
  2484.         currentGameState = GAME_OVER;
  2485.     }*/
  2486.  
  2487.     /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2488.     {
  2489.         if (!eightBallPocketed) return;
  2490.  
  2491.         PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2492.         PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2493.         // Which pocket did we call?
  2494.         int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2495.         // Which pocket did the ball really fall into?
  2496.         int actual = lastEightBallPocketIndex;
  2497.  
  2498.         // Legal victory only if:
  2499.         //  1) Shooter had already pocketed 7 of their object balls,
  2500.         //  2) They called a pocket,
  2501.         //  3) The 8?ball actually fell into that same pocket,
  2502.         //  4) They did not scratch on the 8?ball.
  2503.         bool legal =
  2504.             (shooter.ballsPocketedCount >= 7) &&
  2505.             (called >= 0) &&
  2506.             (called == actual) &&
  2507.             (!cueBallPocketed);
  2508.  
  2509.         if (legal) {
  2510.             gameOverMessage = shooter.name + L" Wins! "
  2511.                 L"(called: " + std::to_wstring(called) +
  2512.                 L", actual: " + std::to_wstring(actual) + L")";
  2513.         }
  2514.         else {
  2515.             gameOverMessage = opponent.name + L" Wins! (illegal 8-ball) "
  2516.             // For debugging you can append:
  2517.             + L" (called: " + std::to_wstring(called)
  2518.             + L", actual: " + std::to_wstring(actual) + L")";
  2519.         }
  2520.  
  2521.         currentGameState = GAME_OVER;
  2522.     }*/
  2523.  
  2524.     // ????????????????????????????????????????????????????????????????
  2525.     //  CheckGameOverConditions()
  2526.     //     – Called when the 8-ball has fallen.
  2527.     //     – Decides who wins and builds the gameOverMessage.
  2528.     // ????????????????????????????????????????????????????????????????
  2529.     /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2530.     {
  2531.         if (!eightBallPocketed) return;                     // safety
  2532.  
  2533.         PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2534.         PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2535.  
  2536.         int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2537.         int actualPocket = lastEightBallPocketIndex;
  2538.  
  2539.         bool clearedSeven = (shooter.ballsPocketedCount >= 7);
  2540.         bool noScratch = !cueBallPocketed;
  2541.         bool callMade = (calledPocket >= 0);
  2542.  
  2543.         // helper ? turn “-1” into "None" for readability
  2544.         auto pocketToStr = [](int idx) -> std::wstring
  2545.         {
  2546.             return (idx >= 0) ? std::to_wstring(idx) : L"None";
  2547.         };
  2548.  
  2549.         if (clearedSeven && noScratch && callMade && actualPocket == calledPocket)
  2550.         {
  2551.             // legitimate win
  2552.             gameOverMessage =
  2553.                 shooter.name +
  2554.                 L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2555.                 L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2556.         }
  2557.         else
  2558.         {
  2559.             // wrong pocket, scratch, or early 8-ball
  2560.             gameOverMessage =
  2561.                 opponent.name +
  2562.                 L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2563.                 L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2564.         }
  2565.  
  2566.         currentGameState = GAME_OVER;
  2567.     }*/
  2568.  
  2569.     /* void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2570.         if (!eightBallPocketed) return; // Only when 8-ball actually pocketed
  2571.  
  2572.         PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2573.         PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2574.         bool      onEightRoll = IsPlayerOnEightBall(currentPlayer);
  2575.         int       calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2576.         int       actualPocket = -1;
  2577.         Ball* bEight = GetBallById(8);
  2578.  
  2579.         // locate which hole the 8-ball went into
  2580.         if (bEight) {
  2581.             for (int i = 0; i < 6; ++i) {
  2582.                 if (GetDistanceSq(bEight->x, bEight->y,
  2583.                     pocketPositions[i].x, pocketPositions[i].y)
  2584.                     < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2585.                     actualPocket = i; break;
  2586.                 }
  2587.             }
  2588.         }
  2589.  
  2590.         // 1) On break / pre-assignment: re-spot & continue
  2591.         if (player1Info.assignedType == BallType::NONE) {
  2592.             if (bEight) {
  2593.                 bEight->isPocketed = false;
  2594.                 bEight->x = RACK_POS_X; bEight->y = RACK_POS_Y;
  2595.                 bEight->vx = bEight->vy = 0;
  2596.             }
  2597.             if (cueBallPocketed) foulCommitted = true;
  2598.             return;
  2599.         }
  2600.  
  2601.         // 2) Loss if pocketed 8 early
  2602.         if (!onEightRoll) {
  2603.             gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" pocketed 8-ball early)";
  2604.         }
  2605.         // 3) Loss if scratched
  2606.         else if (cueBallPocketed) {
  2607.             gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" scratched on 8-ball)";
  2608.         }
  2609.         // 4) Loss if no pocket call
  2610.         else if (calledPocket < 0) {
  2611.             gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" did not call a pocket)";
  2612.         }
  2613.         // 5) Loss if in wrong pocket
  2614.         else if (actualPocket != calledPocket) {
  2615.             gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" 8-ball in wrong pocket)";
  2616.         }
  2617.         // 6) Otherwise, valid win
  2618.         else {
  2619.             gameOverMessage = shooter.name + L" Wins!";
  2620.         }
  2621.  
  2622.         currentGameState = GAME_OVER;
  2623.     } */
  2624.  
  2625.  
  2626.     // Switch the shooter, handle fouls and decide what state we go to next.
  2627.     // ────────────────────────────────────────────────────────────────
  2628.     //  SwitchTurns – final version (arrow–leak bug fixed)
  2629.     // ────────────────────────────────────────────────────────────────
  2630.     void SwitchTurns()
  2631.     {
  2632.         /* --------------------------------------------------------- */
  2633.         /* 1.  Hand the table over to the other player               */
  2634.         /* --------------------------------------------------------- */
  2635.         currentPlayer = (currentPlayer == 1) ? 2 : 1;
  2636.  
  2637.         /* --------------------------------------------------------- */
  2638.         /* 2.  Generic per–turn resets                               */
  2639.         /* --------------------------------------------------------- */
  2640.         isAiming = false;
  2641.         shotPower = 0.0f;
  2642.         currentlyHoveredPocket = -1;
  2643.  
  2644.         /* --------------------------------------------------------- */
  2645.         /* 3.  Wipe every previous pocket call                       */
  2646.         /*    (the new shooter will choose again if needed)          */
  2647.         /* --------------------------------------------------------- */
  2648.         calledPocketP1 = -1;
  2649.         calledPocketP2 = -1;
  2650.         pocketCallMessage.clear();
  2651.  
  2652.         /* --------------------------------------------------------- */
  2653.         /* 4.  Handle fouls — cue-ball in hand overrides everything  */
  2654.         /* --------------------------------------------------------- */
  2655.         if (foulCommitted)
  2656.         {
  2657.             if (currentPlayer == 1)            // human
  2658.             {
  2659.                 currentGameState = BALL_IN_HAND_P1;
  2660.                 aiTurnPending = false;
  2661.             }
  2662.             else                               // P2
  2663.             {
  2664.                 currentGameState = BALL_IN_HAND_P2;
  2665.                 aiTurnPending = isPlayer2AI;   // AI will place cue-ball
  2666.             }
  2667.  
  2668.             foulCommitted = false;
  2669.             return;                            // we're done for this frame
  2670.         }
  2671.  
  2672.         /* --------------------------------------------------------- */
  2673.         /* 5.  Normal flow                                           */
  2674.         /*    Will put us in  ∘ PLAYER?_TURN                         */
  2675.         /*                    ∘ CHOOSING_POCKET_P?                   */
  2676.         /*                    ∘ AI_THINKING  (for CPU)               */
  2677.         /* --------------------------------------------------------- */
  2678.         CheckAndTransitionToPocketChoice(currentPlayer);
  2679.     }
  2680.  
  2681.  
  2682.     void AIBreakShot() {
  2683.         Ball* cueBall = GetCueBall();
  2684.         if (!cueBall) return;
  2685.  
  2686.         // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  2687.         // AI will place the cue ball and then plan the shot.
  2688.         if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2689.             // Place cue ball in the kitchen randomly
  2690.             /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  2691.             float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  2692.             float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  2693.             float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  2694.  
  2695.             // --- AI Places Cue Ball for Break ---
  2696.     // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  2697.     // towards one side for a more angled break, or center for direct apex hit.
  2698.     // A common strategy is to hit the second ball of the rack.
  2699.  
  2700.             float placementY = RACK_POS_Y; // Align vertically with the rack center
  2701.             float placementX;
  2702.  
  2703.             // Randomly choose a side or center-ish placement for variation.
  2704.             int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  2705.  
  2706.             if (placementChoice == 0) { // Left-ish
  2707.                 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  2708.             }
  2709.             else if (placementChoice == 2) { // Right-ish
  2710.                 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  2711.             }
  2712.             else { // Center-ish
  2713.                 placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  2714.             }
  2715.             placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  2716.  
  2717.             bool validPos = false;
  2718.             int attempts = 0;
  2719.             while (!validPos && attempts < 100) {
  2720.                 /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  2721.                 cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  2722.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  2723.                     validPos = true; // [cite: 1591]*/
  2724.                     // Try the chosen X, but vary Y slightly to find a clear spot
  2725.                 cueBall->x = placementX;
  2726.                 cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  2727.                 cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  2728.  
  2729.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  2730.                     validPos = true;
  2731.                 }
  2732.                 attempts++; // [cite: 1592]
  2733.             }
  2734.             if (!validPos) {
  2735.                 // Fallback position
  2736.                 /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  2737.                 cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  2738.                 if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  2739.                     cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  2740.                     cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  2741.                 }
  2742.             }
  2743.             cueBall->vx = 0; // [cite: 1595]
  2744.             cueBall->vy = 0; // [cite: 1596]
  2745.  
  2746.             // Plan a break shot: aim at the center of the rack (apex ball)
  2747.             float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  2748.             float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  2749.  
  2750.             float dx = targetX - cueBall->x; // [cite: 1599]
  2751.             float dy = targetY - cueBall->y; // [cite: 1600]
  2752.             float shotAngle = atan2f(dy, dx); // [cite: 1600]
  2753.             float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  2754.  
  2755.                 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  2756.                 cueBall->y = RACK_POS_Y;
  2757.             }
  2758.             cueBall->vx = 0; cueBall->vy = 0;
  2759.  
  2760.             // --- AI Plans the Break Shot ---
  2761.             float targetX, targetY;
  2762.             // If cue ball is near center of kitchen width, aim for apex.
  2763.             // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  2764.             float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  2765.             if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  2766.                 // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  2767.                 targetX = RACK_POS_X; // Apex ball X
  2768.                 targetY = RACK_POS_Y; // Apex ball Y
  2769.             }
  2770.             else {
  2771.                 // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  2772.                 // This is a simplification. A more robust way is to find the actual second ball.
  2773.                 // For now, aim slightly off the apex towards the side the cue ball is on.
  2774.                 targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  2775.                 targetY = RACK_POS_Y + ((cueBall->y > RACK_POS_Y) ? -BALL_RADIUS : BALL_RADIUS); // Aim at the upper or lower of the two second-row balls
  2776.             }
  2777.  
  2778.             float dx = targetX - cueBall->x;
  2779.             float dy = targetY - cueBall->y;
  2780.             float shotAngle = atan2f(dy, dx);
  2781.             float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  2782.  
  2783.             // Store planned shot details for the AI
  2784.             /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  2785.             aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  2786.             aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  2787.             aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  2788.             aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  2789.  
  2790.             aiPlannedShotDetails.angle = shotAngle;
  2791.             aiPlannedShotDetails.power = shotPowerValue;
  2792.             aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  2793.             aiPlannedShotDetails.spinY = 0.0f;
  2794.             aiPlannedShotDetails.isValid = true;
  2795.  
  2796.             // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  2797.             /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  2798.             ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  2799.             ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  2800.             ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  2801.  
  2802.             ::cueAngle = aiPlannedShotDetails.angle;
  2803.             ::shotPower = aiPlannedShotDetails.power;
  2804.             ::cueSpinX = aiPlannedShotDetails.spinX;
  2805.             ::cueSpinY = aiPlannedShotDetails.spinY;
  2806.  
  2807.             // Set up for AI display via GameUpdate
  2808.             /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  2809.             aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  2810.  
  2811.             currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  2812.                                             // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  2813.                                             // and then execute the shot using aiPlannedShotDetails.
  2814.                                             // isOpeningBreakShot will be set to false within ApplyShot.
  2815.  
  2816.             // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  2817.  
  2818.             aiIsDisplayingAim = true;
  2819.             aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2820.             currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  2821.             aiTurnPending = false;
  2822.  
  2823.             return; // The break shot is now planned and will be executed by GameUpdate
  2824.         }
  2825.  
  2826.         // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  2827.         //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  2828.         //    This part can be extended if AIBreakShot needs to handle other scenarios.
  2829.         //    For now, the primary logic is above.
  2830.     }
  2831.  
  2832.     // --- Helper Functions ---
  2833.  
  2834.     Ball* GetBallById(int id) {
  2835.         for (size_t i = 0; i < balls.size(); ++i) {
  2836.             if (balls[i].id == id) {
  2837.                 return &balls[i];
  2838.             }
  2839.         }
  2840.         return nullptr;
  2841.     }
  2842.  
  2843.     Ball* GetCueBall() {
  2844.         return GetBallById(0);
  2845.     }
  2846.  
  2847.     float GetDistance(float x1, float y1, float x2, float y2) {
  2848.         return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  2849.     }
  2850.  
  2851.     float GetDistanceSq(float x1, float y1, float x2, float y2) {
  2852.         float dx = x2 - x1;
  2853.         float dy = y2 - y1;
  2854.         return dx * dx + dy * dy;
  2855.     }
  2856.  
  2857.     bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  2858.         // Basic bounds check (inside cushions)
  2859.         float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  2860.         float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  2861.         float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  2862.         float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  2863.  
  2864.         if (x < left || x > right || y < top || y > bottom) {
  2865.             return false;
  2866.         }
  2867.  
  2868.         // Check headstring restriction if needed
  2869.         if (checkHeadstring && x >= HEADSTRING_X) {
  2870.             return false;
  2871.         }
  2872.  
  2873.         // Check overlap with other balls
  2874.         for (size_t i = 0; i < balls.size(); ++i) {
  2875.             if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  2876.                 if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  2877.                     return false; // Overlapping another ball
  2878.                 }
  2879.             }
  2880.         }
  2881.  
  2882.         return true;
  2883.     }
  2884.  
  2885.     // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  2886.  
  2887.     // Checks if a player has pocketed all their balls and is now on the 8-ball.
  2888.     bool IsPlayerOnEightBall(int player) {
  2889.         PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  2890.         if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  2891.             Ball* eightBall = GetBallById(8);
  2892.             return (eightBall && !eightBall->isPocketed);
  2893.         }
  2894.         return false;
  2895.     }
  2896.  
  2897.     void CheckAndTransitionToPocketChoice(int playerID) {
  2898.         bool needsToCall = IsPlayerOnEightBall(playerID);
  2899.  
  2900.         if (needsToCall) {
  2901.             if (playerID == 1) { // Human Player 1
  2902.                 currentGameState = CHOOSING_POCKET_P1;
  2903.                 pocketCallMessage = player1Info.name + L": Choose a pocket for the 8-Ball...";
  2904.                 if (calledPocketP1 == -1) calledPocketP1 = 2; // Default to bottom-right
  2905.             }
  2906.             else { // Player 2
  2907.                 if (isPlayer2AI) {
  2908.                     // FOOLPROOF FIX: AI doesn't choose here. It transitions to a thinking state.
  2909.                     // AIMakeDecision will handle the choice and the pocket call.
  2910.                     currentGameState = AI_THINKING;
  2911.                     aiTurnPending = true; // Signal the main loop to run AIMakeDecision
  2912.                 }
  2913.                 else { // Human Player 2
  2914.                     currentGameState = CHOOSING_POCKET_P2;
  2915.                     pocketCallMessage = player2Info.name + L": Choose a pocket for the 8-Ball...";
  2916.                     if (calledPocketP2 == -1) calledPocketP2 = 2; // Default to bottom-right
  2917.                 }
  2918.             }
  2919.         }
  2920.         else {
  2921.             // Player does not need to call a pocket, proceed to normal turn.
  2922.             pocketCallMessage = L"";
  2923.             currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2924.             if (playerID == 2 && isPlayer2AI) {
  2925.                 aiTurnPending = true;
  2926.             }
  2927.         }
  2928.     }
  2929.  
  2930.  
  2931.     template <typename T>
  2932.     void SafeRelease(T** ppT) {
  2933.         if (*ppT) {
  2934.             (*ppT)->Release();
  2935.             *ppT = nullptr;
  2936.         }
  2937.     }
  2938.  
  2939.     // --- CPU Ball?in?Hand Placement --------------------------------
  2940.     // Moves the cue ball to a legal "ball in hand" position for the AI.
  2941.     void AIPlaceCueBall() {
  2942.         Ball* cue = GetCueBall();
  2943.         if (!cue) return;
  2944.  
  2945.         // Simple strategy: place back behind the headstring at the standard break spot
  2946.         cue->x = TABLE_LEFT + TABLE_WIDTH * 0.15f;
  2947.         cue->y = RACK_POS_Y;
  2948.         cue->vx = cue->vy = 0.0f;
  2949.     }
  2950.  
  2951.     // --- Helper Function for Line Segment Intersection ---
  2952.     // Finds intersection point of line segment P1->P2 and line segment P3->P4
  2953.     // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  2954.     bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  2955.     {
  2956.         float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  2957.  
  2958.         // Check if lines are parallel or collinear
  2959.         if (fabs(denominator) < 1e-6) {
  2960.             return false;
  2961.         }
  2962.  
  2963.         float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  2964.         float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  2965.  
  2966.         // Check if intersection point lies on both segments
  2967.         if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  2968.             intersection.x = p1.x + ua * (p2.x - p1.x);
  2969.             intersection.y = p1.y + ua * (p2.y - p1.y);
  2970.             return true;
  2971.         }
  2972.  
  2973.         return false;
  2974.     }
  2975.  
  2976.     // --- INSERT NEW HELPER FUNCTION HERE ---
  2977.     // Calculates the squared distance from point P to the line segment AB.
  2978.     float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  2979.         float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  2980.         if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  2981.         // Consider P projecting onto the line AB infinite line
  2982.         // t = [(P-A) . (B-A)] / |B-A|^2
  2983.         float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  2984.         t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  2985.         // Projection falls on the segment
  2986.         D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  2987.         return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  2988.     }
  2989.     // --- End New Helper ---
  2990.  
  2991.     // --- NEW AI Implementation Functions ---
  2992.  
  2993.     void AIMakeDecision() {
  2994.         // Start with a clean slate for the AI's plan.
  2995.         aiPlannedShotDetails.isValid = false;
  2996.         Ball* cueBall = GetCueBall();
  2997.         if (!cueBall || !isPlayer2AI || currentPlayer != 2) return;
  2998.  
  2999.         // Ask the "expert" (AIFindBestShot) for the best possible shot.
  3000.         AIShotInfo bestShot = AIFindBestShot();
  3001.  
  3002.         if (bestShot.possible) {
  3003.             // A good shot was found.
  3004.             // If it's an 8-ball shot, "call" the pocket.
  3005.             if (bestShot.involves8Ball) {
  3006.                 calledPocketP2 = bestShot.pocketIndex;
  3007.             }
  3008.             else {
  3009.                 calledPocketP2 = -1; // Ensure no pocket is called on a normal shot.
  3010.             }
  3011.  
  3012.             // Commit the details of the best shot to the AI's plan.
  3013.             aiPlannedShotDetails.angle = bestShot.angle;
  3014.             aiPlannedShotDetails.power = bestShot.power;
  3015.             aiPlannedShotDetails.spinX = bestShot.spinX;
  3016.             aiPlannedShotDetails.spinY = bestShot.spinY;
  3017.             aiPlannedShotDetails.isValid = true;
  3018.  
  3019.         }
  3020.         else {
  3021.             // No good offensive shot found, must play a safe defensive shot.
  3022.             // (This is a fallback and your current AIFindBestShot should prevent this)
  3023.             aiPlannedShotDetails.isValid = false;
  3024.         }
  3025.  
  3026.         // --- FOOLPROOF FIX: Trigger the Aim Display ---
  3027.         // If any valid plan was made, update the visuals and start the display pause.
  3028.         if (aiPlannedShotDetails.isValid) {
  3029.  
  3030.             // STEP 1: Copy the AI's plan into the global variables used for drawing.
  3031.             // This is the critical missing link.
  3032.             cueAngle = aiPlannedShotDetails.angle;
  3033.             shotPower = aiPlannedShotDetails.power;
  3034.  
  3035.             // STEP 2: Trigger the visual display pause.
  3036.             // These are the two lines you correctly identified.
  3037.             aiIsDisplayingAim = true;
  3038.             aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  3039.  
  3040.         }
  3041.         else {
  3042.             // Absolute fallback: If no plan could be made, switch turns to prevent a freeze.
  3043.             SwitchTurns();
  3044.         }
  3045.     }
  3046.  
  3047.  
  3048.     AIShotInfo AIFindBestShot()
  3049.     {
  3050.         AIShotInfo best;                       // .possible == false
  3051.         Ball* cue = GetCueBall();
  3052.         if (!cue) return best;
  3053.  
  3054.         const bool on8 = IsPlayerOnEightBall(2);
  3055.         const BallType wantType = player2Info.assignedType;
  3056.  
  3057.         for (Ball& b : balls)
  3058.         {
  3059.             if (b.isPocketed || b.id == 0) continue;
  3060.  
  3061.             // decide if this ball is a legal/interesting target
  3062.             bool ok =
  3063.                 on8 ? (b.id == 8) :
  3064.                 ((wantType == BallType::NONE) || (b.type == wantType));
  3065.  
  3066.             if (!ok) continue;
  3067.  
  3068.             for (int p = 0; p < 6; ++p)
  3069.             {
  3070.                 AIShotInfo cand = EvaluateShot(&b, p);
  3071.                 if (cand.possible &&
  3072.                     (!best.possible || cand.score > best.score))
  3073.                     best = cand;
  3074.             }
  3075.         }
  3076.  
  3077.         // fall-back: tap cue ball forward (safety) if no potting line exists
  3078.         if (!best.possible && cue)
  3079.         {
  3080.             best.possible = true;
  3081.             best.angle = static_cast<float>(rand()) / RAND_MAX * 2.0f * PI;
  3082.             best.power = MAX_SHOT_POWER * 0.30f;
  3083.             best.spinX = best.spinY = 0.0f;
  3084.             best.targetBall = nullptr;
  3085.             best.score = -99999.0f;
  3086.             best.pocketIndex = -1;
  3087.         }
  3088.         return best;
  3089.     }
  3090.  
  3091.  
  3092.     // Evaluate a potential shot at a specific target ball towards a specific pocket
  3093.     AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  3094.         AIShotInfo shotInfo; // Defaults to not possible
  3095.         shotInfo.targetBall = targetBall;
  3096.         shotInfo.pocketIndex = pocketIndex;
  3097.         shotInfo.involves8Ball = (targetBall && targetBall->id == 8);
  3098.  
  3099.         Ball* cueBall = GetCueBall();
  3100.         if (!cueBall || !targetBall) return shotInfo;
  3101.  
  3102.         // 1. Calculate Ghost Ball position (where cue must hit target)
  3103.         shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  3104.  
  3105.         // 2. Check Path: Cue Ball -> Ghost Ball Position
  3106.         if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  3107.             return shotInfo; // Path blocked, shot is impossible.
  3108.         }
  3109.  
  3110.         // 3. Calculate Angle and Power
  3111.         float dx = shotInfo.ghostBallPos.x - cueBall->x;
  3112.         float dy = shotInfo.ghostBallPos.y - cueBall->y;
  3113.         shotInfo.angle = atan2f(dy, dx);
  3114.  
  3115.         float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  3116.         float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  3117.         shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  3118.  
  3119.         // 4. Score the shot (simple scoring: closer and straighter is better)
  3120.         shotInfo.score = 1000.0f - (cueToGhostDist + targetToPocketDist);
  3121.  
  3122.         // If we reached here, the shot is geometrically possible.
  3123.         shotInfo.possible = true;
  3124.         return shotInfo;
  3125.     }
  3126.  
  3127.  
  3128.     //  Estimate the power that will carry the cue-ball to the ghost position
  3129.     //  *and* push the object-ball the remaining distance to the pocket.
  3130.     //
  3131.     //  • cueToGhostDist    – pixels from cue to ghost-ball centre
  3132.     //  • targetToPocketDist– pixels from object-ball to chosen pocket
  3133.     //
  3134.     //  The function is fully deterministic (good for AI search) yet produces
  3135.     //  human-looking power levels.
  3136.     //
  3137.     float CalculateShotPower(float cueToGhostDist, float targetToPocketDist)
  3138.     {
  3139.         // Total distance the *energy* must cover (cue path + object-ball path)
  3140.         float totalDist = cueToGhostDist + targetToPocketDist;
  3141.  
  3142.         // Typical diagonal of the playable area (approx.) – used for scaling
  3143.         constexpr float TABLE_DIAG = 900.0f;
  3144.  
  3145.         // 1.  Convert distance to a 0-1 number (0: tap-in, 1: table length)
  3146.         float norm = std::clamp(totalDist / TABLE_DIAG, 0.0f, 1.0f);
  3147.  
  3148.         // 2.  Ease-in curve (smoothstep) for nicer progression
  3149.         norm = norm * norm * (3.0f - 2.0f * norm);
  3150.  
  3151.         // 3.  Blend between a gentle minimum and the absolute maximum
  3152.         const float MIN_POWER = MAX_SHOT_POWER * 0.18f;     // just enough to move
  3153.         float power = MIN_POWER + norm * (MAX_SHOT_POWER - MIN_POWER);
  3154.  
  3155.         // 4.  Safety clamp (also screens out degenerate calls)
  3156.         power = std::clamp(power, 0.15f, MAX_SHOT_POWER);
  3157.  
  3158.         return power;
  3159.     }
  3160.  
  3161.     // ------------------------------------------------------------------
  3162.     //  Return the ghost-ball centre needed for the target ball to roll
  3163.     //  straight into the chosen pocket.
  3164.     // ------------------------------------------------------------------
  3165.     D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex)
  3166.     {
  3167.         if (!targetBall) return D2D1::Point2F(0, 0);
  3168.  
  3169.         D2D1_POINT_2F P = pocketPositions[pocketIndex];
  3170.  
  3171.         float vx = P.x - targetBall->x;
  3172.         float vy = P.y - targetBall->y;
  3173.         float L = sqrtf(vx * vx + vy * vy);
  3174.         if (L < 1.0f) L = 1.0f;                // safety
  3175.  
  3176.         vx /= L;   vy /= L;
  3177.  
  3178.         return D2D1::Point2F(
  3179.             targetBall->x - vx * (BALL_RADIUS * 2.0f),
  3180.             targetBall->y - vy * (BALL_RADIUS * 2.0f));
  3181.     }
  3182.  
  3183.     // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  3184.     // ────────────────────────────────────────────────────────────────
  3185.     //   2.  Shot evaluation & search
  3186.     // ────────────────────────────────────────────────────────────────
  3187.  
  3188.     //  Calculate ghost-ball position so that cue hits target towards pocket
  3189.     static inline D2D1_POINT_2F GhostPos(const Ball* tgt, int pocketIdx)
  3190.     {
  3191.         D2D1_POINT_2F P = pocketPositions[pocketIdx];
  3192.         float vx = P.x - tgt->x;
  3193.         float vy = P.y - tgt->y;
  3194.         float L = sqrtf(vx * vx + vy * vy);
  3195.         vx /= L;  vy /= L;
  3196.         return D2D1::Point2F(tgt->x - vx * (BALL_RADIUS * 2.0f),
  3197.             tgt->y - vy * (BALL_RADIUS * 2.0f));
  3198.     }
  3199.  
  3200.     //  Heuristic: shorter + straighter + proper group = higher score
  3201.     static inline float ScoreShot(float cue2Ghost,
  3202.         float tgt2Pocket,
  3203.         bool  correctGroup,
  3204.         bool  involves8)
  3205.     {
  3206.         float base = 2000.0f - (cue2Ghost + tgt2Pocket);   // prefer close shots
  3207.         if (!correctGroup)  base -= 400.0f;                  // penalty
  3208.         if (involves8)      base += 150.0f;                  // a bit more desirable
  3209.         return base;
  3210.     }
  3211.  
  3212.     // Checks if line segment is clear of obstructing balls
  3213.     // ────────────────────────────────────────────────────────────────
  3214.     //   1.  Low-level helpers – IsPathClear & FindFirstHitBall
  3215.     // ────────────────────────────────────────────────────────────────
  3216.  
  3217.     //  Test if the capsule [ start … end ] (radius = BALL_RADIUS)
  3218.     //  intersects any ball except the ids we want to ignore.
  3219.     bool IsPathClear(D2D1_POINT_2F start,
  3220.         D2D1_POINT_2F end,
  3221.         int ignoredBallId1,
  3222.         int ignoredBallId2)
  3223.     {
  3224.         float dx = end.x - start.x;
  3225.         float dy = end.y - start.y;
  3226.         float lenSq = dx * dx + dy * dy;
  3227.         if (lenSq < 1e-3f) return true;             // degenerate → treat as clear
  3228.  
  3229.         for (const Ball& b : balls)
  3230.         {
  3231.             if (b.isPocketed)      continue;
  3232.             if (b.id == ignoredBallId1 ||
  3233.                 b.id == ignoredBallId2)             continue;
  3234.  
  3235.             // project ball centre onto the segment
  3236.             float t = ((b.x - start.x) * dx + (b.y - start.y) * dy) / lenSq;
  3237.             t = std::clamp(t, 0.0f, 1.0f);
  3238.  
  3239.             float cx = start.x + t * dx;
  3240.             float cy = start.y + t * dy;
  3241.  
  3242.             if (GetDistanceSq(b.x, b.y, cx, cy) < (BALL_RADIUS * BALL_RADIUS))
  3243.                 return false;                       // blocked
  3244.         }
  3245.         return true;
  3246.     }
  3247.  
  3248.     //  Cast an (infinite) ray and return the first non-pocketed ball hit.
  3249.     //  `hitDistSq` is distance² from the start point to the collision point.
  3250.     Ball* FindFirstHitBall(D2D1_POINT_2F start,
  3251.         float        angle,
  3252.         float& hitDistSq)
  3253.     {
  3254.         Ball* hitBall = nullptr;
  3255.         float  bestSq = std::numeric_limits<float>::max();
  3256.         float  cosA = cosf(angle);
  3257.         float  sinA = sinf(angle);
  3258.  
  3259.         for (Ball& b : balls)
  3260.         {
  3261.             if (b.id == 0 || b.isPocketed) continue;         // ignore cue & sunk balls
  3262.  
  3263.             float relX = b.x - start.x;
  3264.             float relY = b.y - start.y;
  3265.             float proj = relX * cosA + relY * sinA;          // distance along the ray
  3266.  
  3267.             if (proj <= 0) continue;                         // behind cue
  3268.  
  3269.             // closest approach of the ray to the sphere centre
  3270.             float closestX = start.x + proj * cosA;
  3271.             float closestY = start.y + proj * sinA;
  3272.             float dSq = GetDistanceSq(b.x, b.y, closestX, closestY);
  3273.  
  3274.             if (dSq <= BALL_RADIUS * BALL_RADIUS)            // intersection
  3275.             {
  3276.                 float back = sqrtf(BALL_RADIUS * BALL_RADIUS - dSq);
  3277.                 float collDist = proj - back;                // front surface
  3278.                 float collSq = collDist * collDist;
  3279.                 if (collSq < bestSq)
  3280.                 {
  3281.                     bestSq = collSq;
  3282.                     hitBall = &b;
  3283.                 }
  3284.             }
  3285.         }
  3286.         hitDistSq = bestSq;
  3287.         return hitBall;
  3288.     }
  3289.  
  3290.     // Basic check for reasonable AI aim angles (optional)
  3291.     bool IsValidAIAimAngle(float angle) {
  3292.         // Placeholder - could check for NaN or infinity if calculations go wrong
  3293.         return isfinite(angle);
  3294.     }
  3295.  
  3296.     //midi func = start
  3297.     void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  3298.         while (isMusicPlaying) {
  3299.             MCI_OPEN_PARMS mciOpen = { 0 };
  3300.             mciOpen.lpstrDeviceType = TEXT("sequencer");
  3301.             mciOpen.lpstrElementName = midiPath;
  3302.  
  3303.             if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  3304.                 midiDeviceID = mciOpen.wDeviceID;
  3305.  
  3306.                 MCI_PLAY_PARMS mciPlay = { 0 };
  3307.                 mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  3308.  
  3309.                 // Wait for playback to complete
  3310.                 MCI_STATUS_PARMS mciStatus = { 0 };
  3311.                 mciStatus.dwItem = MCI_STATUS_MODE;
  3312.  
  3313.                 do {
  3314.                     mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  3315.                     Sleep(100); // adjust as needed
  3316.                 } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  3317.  
  3318.                 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3319.                 midiDeviceID = 0;
  3320.             }
  3321.         }
  3322.     }
  3323.  
  3324.     void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  3325.         if (isMusicPlaying) {
  3326.             StopMidi();
  3327.         }
  3328.         isMusicPlaying = true;
  3329.         musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3330.     }
  3331.  
  3332.     void StopMidi() {
  3333.         if (isMusicPlaying) {
  3334.             isMusicPlaying = false;
  3335.             if (musicThread.joinable()) musicThread.join();
  3336.             if (midiDeviceID != 0) {
  3337.                 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3338.                 midiDeviceID = 0;
  3339.             }
  3340.         }
  3341.     }
  3342.  
  3343.     /*void PlayGameMusic(HWND hwnd) {
  3344.         // Stop any existing playback
  3345.         if (isMusicPlaying) {
  3346.             isMusicPlaying = false;
  3347.             if (musicThread.joinable()) {
  3348.                 musicThread.join();
  3349.             }
  3350.             if (midiDeviceID != 0) {
  3351.                 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  3352.                 midiDeviceID = 0;
  3353.             }
  3354.         }
  3355.  
  3356.         // Get the path of the executable
  3357.         TCHAR exePath[MAX_PATH];
  3358.         GetModuleFileName(NULL, exePath, MAX_PATH);
  3359.  
  3360.         // Extract the directory path
  3361.         TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  3362.         if (lastBackslash != NULL) {
  3363.             *(lastBackslash + 1) = '\0';
  3364.         }
  3365.  
  3366.         // Construct the full path to the MIDI file
  3367.         static TCHAR midiPath[MAX_PATH];
  3368.         _tcscpy_s(midiPath, MAX_PATH, exePath);
  3369.         _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  3370.  
  3371.         // Start the background playback
  3372.         isMusicPlaying = true;
  3373.         musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3374.     }*/
  3375.     //midi func = end
  3376.  
  3377.     // --- Drawing Functions ---
  3378.  
  3379.     void OnPaint() {
  3380.         HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  3381.  
  3382.         if (SUCCEEDED(hr)) {
  3383.             pRenderTarget->BeginDraw();
  3384.             DrawScene(pRenderTarget); // Pass render target
  3385.             hr = pRenderTarget->EndDraw();
  3386.  
  3387.             if (hr == D2DERR_RECREATE_TARGET) {
  3388.                 DiscardDeviceResources();
  3389.                 // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  3390.                 // But the timer loop will trigger redraw anyway.
  3391.             }
  3392.         }
  3393.         // If CreateDeviceResources failed, EndDraw might not be called.
  3394.         // Consider handling this more robustly if needed.
  3395.     }
  3396.  
  3397.     void DrawScene(ID2D1RenderTarget* pRT) {
  3398.         if (!pRT) return;
  3399.  
  3400.         //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  3401.         // Set background color to #ffffcd (RGB: 255, 255, 205)
  3402.         pRT->Clear(D2D1::ColorF(0.3686f, 0.5333f, 0.3882f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3403.         //pRT->Clear(D2D1::ColorF(1.0f, 1.0f, 0.803f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3404.  
  3405.         DrawTable(pRT, pFactory);
  3406.         DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  3407.         DrawBalls(pRT);
  3408.         DrawAimingAids(pRT); // Includes cue stick if aiming
  3409.         DrawUI(pRT);
  3410.         DrawPowerMeter(pRT);
  3411.         DrawSpinIndicator(pRT);
  3412.         DrawPocketedBallsIndicator(pRT);
  3413.         DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  3414.  
  3415.          // Draw Game Over Message
  3416.         if (currentGameState == GAME_OVER && pTextFormat) {
  3417.             ID2D1SolidColorBrush* pBrush = nullptr;
  3418.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  3419.             if (pBrush) {
  3420.                 D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  3421.                 pRT->DrawText(
  3422.                     gameOverMessage.c_str(),
  3423.                     (UINT32)gameOverMessage.length(),
  3424.                     pTextFormat, // Use large format maybe?
  3425.                     &layoutRect,
  3426.                     pBrush
  3427.                 );
  3428.                 SafeRelease(&pBrush);
  3429.             }
  3430.         }
  3431.  
  3432.     }
  3433.  
  3434.     void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  3435.         ID2D1SolidColorBrush* pBrush = nullptr;
  3436.  
  3437.         // === Draw Full Orange Frame (Table Border) ===
  3438.         ID2D1SolidColorBrush* pFrameBrush = nullptr;
  3439.         pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3440.         //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3441.         if (pFrameBrush) {
  3442.             D2D1_RECT_F outerRect = D2D1::RectF(
  3443.                 TABLE_LEFT - CUSHION_THICKNESS,
  3444.                 TABLE_TOP - CUSHION_THICKNESS,
  3445.                 TABLE_RIGHT + CUSHION_THICKNESS,
  3446.                 TABLE_BOTTOM + CUSHION_THICKNESS
  3447.             );
  3448.             pRT->FillRectangle(&outerRect, pFrameBrush);
  3449.             SafeRelease(&pFrameBrush);
  3450.         }
  3451.  
  3452.         // Draw Table Bed (Green Felt)
  3453.         pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  3454.         if (!pBrush) return;
  3455.         D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  3456.         pRT->FillRectangle(&tableRect, pBrush);
  3457.         SafeRelease(&pBrush);
  3458.  
  3459.         // ------------------------------------------------------------------
  3460. //  Spotlight overlay (soft radial inside a rounded rectangle)
  3461. // ------------------------------------------------------------------
  3462.         {
  3463.             // 2.1  Build a radial gradient brush (edge = base cloth, centre = lighter)
  3464.             ID2D1RadialGradientBrush* pSpot = nullptr;
  3465.             ID2D1GradientStopCollection* pStops = nullptr;
  3466.  
  3467.             D2D1_COLOR_F centreClr = D2D1::ColorF(
  3468.                 std::min(1.f, TABLE_COLOR.r * 1.60f),   // lighten ~60 %
  3469.                 std::min(1.f, TABLE_COLOR.g * 1.60f),
  3470.                 std::min(1.f, TABLE_COLOR.b * 1.60f));
  3471.  
  3472.             const D2D1_GRADIENT_STOP gs[3] =
  3473.             {
  3474.                 { 0.0f, D2D1::ColorF(centreClr.r, centreClr.g, centreClr.b, 0.95f) },
  3475.                 { 0.6f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.55f) },
  3476.                 { 1.0f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.0f) }
  3477.             };
  3478.             pRT->CreateGradientStopCollection(gs, 3, &pStops);
  3479.  
  3480.             if (pStops)
  3481.             {
  3482.                 D2D1_RECT_F rc = tableRect;
  3483.                 const float PAD = 18.0f;                   // inset so corners stay dark
  3484.                 rc.left += PAD;  rc.top += PAD;
  3485.                 rc.right -= PAD;  rc.bottom -= PAD;
  3486.  
  3487.                 // centre point & radii
  3488.                 D2D1_POINT_2F centre = D2D1::Point2F(
  3489.                     (rc.left + rc.right) / 2.0f,
  3490.                     (rc.top + rc.bottom) / 2.0f);
  3491.  
  3492.                 float rx = (rc.right - rc.left) * 0.55f;
  3493.                 float ry = (rc.bottom - rc.top) * 0.55f;
  3494.  
  3495.                 D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  3496.                     D2D1::RadialGradientBrushProperties(
  3497.                         centre,                       // origin
  3498.                         D2D1::Point2F(0, 0),          // offset
  3499.                         rx, ry);
  3500.  
  3501.                 pRT->CreateRadialGradientBrush(props, pStops, &pSpot);
  3502.                 pStops->Release();
  3503.             }
  3504.  
  3505.             if (pSpot)
  3506.             {
  3507.                 // Use the same rounded rectangle the pocket bar uses for subtle round corners
  3508.                 const float RADIUS = 20.0f;                       // corner radius
  3509.                 D2D1_ROUNDED_RECT spotlightRR =
  3510.                     D2D1::RoundedRect(tableRect, RADIUS, RADIUS);
  3511.  
  3512.                 pRT->FillRoundedRectangle(&spotlightRR, pSpot);
  3513.                 pSpot->Release();
  3514.             }
  3515.         }
  3516.  
  3517.         // Draw Cushions (Red Border)
  3518.         pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  3519.         if (!pBrush) return;
  3520.         // Top Cushion (split by middle pocket)
  3521.         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);
  3522.         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);
  3523.         // Bottom Cushion (split by middle pocket)
  3524.         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);
  3525.         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);
  3526.         // Left Cushion
  3527.         pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3528.         // Right Cushion
  3529.         pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3530.         SafeRelease(&pBrush);
  3531.  
  3532.  
  3533.         // Draw Pockets (Black Circles)
  3534.         pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  3535.         if (!pBrush) return;
  3536.         for (int i = 0; i < 6; ++i) {
  3537.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  3538.             pRT->FillEllipse(&ellipse, pBrush);
  3539.         }
  3540.         SafeRelease(&pBrush);
  3541.  
  3542.         // Draw Headstring Line (White)
  3543.         pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3544.         //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3545.         if (!pBrush) return;
  3546.         pRT->DrawLine(
  3547.             D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  3548.             D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  3549.             pBrush,
  3550.             1.0f // Line thickness
  3551.         );
  3552.         SafeRelease(&pBrush);
  3553.  
  3554.         // Draw Semicircle facing West (flat side East)
  3555.         // Draw Semicircle facing East (curved side on the East, flat side on the West)
  3556.         ID2D1PathGeometry* pGeometry = nullptr;
  3557.         HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  3558.         if (SUCCEEDED(hr) && pGeometry)
  3559.         {
  3560.             ID2D1GeometrySink* pSink = nullptr;
  3561.             hr = pGeometry->Open(&pSink);
  3562.             if (SUCCEEDED(hr) && pSink)
  3563.             {
  3564.                 float radius = 60.0f; // Radius for the semicircle
  3565.                 D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  3566.  
  3567.                 // For a semicircle facing East (curved side on the East), use the top and bottom points.
  3568.                 D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
  3569.  
  3570.                 pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  3571.  
  3572.                 D2D1_ARC_SEGMENT arc = {};
  3573.                 arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
  3574.                 arc.size = D2D1::SizeF(radius, radius);
  3575.                 arc.rotationAngle = 0.0f;
  3576.                 // Use the correct identifier with the extra underscore:
  3577.                 arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3578.                 arc.arcSize = D2D1_ARC_SIZE_SMALL;
  3579.  
  3580.                 pSink->AddArc(&arc);
  3581.                 pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  3582.                 pSink->Close();
  3583.                 SafeRelease(&pSink);
  3584.  
  3585.                 ID2D1SolidColorBrush* pArcBrush = nullptr;
  3586.                 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
  3587.                 pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  3588.                 if (pArcBrush)
  3589.                 {
  3590.                     pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  3591.                     SafeRelease(&pArcBrush);
  3592.                 }
  3593.             }
  3594.             SafeRelease(&pGeometry);
  3595.         }
  3596.  
  3597.  
  3598.  
  3599.  
  3600.     }
  3601.  
  3602.  
  3603.     // ----------------------------------------------
  3604.     //  Helper : clamp to [0,1] and lighten a colour
  3605.     // ----------------------------------------------
  3606.     static D2D1_COLOR_F Lighten(const D2D1_COLOR_F& c, float factor = 1.25f)
  3607.     {
  3608.         return D2D1::ColorF(
  3609.             std::min(1.0f, c.r * factor),
  3610.             std::min(1.0f, c.g * factor),
  3611.             std::min(1.0f, c.b * factor),
  3612.             c.a);
  3613.     }
  3614.  
  3615.     // ------------------------------------------------
  3616.     //  NEW  DrawBalls – radial-gradient “spot-light”
  3617.     // ------------------------------------------------
  3618.     void DrawBalls(ID2D1RenderTarget* pRT)
  3619.     {
  3620.         if (!pRT) return;
  3621.  
  3622.         ID2D1SolidColorBrush* pStripeBrush = nullptr;    // white stripe
  3623.         ID2D1SolidColorBrush* pBorderBrush = nullptr;    // black ring
  3624.         ID2D1SolidColorBrush * pNumWhite = nullptr; // NEW – white circle
  3625.         ID2D1SolidColorBrush * pNumBlack = nullptr; // NEW – digit colour
  3626.  
  3627.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3628.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3629.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  3630.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  3631.  
  3632.         for (const Ball& b : balls)
  3633.         {
  3634.             if (b.isPocketed) continue;
  3635.  
  3636.             //------------------------------------------
  3637.             // Build the radial gradient for THIS ball
  3638.             //------------------------------------------
  3639.             ID2D1GradientStopCollection* pStops = nullptr;
  3640.             ID2D1RadialGradientBrush* pRad = nullptr;
  3641.  
  3642.             D2D1_GRADIENT_STOP gs[3];
  3643.             gs[0].position = 0.0f;  gs[0].color = D2D1::ColorF(1, 1, 1, 0.95f);     // bright spot
  3644.             gs[1].position = 0.35f; gs[1].color = Lighten(b.color);                 // transitional
  3645.             gs[2].position = 1.0f;  gs[2].color = b.color;                          // base colour
  3646.  
  3647.             pRT->CreateGradientStopCollection(gs, 3, &pStops);
  3648.  
  3649.             if (pStops)
  3650.             {
  3651.                 // Place the hot-spot slightly towards top-left to look more 3-D
  3652.                 D2D1_POINT_2F origin = D2D1::Point2F(b.x - BALL_RADIUS * 0.4f,
  3653.                     b.y - BALL_RADIUS * 0.4f);
  3654.  
  3655.                 D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  3656.                     D2D1::RadialGradientBrushProperties(
  3657.                         origin,                        // gradientOrigin
  3658.                         D2D1::Point2F(0, 0),           // offset (not used here)
  3659.                         BALL_RADIUS * 1.3f,            // radiusX
  3660.                         BALL_RADIUS * 1.3f);           // radiusY
  3661.  
  3662.                 pRT->CreateRadialGradientBrush(props, pStops, &pRad);
  3663.                 SafeRelease(&pStops);
  3664.             }
  3665.  
  3666.             //------------------------------------------
  3667.             //  Draw the solid or striped ball itself
  3668.             //------------------------------------------
  3669.             D2D1_ELLIPSE outer = D2D1::Ellipse(
  3670.                 D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3671.  
  3672.             if (pRad)  pRT->FillEllipse(&outer, pRad);
  3673.  
  3674.             // ----------  Stripe overlay  -------------
  3675.             if (b.type == BallType::STRIPE && pStripeBrush)
  3676.             {
  3677.                 // White band
  3678.                 D2D1_RECT_F stripe = D2D1::RectF(
  3679.                     b.x - BALL_RADIUS,
  3680.                     b.y - BALL_RADIUS * 0.40f,
  3681.                     b.x + BALL_RADIUS,
  3682.                     b.y + BALL_RADIUS * 0.40f);
  3683.                 pRT->FillRectangle(&stripe, pStripeBrush);
  3684.  
  3685.                 // Inner circle (give stripe area same glossy shading)
  3686.                 if (pRad)
  3687.                 {
  3688.                     D2D1_ELLIPSE inner = D2D1::Ellipse(
  3689.                         D2D1::Point2F(b.x, b.y),
  3690.                         BALL_RADIUS * 0.60f,
  3691.                         BALL_RADIUS * 0.60f);
  3692.                     pRT->FillEllipse(&inner, pRad);
  3693.                 }
  3694.             }
  3695.  
  3696.             // --------------------------------------------------------
  3697. //  Draw number decal (skip cue ball)
  3698. // --------------------------------------------------------
  3699.             if (b.id != 0 && pBallNumFormat && pNumWhite && pNumBlack)
  3700.             {
  3701.                 // 1) white circle – slightly smaller on stripes so it fits
  3702.                 const float decalR = (b.type == BallType::STRIPE) ?
  3703.                     BALL_RADIUS * 0.40f : BALL_RADIUS * 0.45f;
  3704.  
  3705.                 D2D1_ELLIPSE decal = D2D1::Ellipse(
  3706.                     D2D1::Point2F(b.x, b.y), decalR, decalR);
  3707.  
  3708.                 pRT->FillEllipse(&decal, pNumWhite);
  3709.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);   // thin border
  3710.  
  3711.                 // 2) digit – convert id to printable number
  3712.                 wchar_t numText[3];
  3713.                 _snwprintf_s(numText, _TRUNCATE, L"%d", b.id);
  3714.  
  3715.                 // layout rectangle exactly the diameter of the decal
  3716.                 D2D1_RECT_F layout = D2D1::RectF(
  3717.                     b.x - decalR, b.y - decalR,
  3718.                     b.x + decalR, b.y + decalR);
  3719.  
  3720.                 pRT->DrawText(numText,
  3721.                     (UINT32)wcslen(numText),
  3722.                     pBallNumFormat,
  3723.                     &layout,
  3724.                     pNumBlack);
  3725.             }
  3726.  
  3727.             // Black border
  3728.             if (pBorderBrush)
  3729.                 pRT->DrawEllipse(&outer, pBorderBrush, 1.5f);
  3730.  
  3731.             SafeRelease(&pRad);
  3732.         }
  3733.  
  3734.         SafeRelease(&pStripeBrush);
  3735.         SafeRelease(&pBorderBrush);
  3736.         SafeRelease(&pNumWhite);   // NEW
  3737.         SafeRelease(&pNumBlack);   // NEW
  3738.     }
  3739.  
  3740.     /*void DrawBalls(ID2D1RenderTarget* pRT) {
  3741.         ID2D1SolidColorBrush* pBrush = nullptr;
  3742.         ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  3743.  
  3744.         pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  3745.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3746.  
  3747.         if (!pBrush || !pStripeBrush) {
  3748.             SafeRelease(&pBrush);
  3749.             SafeRelease(&pStripeBrush);
  3750.             return;
  3751.         }
  3752.  
  3753.  
  3754.         for (size_t i = 0; i < balls.size(); ++i) {
  3755.             const Ball& b = balls[i];
  3756.             if (!b.isPocketed) {
  3757.                 D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3758.  
  3759.                 // Set main ball color
  3760.                 pBrush->SetColor(b.color);
  3761.                 pRT->FillEllipse(&ellipse, pBrush);
  3762.  
  3763.                 // Draw Stripe if applicable
  3764.                 if (b.type == BallType::STRIPE) {
  3765.                     // Draw a white band across the middle (simplified stripe)
  3766.                     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);
  3767.                     // Need to clip this rectangle to the ellipse bounds - complex!
  3768.                     // Alternative: Draw two colored arcs leaving a white band.
  3769.                     // Simplest: Draw a white circle inside, slightly smaller.
  3770.                     D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  3771.                     pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  3772.                     pBrush->SetColor(b.color); // Set back to stripe color
  3773.                     pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  3774.  
  3775.                     // Let's try drawing a thick white line across
  3776.                     // This doesn't look great. Just drawing solid red for stripes for now.
  3777.                 }
  3778.  
  3779.                 // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  3780.                 // if (b.id != 0 && pTextFormat) {
  3781.                 //     std::wstring numStr = std::to_wstring(b.id);
  3782.                 //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  3783.                 //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  3784.                 //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  3785.                 //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  3786.                 //     // Create a smaller text format...
  3787.                 //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  3788.                 //     SafeRelease(&pNumBrush);
  3789.                 // }
  3790.             }
  3791.         }
  3792.  
  3793.         SafeRelease(&pBrush);
  3794.         SafeRelease(&pStripeBrush);
  3795.     }*/
  3796.  
  3797.  
  3798.     /*void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3799.         // Condition check at start (Unchanged)
  3800.         //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  3801.             //currentGameState != BREAKING && currentGameState != AIMING)
  3802.         //{
  3803.             //return;
  3804.         //}
  3805.             // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  3806.         // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  3807.         bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3808.             (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3809.                 currentGameState == BREAKING || currentGameState == AIMING);
  3810.         // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  3811.         // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  3812.             // NEW Condition: AI is displaying its aim
  3813.         bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  3814.             currentGameState == AI_THINKING && aiIsDisplayingAim);
  3815.  
  3816.         if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  3817.             return;
  3818.         }
  3819.  
  3820.         Ball* cueBall = GetCueBall();
  3821.         if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  3822.  
  3823.         ID2D1SolidColorBrush* pBrush = nullptr;
  3824.         ID2D1SolidColorBrush* pGhostBrush = nullptr;
  3825.         ID2D1StrokeStyle* pDashedStyle = nullptr;
  3826.         ID2D1SolidColorBrush* pCueBrush = nullptr;
  3827.         ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  3828.  
  3829.         // Ensure render target is valid
  3830.         if (!pRT) return;
  3831.  
  3832.         // Create Brushes and Styles (check for failures)
  3833.         HRESULT hr;
  3834.         hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  3835.         if FAILED(hr) { SafeRelease(&pBrush); return; }
  3836.         hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  3837.         if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  3838.         hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  3839.         if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  3840.         // Create reflection brush (e.g., lighter shade or different color)
  3841.         hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  3842.         if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  3843.         // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  3844.         D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  3845.         ID2D1SolidColorBrush* pCyanBrush = nullptr;
  3846.         hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  3847.         if (FAILED(hr)) {
  3848.             SafeRelease(&pCyanBrush);
  3849.             // handle error if needed
  3850.         }
  3851.         // Create a Purple brush for primary and secondary lines
  3852.         D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  3853.         ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  3854.         hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  3855.         if (FAILED(hr)) {
  3856.             SafeRelease(&pPurpleBrush);
  3857.             // handle error if needed
  3858.         }
  3859.  
  3860.         if (pFactory) {
  3861.             D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  3862.             strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  3863.             hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  3864.             if FAILED(hr) { pDashedStyle = nullptr; }
  3865.         }
  3866.  
  3867.  
  3868.         // --- Cue Stick Drawing (Unchanged from previous fix) ---
  3869.         const float baseStickLength = 150.0f;
  3870.         const float baseStickThickness = 4.0f;
  3871.         float stickLength = baseStickLength * 1.4f;
  3872.         float stickThickness = baseStickThickness * 1.5f;
  3873.         float stickAngle = cueAngle + PI;
  3874.         float powerOffset = 0.0f;
  3875.         //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  3876.             // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  3877.         if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  3878.             powerOffset = shotPower * 5.0f;
  3879.         }
  3880.         D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  3881.         D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  3882.         pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  3883.  
  3884.  
  3885.         // --- Projection Line Calculation ---
  3886.         float cosA = cosf(cueAngle);
  3887.         float sinA = sinf(cueAngle);
  3888.         float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  3889.         D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  3890.         D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);*/
  3891.  
  3892.     void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3893.         // Determine if aiming aids should be drawn.
  3894.         bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3895.             (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3896.                 currentGameState == BREAKING || currentGameState == AIMING ||
  3897.                 currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2);
  3898.  
  3899.         // FOOLPROOF FIX: This is the new condition to show the AI's aim.
  3900.         bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 && aiIsDisplayingAim);
  3901.  
  3902.         if (!isHumanInteracting && !isAiVisualizingShot) {
  3903.             return;
  3904.         }
  3905.  
  3906.         Ball* cueBall = GetCueBall();
  3907.         if (!cueBall || cueBall->isPocketed) return;
  3908.  
  3909.         // --- Brush and Style Creation (No changes here) ---
  3910.         ID2D1SolidColorBrush* pBrush = nullptr;
  3911.         ID2D1SolidColorBrush* pGhostBrush = nullptr;
  3912.         ID2D1StrokeStyle* pDashedStyle = nullptr;
  3913.         ID2D1SolidColorBrush* pCueBrush = nullptr;
  3914.         ID2D1SolidColorBrush* pReflectBrush = nullptr;
  3915.         ID2D1SolidColorBrush* pCyanBrush = nullptr;
  3916.         ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  3917.         pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  3918.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  3919.         pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  3920.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  3921.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Cyan), &pCyanBrush);
  3922.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Purple), &pPurpleBrush);
  3923.         if (pFactory) {
  3924.             D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  3925.             strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  3926.             pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  3927.         }
  3928.         // --- End Brush Creation ---
  3929.  
  3930.         // --- FOOLPROOF FIX: Use the AI's planned angle and power for drawing ---
  3931.         float angleToDraw = cueAngle;
  3932.         float powerToDraw = shotPower;
  3933.  
  3934.         if (isAiVisualizingShot) {
  3935.             // When the AI is showing its aim, force the drawing to use its planned shot details.
  3936.             angleToDraw = aiPlannedShotDetails.angle;
  3937.             powerToDraw = aiPlannedShotDetails.power;
  3938.         }
  3939.         // --- End AI Aiming Fix ---
  3940.  
  3941.         // --- Cue Stick Drawing ---
  3942.         const float baseStickLength = 150.0f;
  3943.         const float baseStickThickness = 4.0f;
  3944.         float stickLength = baseStickLength * 1.4f;
  3945.         float stickThickness = baseStickThickness * 1.5f;
  3946.         float stickAngle = angleToDraw + PI; // Use the angle we determined
  3947.         float powerOffset = 0.0f;
  3948.         if ((isAiming || isDraggingStick) || isAiVisualizingShot) {
  3949.             powerOffset = powerToDraw * 5.0f; // Use the power we determined
  3950.         }
  3951.         D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  3952.         D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  3953.         pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  3954.  
  3955.         // --- Projection Line Calculation ---
  3956.         float cosA = cosf(angleToDraw); // Use the angle we determined
  3957.         float sinA = sinf(angleToDraw);
  3958.         float rayLength = TABLE_WIDTH + TABLE_HEIGHT;
  3959.         D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  3960.         D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  3961.  
  3962.         // Find the first ball hit by the aiming ray
  3963.         Ball* hitBall = nullptr;
  3964.         float firstHitDistSq = -1.0f;
  3965.         D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  3966.         D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  3967.  
  3968.         hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  3969.         if (hitBall) {
  3970.             // Calculate the point on the target ball's circumference
  3971.             float collisionDist = sqrtf(firstHitDistSq);
  3972.             ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  3973.             // Calculate ghost ball position for this specific hit (used for projection consistency)
  3974.             ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  3975.         }
  3976.  
  3977.         // Find the first rail hit by the aiming ray
  3978.         D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  3979.         float minRailDistSq = rayLength * rayLength;
  3980.         int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  3981.  
  3982.         // Define table edge segments for intersection checks
  3983.         D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  3984.         D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  3985.         D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  3986.         D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  3987.  
  3988.         D2D1_POINT_2F currentIntersection;
  3989.  
  3990.         // Check Left Rail
  3991.         if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  3992.             float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3993.             if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  3994.         }
  3995.         // Check Right Rail
  3996.         if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  3997.             float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3998.             if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  3999.         }
  4000.         // Check Top Rail
  4001.         if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  4002.             float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4003.             if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  4004.         }
  4005.         // Check Bottom Rail
  4006.         if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  4007.             float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  4008.             if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  4009.         }
  4010.  
  4011.  
  4012.         // --- Determine final aim line end point ---
  4013.         D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  4014.         bool aimingAtRail = true;
  4015.  
  4016.         if (hitBall && firstHitDistSq < minRailDistSq) {
  4017.             // Ball collision is closer than rail collision
  4018.             finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  4019.             aimingAtRail = false;
  4020.         }
  4021.  
  4022.         // --- Draw Primary Aiming Line ---
  4023.         pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4024.  
  4025.         // --- Draw Target Circle/Indicator ---
  4026.         D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  4027.         pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  4028.  
  4029.         // --- Draw Projection/Reflection Lines ---
  4030.         if (!aimingAtRail && hitBall) {
  4031.             // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  4032.             D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  4033.             pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4034.  
  4035.             // Calculate target ball projection based on impact line (cue collision point -> target center)
  4036.             float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  4037.             // Clamp angle calculation if distance is tiny
  4038.             if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  4039.                 targetProjectionAngle = cueAngle; // Fallback if overlapping
  4040.             }
  4041.  
  4042.             D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  4043.             D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  4044.                 hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  4045.                 hitBall->y + sinf(targetProjectionAngle) * 50.0f
  4046.             );
  4047.             // Draw solid line for target projection
  4048.             //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  4049.  
  4050.         //new code start
  4051.  
  4052.                     // Dual trajectory with edge-aware contact simulation
  4053.             D2D1_POINT_2F dir = {
  4054.                 targetProjectionEnd.x - targetStartPoint.x,
  4055.                 targetProjectionEnd.y - targetStartPoint.y
  4056.             };
  4057.             float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  4058.             dir.x /= dirLen;
  4059.             dir.y /= dirLen;
  4060.  
  4061.             D2D1_POINT_2F perp = { -dir.y, dir.x };
  4062.  
  4063.             // Approximate cue ball center by reversing from tip
  4064.             D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  4065.                 targetStartPoint.x - dir.x * BALL_RADIUS,
  4066.                 targetStartPoint.y - dir.y * BALL_RADIUS
  4067.             };
  4068.  
  4069.             // REAL contact-ball center - use your physics object's center:
  4070.             // (replace 'objectBallPos' with whatever you actually call it)
  4071.             // (targetStartPoint is already hitBall->x, hitBall->y)
  4072.             D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  4073.             //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  4074.  
  4075.            // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  4076.            // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  4077.            // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  4078.            // and 'perp' is perpendicular to 'dir'.
  4079.            // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  4080.             /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  4081.                 (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  4082.                 /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  4083.                     (targetStartPoint.y - cueBallCenter.y) * perp.y);
  4084.                 float absOffset = fabsf(offset);
  4085.                 float side = (offset >= 0 ? 1.0f : -1.0f);*/
  4086.  
  4087.                 // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  4088.             D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  4089.  
  4090.             // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  4091.             float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  4092.                 (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  4093.             float absOffset = fabsf(offset);
  4094.             float side = (offset >= 0 ? 1.0f : -1.0f);
  4095.  
  4096.  
  4097.             // Actual contact point on target ball edge
  4098.             D2D1_POINT_2F contactPoint = {
  4099.             contactBallCenter.x + perp.x * BALL_RADIUS * side,
  4100.             contactBallCenter.y + perp.y * BALL_RADIUS * side
  4101.             };
  4102.  
  4103.             // Tangent (cut shot) path from contact point
  4104.                 // Tangent (cut shot) path: from contact point to contact ball center
  4105.             D2D1_POINT_2F objectBallDir = {
  4106.                 contactBallCenter.x - contactPoint.x,
  4107.                 contactBallCenter.y - contactPoint.y
  4108.             };
  4109.             float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  4110.             if (oLen != 0.0f) {
  4111.                 objectBallDir.x /= oLen;
  4112.                 objectBallDir.y /= oLen;
  4113.             }
  4114.  
  4115.             const float PRIMARY_LEN = 150.0f; //default=150.0f
  4116.             const float SECONDARY_LEN = 150.0f; //default=150.0f
  4117.             const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  4118.  
  4119.             D2D1_POINT_2F primaryEnd = {
  4120.                 targetStartPoint.x + dir.x * PRIMARY_LEN,
  4121.                 targetStartPoint.y + dir.y * PRIMARY_LEN
  4122.             };
  4123.  
  4124.             // Secondary line starts from the contact ball's center
  4125.             D2D1_POINT_2F secondaryStart = contactBallCenter;
  4126.             D2D1_POINT_2F secondaryEnd = {
  4127.                 secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  4128.                 secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  4129.             };
  4130.  
  4131.             if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  4132.             {
  4133.                 // Straight: secondary behind primary
  4134.                         // secondary behind primary {pDashedStyle param at end}
  4135.                 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  4136.                 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  4137.                 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  4138.                 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  4139.             }
  4140.             else
  4141.             {
  4142.                 // Cut shot: both visible
  4143.                         // both visible for cut shot
  4144.                 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  4145.                 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  4146.                 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  4147.                 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  4148.             }
  4149.             // End improved trajectory logic
  4150.  
  4151.         //new code end
  4152.  
  4153.             // -- Cue Ball Path after collision (Optional, requires physics) --
  4154.             // Very simplified: Assume cue deflects, angle depends on cut angle.
  4155.             // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  4156.             // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  4157.             // D2D1_POINT_2F cueProjectionEnd = ...
  4158.             // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4159.  
  4160.             // --- Accuracy Comment ---
  4161.             // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  4162.             // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  4163.             // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  4164.             // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  4165.  
  4166.         }
  4167.         else if (aimingAtRail && hitRailIndex != -1) {
  4168.             // Aiming at a rail: Draw reflection line
  4169.             float reflectAngle = cueAngle;
  4170.             // Reflect angle based on which rail was hit
  4171.             if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  4172.                 reflectAngle = PI - cueAngle; // Reflect horizontal component
  4173.             }
  4174.             else { // Top or Bottom rail
  4175.                 reflectAngle = -cueAngle; // Reflect vertical component
  4176.             }
  4177.             // Normalize angle if needed (atan2 usually handles this)
  4178.             while (reflectAngle > PI) reflectAngle -= 2 * PI;
  4179.             while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  4180.  
  4181.  
  4182.             float reflectionLength = 60.0f; // Length of the reflection line
  4183.             D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  4184.                 finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  4185.                 finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  4186.             );
  4187.  
  4188.             // Draw the reflection line (e.g., using a different color/style)
  4189.             pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  4190.         }
  4191.  
  4192.         // Release resources
  4193.         SafeRelease(&pBrush);
  4194.         SafeRelease(&pGhostBrush);
  4195.         SafeRelease(&pCueBrush);
  4196.         SafeRelease(&pReflectBrush); // Release new brush
  4197.         SafeRelease(&pCyanBrush);
  4198.         SafeRelease(&pPurpleBrush);
  4199.         SafeRelease(&pDashedStyle);
  4200.     }
  4201.  
  4202.  
  4203.     void DrawUI(ID2D1RenderTarget* pRT) {
  4204.         if (!pTextFormat || !pLargeTextFormat) return;
  4205.  
  4206.         ID2D1SolidColorBrush* pBrush = nullptr;
  4207.         pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  4208.         if (!pBrush) return;
  4209.  
  4210.         //new code
  4211.         // --- Always draw AI's 8?Ball call arrow when it's Player?2's turn and AI has called ---
  4212.         //if (isPlayer2AI && currentPlayer == 2 && calledPocketP2 >= 0) {
  4213.             // FIX: This condition correctly shows the AI's called pocket arrow.
  4214.         if (isPlayer2AI && IsPlayerOnEightBall(2) && calledPocketP2 >= 0) {
  4215.             // pocket index that AI called
  4216.             int idx = calledPocketP2;
  4217.             // draw large blue arrow
  4218.             ID2D1SolidColorBrush* pArrow = nullptr;
  4219.             pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4220.             if (pArrow) {
  4221.                 auto P = pocketPositions[idx];
  4222.                 D2D1_POINT_2F tri[3] = {
  4223.                     { P.x - 15.0f, P.y - 40.0f },
  4224.                     { P.x + 15.0f, P.y - 40.0f },
  4225.                     { P.x       , P.y - 10.0f }
  4226.                 };
  4227.                 ID2D1PathGeometry* geom = nullptr;
  4228.                 pFactory->CreatePathGeometry(&geom);
  4229.                 ID2D1GeometrySink* sink = nullptr;
  4230.                 geom->Open(&sink);
  4231.                 sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4232.                 sink->AddLines(&tri[1], 2);
  4233.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4234.                 sink->Close();
  4235.                 pRT->FillGeometry(geom, pArrow);
  4236.                 SafeRelease(&sink);
  4237.                 SafeRelease(&geom);
  4238.                 SafeRelease(&pArrow);
  4239.             }
  4240.             // draw “Choose a pocket...” prompt
  4241.             D2D1_RECT_F txt = D2D1::RectF(
  4242.                 TABLE_LEFT,
  4243.                 TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4244.                 TABLE_RIGHT,
  4245.                 TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4246.             );
  4247.             pRT->DrawText(
  4248.                 L"AI has called this pocket",
  4249.                 (UINT32)wcslen(L"AI has called this pocket"),
  4250.                 pTextFormat,
  4251.                 &txt,
  4252.                 pBrush
  4253.             );
  4254.             // note: no return here — we still draw fouls/turn text underneath
  4255.         }
  4256.         //end new code
  4257.  
  4258.         // --- Player Info Area (Top Left/Right) --- (Unchanged)
  4259.         float uiTop = TABLE_TOP - 80;
  4260.         float uiHeight = 60;
  4261.         float p1Left = TABLE_LEFT;
  4262.         float p1Width = 150;
  4263.         float p2Left = TABLE_RIGHT - p1Width;
  4264.         D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  4265.         D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  4266.  
  4267.         // Player 1 Info Text (Unchanged)
  4268.         std::wostringstream oss1;
  4269.         oss1 << player1Info.name.c_str() << L"\n";
  4270.         if (player1Info.assignedType != BallType::NONE) {
  4271.             oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  4272.             oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  4273.         }
  4274.         else {
  4275.             oss1 << L"(Undecided)";
  4276.         }
  4277.         pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  4278.         // Draw Player 1 Side Ball
  4279.         if (player1Info.assignedType != BallType::NONE)
  4280.         {
  4281.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  4282.             D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  4283.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  4284.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  4285.             if (pBallBrush)
  4286.             {
  4287.                 D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
  4288.                 float radius = 10.0f;
  4289.                 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  4290.                 pRT->FillEllipse(&ball, pBallBrush);
  4291.                 SafeRelease(&pBallBrush);
  4292.                 // Draw border around the ball
  4293.                 ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4294.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4295.                 if (pBorderBrush)
  4296.                 {
  4297.                     pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  4298.                     SafeRelease(&pBorderBrush);
  4299.                 }
  4300.  
  4301.                 // If stripes, draw a stripe band
  4302.                 if (player1Info.assignedType == BallType::STRIPE)
  4303.                 {
  4304.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  4305.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  4306.                     if (pStripeBrush)
  4307.                     {
  4308.                         D2D1_RECT_F stripeRect = D2D1::RectF(
  4309.                             ballCenter.x - radius,
  4310.                             ballCenter.y - 3.0f,
  4311.                             ballCenter.x + radius,
  4312.                             ballCenter.y + 3.0f
  4313.                         );
  4314.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  4315.                         SafeRelease(&pStripeBrush);
  4316.                     }
  4317.                 }
  4318.             }
  4319.         }
  4320.  
  4321.  
  4322.         // Player 2 Info Text (Unchanged)
  4323.         std::wostringstream oss2;
  4324.         oss2 << player2Info.name.c_str() << L"\n";
  4325.         if (player2Info.assignedType != BallType::NONE) {
  4326.             oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  4327.             oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  4328.         }
  4329.         else {
  4330.             oss2 << L"(Undecided)";
  4331.         }
  4332.         pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  4333.         // Draw Player 2 Side Ball
  4334.         if (player2Info.assignedType != BallType::NONE)
  4335.         {
  4336.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  4337.             D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  4338.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  4339.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  4340.             if (pBallBrush)
  4341.             {
  4342.                 D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
  4343.                 float radius = 10.0f;
  4344.                 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  4345.                 pRT->FillEllipse(&ball, pBallBrush);
  4346.                 SafeRelease(&pBallBrush);
  4347.                 // Draw border around the ball
  4348.                 ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4349.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4350.                 if (pBorderBrush)
  4351.                 {
  4352.                     pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  4353.                     SafeRelease(&pBorderBrush);
  4354.                 }
  4355.  
  4356.                 // If stripes, draw a stripe band
  4357.                 if (player2Info.assignedType == BallType::STRIPE)
  4358.                 {
  4359.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  4360.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  4361.                     if (pStripeBrush)
  4362.                     {
  4363.                         D2D1_RECT_F stripeRect = D2D1::RectF(
  4364.                             ballCenter.x - radius,
  4365.                             ballCenter.y - 3.0f,
  4366.                             ballCenter.x + radius,
  4367.                             ballCenter.y + 3.0f
  4368.                         );
  4369.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  4370.                         SafeRelease(&pStripeBrush);
  4371.                     }
  4372.                 }
  4373.             }
  4374.         }
  4375.  
  4376.         // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  4377.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4378.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4379.         if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  4380.             float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  4381.             float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  4382.             float arrowTipX, arrowBackX;
  4383.  
  4384.             D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  4385.             arrowBackX = playerBox.left - 25.0f;
  4386.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  4387.  
  4388.             float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  4389.             float notchWidth = 10.0f;
  4390.  
  4391.             float cx = arrowBackX;
  4392.             float cy = arrowCenterY;
  4393.  
  4394.             // Define triangle + rectangle tail shape
  4395.             D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  4396.             D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  4397.             D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  4398.  
  4399.             // Rectangle coordinates for the tail portion:
  4400.             D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  4401.             D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  4402.             D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  4403.             D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  4404.  
  4405.             ID2D1PathGeometry* pPath = nullptr;
  4406.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4407.                 ID2D1GeometrySink* pSink = nullptr;
  4408.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  4409.                     pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  4410.                     pSink->AddLine(baseTop);
  4411.                     pSink->AddLine(r2); // transition from triangle into rectangle
  4412.                     pSink->AddLine(r1);
  4413.                     pSink->AddLine(r4);
  4414.                     pSink->AddLine(r3);
  4415.                     pSink->AddLine(baseBot);
  4416.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4417.                     pSink->Close();
  4418.                     SafeRelease(&pSink);
  4419.                     pRT->FillGeometry(pPath, pArrowBrush);
  4420.                 }
  4421.                 SafeRelease(&pPath);
  4422.             }
  4423.  
  4424.  
  4425.             SafeRelease(&pArrowBrush);
  4426.         }
  4427.  
  4428.         //original
  4429.     /*
  4430.         // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  4431.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4432.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4433.         if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  4434.             float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  4435.             float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  4436.             float arrowTipX, arrowBackX;
  4437.  
  4438.             if (currentPlayer == 1) {
  4439.     arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  4440.                 arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  4441.                 // Define points for right-pointing arrow
  4442.                 //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4443.                 //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4444.                 //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4445.                 // Enhanced arrow with base rectangle intersection
  4446.         float notchDepth = 6.0f; // Depth of square base "stem"
  4447.         float notchWidth = 4.0f; // Thickness of square part
  4448.  
  4449.         D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4450.         D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4451.         D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  4452.         D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  4453.         D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4454.  
  4455.  
  4456.         ID2D1PathGeometry* pPath = nullptr;
  4457.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4458.             ID2D1GeometrySink* pSink = nullptr;
  4459.             if (SUCCEEDED(pPath->Open(&pSink))) {
  4460.                 pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  4461.                 pSink->AddLine(pt2);
  4462.                 pSink->AddLine(pt3);
  4463.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4464.                 pSink->Close();
  4465.                 SafeRelease(&pSink);
  4466.                 pRT->FillGeometry(pPath, pArrowBrush);
  4467.             }
  4468.             SafeRelease(&pPath);
  4469.         }
  4470.             }
  4471.  
  4472.  
  4473.             //==================else player 2
  4474.             else { // Player 2
  4475.              // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  4476.              // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  4477.     // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  4478.     arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  4479.     arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  4480.     // Define points for right-pointing arrow
  4481.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  4482.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  4483.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  4484.  
  4485.     ID2D1PathGeometry* pPath = nullptr;
  4486.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4487.         ID2D1GeometrySink* pSink = nullptr;
  4488.         if (SUCCEEDED(pPath->Open(&pSink))) {
  4489.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  4490.             pSink->AddLine(pt2);
  4491.             pSink->AddLine(pt3);
  4492.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4493.             pSink->Close();
  4494.             SafeRelease(&pSink);
  4495.             pRT->FillGeometry(pPath, pArrowBrush);
  4496.         }
  4497.         SafeRelease(&pPath);
  4498.     }
  4499.             }
  4500.             */
  4501.  
  4502.  
  4503.             // --- Persistent Blue 8?Ball Call Arrow & Prompt ---
  4504.         /*if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  4505.         {
  4506.             // determine index (default top?right)
  4507.             int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4508.             if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  4509.             if (idx < 0) idx = 2;
  4510.  
  4511.             // draw large blue arrow
  4512.             ID2D1SolidColorBrush* pArrow = nullptr;
  4513.             pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4514.             if (pArrow) {
  4515.                 auto P = pocketPositions[idx];
  4516.                 D2D1_POINT_2F tri[3] = {
  4517.                     {P.x - 15.0f, P.y - 40.0f},
  4518.                     {P.x + 15.0f, P.y - 40.0f},
  4519.                     {P.x       , P.y - 10.0f}
  4520.                 };
  4521.                 ID2D1PathGeometry* geom = nullptr;
  4522.                 pFactory->CreatePathGeometry(&geom);
  4523.                 ID2D1GeometrySink* sink = nullptr;
  4524.                 geom->Open(&sink);
  4525.                 sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4526.                 sink->AddLines(&tri[1], 2);
  4527.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4528.                 sink->Close();
  4529.                 pRT->FillGeometry(geom, pArrow);
  4530.                 SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  4531.             }
  4532.  
  4533.             // draw prompt
  4534.             D2D1_RECT_F txt = D2D1::RectF(
  4535.                 TABLE_LEFT,
  4536.                 TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4537.                 TABLE_RIGHT,
  4538.                 TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4539.             );
  4540.             pRT->DrawText(
  4541.                 L"Choose a pocket...",
  4542.                 (UINT32)wcslen(L"Choose a pocket..."),
  4543.                 pTextFormat,
  4544.                 &txt,
  4545.                 pBrush
  4546.             );
  4547.         }*/
  4548.  
  4549.         // --- Persistent Blue 8?Ball Pocket Arrow & Prompt (once called) ---
  4550.     /* if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  4551.     {
  4552.         // 1) Determine pocket index
  4553.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4554.         // If the other player had called but it's now your turn, still show that call
  4555.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  4556.         if (idx < 0) idx = 2; // default to top?right if somehow still unset
  4557.  
  4558.         // 2) Draw large blue arrow
  4559.         ID2D1SolidColorBrush* pArrow = nullptr;
  4560.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4561.         if (pArrow) {
  4562.             auto P = pocketPositions[idx];
  4563.             D2D1_POINT_2F tri[3] = {
  4564.                 { P.x - 15.0f, P.y - 40.0f },
  4565.                 { P.x + 15.0f, P.y - 40.0f },
  4566.                 { P.x       , P.y - 10.0f }
  4567.             };
  4568.             ID2D1PathGeometry* geom = nullptr;
  4569.             pFactory->CreatePathGeometry(&geom);
  4570.             ID2D1GeometrySink* sink = nullptr;
  4571.             geom->Open(&sink);
  4572.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4573.             sink->AddLines(&tri[1], 2);
  4574.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4575.             sink->Close();
  4576.             pRT->FillGeometry(geom, pArrow);
  4577.             SafeRelease(&sink);
  4578.             SafeRelease(&geom);
  4579.             SafeRelease(&pArrow);
  4580.         }
  4581.  
  4582.         // 3) Draw persistent prompt text
  4583.         D2D1_RECT_F txt = D2D1::RectF(
  4584.             TABLE_LEFT,
  4585.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4586.             TABLE_RIGHT,
  4587.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4588.         );
  4589.         pRT->DrawText(
  4590.             L"Choose a pocket...",
  4591.             (UINT32)wcslen(L"Choose a pocket..."),
  4592.             pTextFormat,
  4593.             &txt,
  4594.             pBrush
  4595.         );
  4596.         // Note: no 'return'; allow foul/turn text to draw beneath if needed
  4597.     } */
  4598.  
  4599.     // new code ends here
  4600.  
  4601.         // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  4602.         if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  4603.             ID2D1SolidColorBrush* pFoulBrush = nullptr;
  4604.             pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  4605.             if (pFoulBrush && pLargeTextFormat) {
  4606.                 // Calculate Rect for bottom-middle area
  4607.                 float foulWidth = 200.0f; // Adjust width as needed
  4608.                 float foulHeight = 60.0f;
  4609.                 float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  4610.                 // Position below the pocketed balls bar
  4611.                 float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  4612.                 D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  4613.  
  4614.                 // --- Set text alignment to center for foul text ---
  4615.                 pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4616.                 pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4617.  
  4618.                 pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  4619.  
  4620.                 // --- Restore default alignment for large text if needed elsewhere ---
  4621.                 // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  4622.                 // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4623.  
  4624.                 SafeRelease(&pFoulBrush);
  4625.             }
  4626.         }
  4627.  
  4628.         // --- Blue Arrow & Prompt for 8?Ball Call (while choosing or after called) ---
  4629.         if ((currentGameState == CHOOSING_POCKET_P1
  4630.             || currentGameState == CHOOSING_POCKET_P2)
  4631.             || (calledPocketP1 >= 0 || calledPocketP2 >= 0))
  4632.         {
  4633.             // determine index:
  4634.             //  - if a call exists, use it
  4635.             //  - if still choosing, use hover if any
  4636.             // determine index: use only the clicked call; default to top?right if unset
  4637.             int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  4638.             if (idx < 0) idx = 2;
  4639.  
  4640.             // draw large blue arrow
  4641.             ID2D1SolidColorBrush* pArrow = nullptr;
  4642.             pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4643.             if (pArrow) {
  4644.                 auto P = pocketPositions[idx];
  4645.                 D2D1_POINT_2F tri[3] = {
  4646.                     {P.x - 15.0f, P.y - 40.0f},
  4647.                     {P.x + 15.0f, P.y - 40.0f},
  4648.                     {P.x       , P.y - 10.0f}
  4649.                 };
  4650.                 ID2D1PathGeometry* geom = nullptr;
  4651.                 pFactory->CreatePathGeometry(&geom);
  4652.                 ID2D1GeometrySink* sink = nullptr;
  4653.                 geom->Open(&sink);
  4654.                 sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4655.                 sink->AddLines(&tri[1], 2);
  4656.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4657.                 sink->Close();
  4658.                 pRT->FillGeometry(geom, pArrow);
  4659.                 SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  4660.             }
  4661.  
  4662.             // draw prompt below pockets
  4663.             D2D1_RECT_F txt = D2D1::RectF(
  4664.                 TABLE_LEFT,
  4665.                 TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4666.                 TABLE_RIGHT,
  4667.                 TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4668.             );
  4669.             pRT->DrawText(
  4670.                 L"Choose a pocket...",
  4671.                 (UINT32)wcslen(L"Choose a pocket..."),
  4672.                 pTextFormat,
  4673.                 &txt,
  4674.                 pBrush
  4675.             );
  4676.             // do NOT return here; allow foul/turn text to display under the arrow
  4677.         }
  4678.  
  4679.         // Removed Obsolete
  4680.         /*
  4681.         // --- 8-Ball Pocket Selection Arrow & Prompt ---
  4682.         if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  4683.             // Determine which pocket to highlight (default to Top-Right if unset)
  4684.             int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4685.             if (idx < 0) idx = 2;
  4686.  
  4687.             // Draw the downward arrow
  4688.             ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4689.             pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4690.             if (pArrowBrush) {
  4691.                 D2D1_POINT_2F P = pocketPositions[idx];
  4692.                 D2D1_POINT_2F tri[3] = {
  4693.                     {P.x - 10.0f, P.y - 30.0f},
  4694.                     {P.x + 10.0f, P.y - 30.0f},
  4695.                     {P.x        , P.y - 10.0f}
  4696.                 };
  4697.                 ID2D1PathGeometry* geom = nullptr;
  4698.                 pFactory->CreatePathGeometry(&geom);
  4699.                 ID2D1GeometrySink* sink = nullptr;
  4700.                 geom->Open(&sink);
  4701.                 sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4702.                 sink->AddLines(&tri[1], 2);
  4703.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4704.                 sink->Close();
  4705.                 pRT->FillGeometry(geom, pArrowBrush);
  4706.                 SafeRelease(&sink);
  4707.                 SafeRelease(&geom);
  4708.                 SafeRelease(&pArrowBrush);
  4709.             }
  4710.  
  4711.             // Draw “Choose a pocket...” text under the table
  4712.             D2D1_RECT_F prompt = D2D1::RectF(
  4713.                 TABLE_LEFT,
  4714.                 TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4715.                 TABLE_RIGHT,
  4716.                 TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4717.             );
  4718.             pRT->DrawText(
  4719.                 L"Choose a pocket...",
  4720.                 (UINT32)wcslen(L"Choose a pocket..."),
  4721.                 pTextFormat,
  4722.                 &prompt,
  4723.                 pBrush
  4724.             );
  4725.  
  4726.             return; // Skip normal turn/foul text
  4727.         }
  4728.         */
  4729.  
  4730.  
  4731.         // Show AI Thinking State (Unchanged from previous step)
  4732.         if (currentGameState == AI_THINKING && pTextFormat) {
  4733.             ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  4734.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  4735.             if (pThinkingBrush) {
  4736.                 D2D1_RECT_F thinkingRect = p2Rect;
  4737.                 thinkingRect.top += 20; // Offset within P2 box
  4738.                 // Ensure default text alignment for this
  4739.                 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4740.                 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4741.                 pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  4742.                 SafeRelease(&pThinkingBrush);
  4743.             }
  4744.         }
  4745.  
  4746.         SafeRelease(&pBrush);
  4747.  
  4748.         // --- Draw CHEAT MODE label if active ---
  4749.         if (cheatModeEnabled) {
  4750.             ID2D1SolidColorBrush* pCheatBrush = nullptr;
  4751.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  4752.             if (pCheatBrush && pTextFormat) {
  4753.                 D2D1_RECT_F cheatTextRect = D2D1::RectF(
  4754.                     TABLE_LEFT + 10.0f,
  4755.                     TABLE_TOP + 10.0f,
  4756.                     TABLE_LEFT + 200.0f,
  4757.                     TABLE_TOP + 40.0f
  4758.                 );
  4759.                 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  4760.                 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4761.                 pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
  4762.             }
  4763.             SafeRelease(&pCheatBrush);
  4764.         }
  4765.     }
  4766.  
  4767.     void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  4768.         // Draw Border
  4769.         ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4770.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4771.         if (!pBorderBrush) return;
  4772.         pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  4773.         SafeRelease(&pBorderBrush);
  4774.  
  4775.         // Create Gradient Fill
  4776.         ID2D1GradientStopCollection* pGradientStops = nullptr;
  4777.         ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  4778.         D2D1_GRADIENT_STOP gradientStops[4];
  4779.         gradientStops[0].position = 0.0f;
  4780.         gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  4781.         gradientStops[1].position = 0.45f;
  4782.         gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  4783.         gradientStops[2].position = 0.7f;
  4784.         gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  4785.         gradientStops[3].position = 1.0f;
  4786.         gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  4787.  
  4788.         pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  4789.         if (pGradientStops) {
  4790.             D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  4791.             props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  4792.             props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  4793.             pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  4794.             SafeRelease(&pGradientStops);
  4795.         }
  4796.  
  4797.         // Calculate Fill Height
  4798.         float fillRatio = 0;
  4799.         //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  4800.             // Determine if power meter should reflect shot power (human aiming or AI preparing)
  4801.         bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  4802.         // NEW Condition: AI is displaying its aim, so show its chosen power
  4803.         bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  4804.             currentGameState == AI_THINKING && aiIsDisplayingAim);
  4805.  
  4806.         if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  4807.             fillRatio = shotPower / MAX_SHOT_POWER;
  4808.         }
  4809.         float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  4810.         D2D1_RECT_F fillRect = D2D1::RectF(
  4811.             powerMeterRect.left,
  4812.             powerMeterRect.bottom - fillHeight,
  4813.             powerMeterRect.right,
  4814.             powerMeterRect.bottom
  4815.         );
  4816.  
  4817.         if (pGradientBrush) {
  4818.             pRT->FillRectangle(&fillRect, pGradientBrush);
  4819.             SafeRelease(&pGradientBrush);
  4820.         }
  4821.  
  4822.         // Draw scale notches
  4823.         ID2D1SolidColorBrush* pNotchBrush = nullptr;
  4824.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  4825.         if (pNotchBrush) {
  4826.             for (int i = 0; i <= 8; ++i) {
  4827.                 float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  4828.                 pRT->DrawLine(
  4829.                     D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  4830.                     D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  4831.                     pNotchBrush,
  4832.                     1.5f
  4833.                 );
  4834.             }
  4835.             SafeRelease(&pNotchBrush);
  4836.         }
  4837.  
  4838.         // Draw "Power" Label Below Meter
  4839.         if (pTextFormat) {
  4840.             ID2D1SolidColorBrush* pTextBrush = nullptr;
  4841.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  4842.             if (pTextBrush) {
  4843.                 D2D1_RECT_F textRect = D2D1::RectF(
  4844.                     powerMeterRect.left - 20.0f,
  4845.                     powerMeterRect.bottom + 8.0f,
  4846.                     powerMeterRect.right + 20.0f,
  4847.                     powerMeterRect.bottom + 38.0f
  4848.                 );
  4849.                 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4850.                 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4851.                 pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  4852.                 SafeRelease(&pTextBrush);
  4853.             }
  4854.         }
  4855.  
  4856.         // Draw Glow Effect if fully charged or fading out
  4857.         static float glowPulse = 0.0f;
  4858.         static bool glowIncreasing = true;
  4859.         static float glowFadeOut = 0.0f; // NEW: tracks fading out
  4860.  
  4861.         if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  4862.             // While fully charged, keep pulsing normally
  4863.             if (glowIncreasing) {
  4864.                 glowPulse += 0.02f;
  4865.                 if (glowPulse >= 1.0f) glowIncreasing = false;
  4866.             }
  4867.             else {
  4868.                 glowPulse -= 0.02f;
  4869.                 if (glowPulse <= 0.0f) glowIncreasing = true;
  4870.             }
  4871.             glowFadeOut = 1.0f; // Reset fade out to full
  4872.         }
  4873.         else if (glowFadeOut > 0.0f) {
  4874.             // If shot fired, gradually fade out
  4875.             glowFadeOut -= 0.02f;
  4876.             if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  4877.         }
  4878.  
  4879.         if (glowFadeOut > 0.0f) {
  4880.             ID2D1SolidColorBrush* pGlowBrush = nullptr;
  4881.             float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  4882.             pRT->CreateSolidColorBrush(
  4883.                 D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  4884.                 &pGlowBrush
  4885.             );
  4886.             if (pGlowBrush) {
  4887.                 float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  4888.                 float glowCenterY = powerMeterRect.top;
  4889.                 D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  4890.                     D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  4891.                     12.0f + 3.0f * glowPulse,
  4892.                     6.0f + 2.0f * glowPulse
  4893.                 );
  4894.                 pRT->FillEllipse(&glowEllipse, pGlowBrush);
  4895.                 SafeRelease(&pGlowBrush);
  4896.             }
  4897.         }
  4898.     }
  4899.  
  4900.     void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  4901.         ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  4902.         ID2D1SolidColorBrush* pRedBrush = nullptr;
  4903.  
  4904.         pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  4905.         pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  4906.  
  4907.         if (!pWhiteBrush || !pRedBrush) {
  4908.             SafeRelease(&pWhiteBrush);
  4909.             SafeRelease(&pRedBrush);
  4910.             return;
  4911.         }
  4912.  
  4913.         // Draw White Ball Background
  4914.         D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  4915.         pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  4916.         pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  4917.  
  4918.  
  4919.         // Draw Red Dot for Spin Position
  4920.         float dotRadius = 4.0f;
  4921.         float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  4922.         float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  4923.         D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  4924.         pRT->FillEllipse(&dotEllipse, pRedBrush);
  4925.  
  4926.         SafeRelease(&pWhiteBrush);
  4927.         SafeRelease(&pRedBrush);
  4928.     }
  4929.  
  4930.  
  4931.     void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  4932.         ID2D1SolidColorBrush* pBgBrush = nullptr;
  4933.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  4934.  
  4935.         // Ensure render target is valid before proceeding
  4936.         if (!pRT) return;
  4937.  
  4938.         HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  4939.         if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  4940.  
  4941.         hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  4942.         if (FAILED(hr)) {
  4943.             SafeRelease(&pBgBrush);
  4944.             SafeRelease(&pBallBrush);
  4945.             return; // Exit if brush creation fails
  4946.         }
  4947.  
  4948.         // Draw the background bar (rounded rect)
  4949.         D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  4950.         float baseAlpha = 0.8f;
  4951.         float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  4952.         float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  4953.         pBgBrush->SetOpacity(finalAlpha);
  4954.         pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  4955.         pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  4956.  
  4957.         // --- Draw small circles for pocketed balls inside the bar ---
  4958.  
  4959.         // Calculate dimensions based on the bar's height for better scaling
  4960.         float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  4961.         float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  4962.         float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  4963.         float padding = spacing * 0.75f; // Add padding from the edges
  4964.         float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  4965.  
  4966.         // Starting X positions with padding
  4967.         float currentX_P1 = pocketedBallsBarRect.left + padding;
  4968.         float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  4969.  
  4970.         int p1DrawnCount = 0;
  4971.         int p2DrawnCount = 0;
  4972.         const int maxBallsToShow = 7; // Max balls per player in the bar
  4973.  
  4974.         for (const auto& b : balls) {
  4975.             if (b.isPocketed) {
  4976.                 // Skip cue ball and 8-ball in this indicator
  4977.                 if (b.id == 0 || b.id == 8) continue;
  4978.  
  4979.                 bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  4980.                 bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  4981.  
  4982.                 if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  4983.                     pBallBrush->SetColor(b.color);
  4984.                     // Draw P1 balls from left to right
  4985.                     D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4986.                     pRT->FillEllipse(&ballEllipse, pBallBrush);
  4987.                     p1DrawnCount++;
  4988.                 }
  4989.                 else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  4990.                     pBallBrush->SetColor(b.color);
  4991.                     // Draw P2 balls from right to left
  4992.                     D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4993.                     pRT->FillEllipse(&ballEllipse, pBallBrush);
  4994.                     p2DrawnCount++;
  4995.                 }
  4996.                 // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  4997.                 // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  4998.             }
  4999.         }
  5000.  
  5001.         SafeRelease(&pBgBrush);
  5002.         SafeRelease(&pBallBrush);
  5003.     }
  5004.  
  5005.     void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  5006.         if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  5007.             return; // Only show when placing/dragging
  5008.         }
  5009.  
  5010.         Ball* cueBall = GetCueBall();
  5011.         if (!cueBall) return;
  5012.  
  5013.         ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5014.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  5015.  
  5016.         if (pGhostBrush) {
  5017.             D2D1_POINT_2F drawPos;
  5018.             if (isDraggingCueBall) {
  5019.                 drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  5020.             }
  5021.             else {
  5022.                 // If not dragging but in placement state, show at current ball pos
  5023.                 drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  5024.             }
  5025.  
  5026.             // Check if the placement is valid before drawing differently?
  5027.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  5028.             bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  5029.  
  5030.             if (!isValid) {
  5031.                 // Maybe draw red outline if invalid placement?
  5032.                 pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  5033.             }
  5034.  
  5035.  
  5036.             D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  5037.             pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  5038.             pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  5039.  
  5040.             SafeRelease(&pGhostBrush);
  5041.         }
  5042.     }
  5043.  
  5044.     void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  5045.         /*  Never show the arrow while the player is still placing the
  5046.         cue-ball (ball-in-hand) – it otherwise hides behind the
  5047.         ghost-ball and can lock the UI.                               */
  5048.  
  5049.         /* Still skip the opening-break placement,
  5050.        but show the arrow during BALL-IN-HAND */
  5051.        // ? skip when no active call for the CURRENT shooter
  5052.         if ((currentPlayer == 1 && calledPocketP1 < 0) ||
  5053.             (currentPlayer == 2 && calledPocketP2 < 0))    return;
  5054.         /*if (currentGameState == PRE_BREAK_PLACEMENT)
  5055.             return;*/ //new ai-asked-to-disable
  5056.             /*if (currentGameState == BALL_IN_HAND_P1 ||
  5057.                 currentGameState == BALL_IN_HAND_P2 ||
  5058.                 currentGameState == PRE_BREAK_PLACEMENT)
  5059.             {
  5060.                 return;
  5061.             }*/
  5062.  
  5063.         int pocketToIndicate = -1;
  5064.         // Whenever EITHER player has pocketed their first 7 and has called (human or AI),
  5065.         // we forcibly show their arrow—regardless of currentGameState.
  5066.         if ((currentPlayer == 1 && player1Info.ballsPocketedCount >= 7 && calledPocketP1 >= 0) ||
  5067.             (currentPlayer == 2 && player2Info.ballsPocketedCount >= 7 && calledPocketP2 >= 0))
  5068.         {
  5069.             pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5070.         }
  5071.         /*// A human player is actively choosing if they are in the CHOOSING_POCKET state.
  5072.         bool isHumanChoosing = (currentGameState == CHOOSING_POCKET_P1 || (currentGameState == CHOOSING_POCKET_P2 && !isPlayer2AI));
  5073.  
  5074.         if (isHumanChoosing) {
  5075.             // When choosing, show the currently selected pocket (which has a default).
  5076.             pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5077.         }
  5078.         else if (IsPlayerOnEightBall(currentPlayer)) {
  5079.             // If it's a normal turn but the player is on the 8-ball, show their called pocket as a reminder.
  5080.             pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  5081.         }*/
  5082.  
  5083.         if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  5084.             return; // Don't draw if no pocket is selected or relevant.
  5085.         }
  5086.  
  5087.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  5088.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  5089.         if (!pArrowBrush) return;
  5090.  
  5091.         // ... The rest of your arrow drawing geometry logic remains exactly the same ...
  5092.         // (No changes needed to the points/path drawing, only the logic above)
  5093.         D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  5094.         float arrowHeadSize = HOLE_VISUAL_RADIUS * 0.5f;
  5095.         float arrowShaftLength = HOLE_VISUAL_RADIUS * 0.3f;
  5096.         float arrowShaftWidth = arrowHeadSize * 0.4f;
  5097.         float verticalOffsetFromPocketCenter = HOLE_VISUAL_RADIUS * 1.6f;
  5098.         D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  5099.  
  5100.         if (targetPocketCenter.y == TABLE_TOP) {
  5101.             tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  5102.             baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  5103.             baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  5104.             shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  5105.             shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  5106.             shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  5107.             shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  5108.         }
  5109.         else {
  5110.             tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  5111.             baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  5112.             baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  5113.             shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  5114.             shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  5115.             shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  5116.             shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  5117.         }
  5118.  
  5119.         ID2D1PathGeometry* pPath = nullptr;
  5120.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  5121.             ID2D1GeometrySink* pSink = nullptr;
  5122.             if (SUCCEEDED(pPath->Open(&pSink))) {
  5123.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  5124.                 pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  5125.                 pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  5126.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5127.                 pSink->Close();
  5128.                 SafeRelease(&pSink);
  5129.                 pRT->FillGeometry(pPath, pArrowBrush);
  5130.             }
  5131.             SafeRelease(&pPath);
  5132.         }
  5133.         SafeRelease(&pArrowBrush);
  5134.     }
  5135. ```
  5136.  
  5137. ==++ Here's the full source for (file 2/3 (No OOP-based)) "resource.h"::: ++==
  5138. ```resource.h
  5139. //{{NO_DEPENDENCIES}}
  5140. // Microsoft Visual C++ generated include file.
  5141. // Used by Yahoo-8Ball-Pool-Clone.rc
  5142. //
  5143. #define IDI_ICON1                       101
  5144. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  5145. #define IDD_NEWGAMEDLG 106
  5146. #define IDC_RADIO_2P   1003
  5147. #define IDC_RADIO_CPU  1005
  5148. #define IDC_GROUP_AI   1006
  5149. #define IDC_RADIO_EASY 1007
  5150. #define IDC_RADIO_MEDIUM 1008
  5151. #define IDC_RADIO_HARD 1009
  5152. // --- NEW Resource IDs for Opening Break ---
  5153. #define IDC_GROUP_BREAK_MODE 1010
  5154. #define IDC_RADIO_CPU_BREAK  1011
  5155. #define IDC_RADIO_P1_BREAK   1012
  5156. #define IDC_RADIO_FLIP_BREAK 1013
  5157. // --- NEW Resource ID for Table Color Dropdown ---
  5158. #define IDC_COMBO_TABLECOLOR 1014
  5159. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  5160.  
  5161. // Next default values for new objects
  5162. //
  5163. #ifdef APSTUDIO_INVOKED
  5164. #ifndef APSTUDIO_READONLY_SYMBOLS
  5165. #define _APS_NEXT_RESOURCE_VALUE        102
  5166. #define _APS_NEXT_COMMAND_VALUE         40002 // Incremented
  5167. #define _APS_NEXT_CONTROL_VALUE         1014 // Incremented
  5168. #define _APS_NEXT_SYMED_VALUE           101
  5169. #endif
  5170. #endif
  5171.  
  5172. ```
  5173.  
  5174. ==++ Here's the full source for (file 3/3 (No OOP-based)) "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  5175. ```Yahoo-8Ball-Pool-Clone.rc
  5176. // Microsoft Visual C++ generated resource script.
  5177. //
  5178. #include "resource.h"
  5179.  
  5180. #define APSTUDIO_READONLY_SYMBOLS
  5181. /////////////////////////////////////////////////////////////////////////////
  5182. //
  5183. // Generated from the TEXTINCLUDE 2 resource.
  5184. //
  5185. #include "winres.h"
  5186.  
  5187. /////////////////////////////////////////////////////////////////////////////
  5188. #undef APSTUDIO_READONLY_SYMBOLS
  5189.  
  5190. /////////////////////////////////////////////////////////////////////////////
  5191. // English (United States) resources
  5192.  
  5193. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  5194. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  5195. #pragma code_page(1252)
  5196.  
  5197. #ifdef APSTUDIO_INVOKED
  5198. /////////////////////////////////////////////////////////////////////////////
  5199. //
  5200. // TEXTINCLUDE
  5201. //
  5202.  
  5203. 1 TEXTINCLUDE
  5204. BEGIN
  5205. "resource.h\0"
  5206. END
  5207.  
  5208. 2 TEXTINCLUDE
  5209. BEGIN
  5210. "#include ""winres.h""\r\n"
  5211. "\0"
  5212. END
  5213.  
  5214. 3 TEXTINCLUDE
  5215. BEGIN
  5216. "\r\n"
  5217. "\0"
  5218. END
  5219.  
  5220. #endif    // APSTUDIO_INVOKED
  5221.  
  5222.  
  5223. /////////////////////////////////////////////////////////////////////////////
  5224. //
  5225. // Icon
  5226. //
  5227.  
  5228. // Icon with lowest ID value placed first to ensure application icon
  5229. // remains consistent on all systems.
  5230. IDI_ICON1               ICON                    "D:\\Download\\8Ball_Colored.ico"
  5231.  
  5232. #endif    // English (United States) resources
  5233. /////////////////////////////////////////////////////////////////////////////
  5234.  
  5235.  
  5236.  
  5237. #ifndef APSTUDIO_INVOKED
  5238. /////////////////////////////////////////////////////////////////////////////
  5239. //
  5240. // Generated from the TEXTINCLUDE 3 resource.
  5241. //
  5242.  
  5243.  
  5244. /////////////////////////////////////////////////////////////////////////////
  5245. #endif    // not APSTUDIO_INVOKED
  5246.  
  5247. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  5248.  
  5249. /////////////////////////////////////////////////////////////////////////////
  5250. //
  5251. // Dialog
  5252. //
  5253.  
  5254. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 185 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs) - Increased Height
  5255. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  5256. CAPTION "New 8-Ball Game"
  5257. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  5258. BEGIN
  5259. // --- Game Mode Selection ---
  5260. // Group Box for Game Mode (Optional visually, but helps structure)
  5261. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  5262.  
  5263. // "2 Player" Radio Button (First in this group)
  5264. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  5265. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  5266.  
  5267. // "Human vs CPU" Radio Button
  5268. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  5269. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  5270.  
  5271. // --- NEW: Table Color Selection ---
  5272. LTEXT           "Table Color:", IDC_STATIC, 7, 65, 50, 8
  5273. COMBOBOX        IDC_COMBO_TABLECOLOR, 7, 75, 90, 60,
  5274. CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
  5275.  
  5276.  
  5277. // --- AI Difficulty Selection (Inside its own Group Box) ---
  5278. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  5279.  
  5280. // "Easy" Radio Button (First in the AI group)
  5281. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  5282. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  5283.  
  5284. // "Medium" Radio Button
  5285. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  5286. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  5287.  
  5288. // "Hard" Radio Button
  5289. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  5290. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  5291.  
  5292. // --- Opening Break Modes (For Versus CPU Only) ---
  5293. GROUPBOX        "Opening Break Modes:", IDC_GROUP_BREAK_MODE, 118, 82, 95, 60
  5294.  
  5295. // "CPU Break" Radio Button (Default for this group)
  5296. CONTROL         "&CPU Break", IDC_RADIO_CPU_BREAK, "Button",
  5297. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 95, 70, 10
  5298.  
  5299. // "P1 Break" Radio Button
  5300. CONTROL         "&P1 Break", IDC_RADIO_P1_BREAK, "Button",
  5301. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 110, 70, 10
  5302.  
  5303. // "FlipCoin Break" Radio Button
  5304. CONTROL         "&FlipCoin Break", IDC_RADIO_FLIP_BREAK, "Button",
  5305. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 125, 70, 10
  5306.  
  5307.  
  5308. // --- Standard Buttons ---
  5309. DEFPUSHBUTTON   "Start", IDOK, 55, 160, 50, 14 // Default button (Enter key) - Adjusted Y position
  5310. PUSHBUTTON      "Cancel", IDCANCEL, 115, 160, 50, 14 // Adjusted Y position
  5311. END
  5312. ```
Advertisement
Add Comment
Please, Sign In to add comment