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