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