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