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