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