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