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