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