Main.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. // ----------------------------------------------------------------
  2. // From Game Programming in C++ by Sanjay Madhav
  3. // Copyright (C) 2017 Sanjay Madhav. All rights reserved.
  4. //
  5. // Released under the BSD License
  6. // See LICENSE in root directory for full details.
  7. // ----------------------------------------------------------------
  8. #include "Game.h"
  9. #include <vector>
  10. #include <queue>
  11. #include <iostream>
  12. struct GraphNode
  13. {
  14. // Adjacency list
  15. std::vector<GraphNode*> mAdjacent;
  16. };
  17. struct Graph
  18. {
  19. // A graph contains nodes
  20. std::vector<GraphNode*> mNodes;
  21. };
  22. struct WeightedEdge
  23. {
  24. // Which nodes are connected by this edge?
  25. struct WeightedGraphNode* mFrom;
  26. struct WeightedGraphNode* mTo;
  27. // Weight of this edge
  28. float mWeight;
  29. };
  30. struct WeightedGraphNode
  31. {
  32. std::vector<WeightedEdge*> mEdges;
  33. // Edge from parent to me
  34. WeightedEdge* mParentEdge;
  35. float f;
  36. float g;
  37. float h;
  38. };
  39. struct WeightedGraph
  40. {
  41. std::vector<WeightedGraphNode*> mNodes;
  42. };
  43. float ComputeHeuristic(WeightedGraphNode* a, WeightedGraphNode* b)
  44. {
  45. return 0.0f;
  46. }
  47. bool AStar(WeightedGraph& g, WeightedGraphNode* start,
  48. WeightedGraphNode* goal)
  49. {
  50. // Reset mParentEdge for all nodes
  51. for (WeightedGraphNode* node : g.mNodes)
  52. {
  53. node->mParentEdge = nullptr;
  54. }
  55. // Open/closed sets
  56. std::vector<WeightedGraphNode*> openSet;
  57. std::vector<WeightedGraphNode*> closedSet;
  58. // Set current node to start, and add to closed set
  59. WeightedGraphNode* current = start;
  60. closedSet.emplace_back(current);
  61. do
  62. {
  63. // Add adjacent nodes to open set
  64. for (WeightedEdge* edge : current->mEdges)
  65. {
  66. // Only check nodes that aren't in the closed set
  67. auto iter = std::find(closedSet.begin(), closedSet.end(),
  68. edge->mTo);
  69. if (iter == closedSet.end())
  70. {
  71. iter = std::find(openSet.begin(), openSet.end(), edge->mTo);
  72. if (iter == openSet.end())
  73. {
  74. // Not in the open set, so set parent
  75. WeightedGraphNode* neighbor = edge->mTo;
  76. neighbor->mParentEdge = edge;
  77. neighbor->h = ComputeHeuristic(neighbor, goal);
  78. // g(x) is the parent's g plus cost of traversing edge
  79. neighbor->g = current->g + edge->mWeight;
  80. neighbor->f = neighbor->g + neighbor->h;
  81. openSet.emplace_back(neighbor);
  82. }
  83. else
  84. {
  85. WeightedGraphNode* neighbor = edge->mTo;
  86. // Compute g(x) cost if current becomes the parent
  87. float newG = current->g + edge->mWeight;
  88. if (newG < current->g)
  89. {
  90. // Adopt this node
  91. neighbor->mParentEdge = edge;
  92. neighbor->g = newG;
  93. // f(x) changes because g(x) changes
  94. neighbor->f = neighbor->g + neighbor->h;
  95. }
  96. }
  97. }
  98. }
  99. // If open set is empty, all possible paths are exhausted
  100. if (openSet.empty())
  101. {
  102. break;
  103. }
  104. // Find lowest cost node in open set
  105. auto iter = std::min_element(openSet.begin(), openSet.end(),
  106. [](WeightedGraphNode* a, WeightedGraphNode* b) {
  107. return a->f < b->f;
  108. });
  109. // Set to current and move from open to closed
  110. current = *iter;
  111. openSet.erase(iter);
  112. closedSet.emplace_back(current);
  113. }
  114. while (current != goal);
  115. // Did we find a path?
  116. return (current == goal) ? true : false;
  117. }
  118. bool GBFS(WeightedGraph& g, WeightedGraphNode* start,
  119. WeightedGraphNode* goal)
  120. {
  121. // Reset mParentEdge for all nodes
  122. for (WeightedGraphNode* node : g.mNodes)
  123. {
  124. node->mParentEdge = nullptr;
  125. }
  126. // Open/closed sets
  127. std::vector<WeightedGraphNode*> openSet;
  128. std::vector<WeightedGraphNode*> closedSet;
  129. // Set current node to start, and add to closed set
  130. WeightedGraphNode* current = start;
  131. closedSet.emplace_back(current);
  132. do
  133. {
  134. // Add adjacent nodes to open set
  135. for (WeightedEdge* edge : current->mEdges)
  136. {
  137. // Only check nodes that aren't in the closed set
  138. auto iter = std::find(closedSet.begin(), closedSet.end(),
  139. edge->mTo);
  140. if (iter == closedSet.end())
  141. {
  142. // Set the adjacent node's parent edge
  143. edge->mTo->mParentEdge = edge;
  144. iter = std::find(openSet.begin(), openSet.end(), edge->mTo);
  145. if (iter == openSet.end())
  146. {
  147. // Compute the heuristic for this node, and add to open set
  148. edge->mTo->h = ComputeHeuristic(edge->mTo, goal);
  149. openSet.emplace_back(edge->mTo);
  150. }
  151. }
  152. }
  153. // If open set is empty, all possible paths are exhausted
  154. if (openSet.empty())
  155. {
  156. break;
  157. }
  158. // Find lowest cost node in open set
  159. auto iter = std::min_element(openSet.begin(), openSet.end(),
  160. [](WeightedGraphNode* a, WeightedGraphNode* b) {
  161. return a->h < b->h;
  162. });
  163. // Set to current and move from open to closed
  164. current = *iter;
  165. openSet.erase(iter);
  166. closedSet.emplace_back(current);
  167. }
  168. while (current != goal);
  169. // Did we find a path?
  170. return (current == goal) ? true : false;
  171. }
  172. using NodeToParentMap =
  173. std::unordered_map<GraphNode*, GraphNode*>;
  174. bool BFS(Graph& graph, GraphNode* start, GraphNode* goal, NodeToParentMap& outMap)
  175. {
  176. // Whether we found a path
  177. bool pathFound = false;
  178. // Nodes to consider
  179. std::queue<GraphNode*> q;
  180. // Enqueue the first node
  181. q.emplace(start);
  182. while (!q.empty())
  183. {
  184. // Dequeue a node
  185. GraphNode* current = q.front();
  186. q.pop();
  187. if (current == goal)
  188. {
  189. pathFound = true;
  190. break;
  191. }
  192. // Enqueue adjacent nodes that aren't already in the queue
  193. for (GraphNode* node : current->mAdjacent)
  194. {
  195. // If the parent is null, it hasn't been enqueued
  196. // (except for the start node)
  197. GraphNode* parent = outMap[node];
  198. if (parent == nullptr && node != start)
  199. {
  200. // Enqueue this node, setting its parent
  201. outMap[node] = current;
  202. q.emplace(node);
  203. }
  204. }
  205. }
  206. return pathFound;
  207. }
  208. void testBFS()
  209. {
  210. Graph g;
  211. for (int i = 0; i < 5; i++)
  212. {
  213. for (int j = 0; j < 5; j++)
  214. {
  215. GraphNode* node = new GraphNode;
  216. g.mNodes.emplace_back(node);
  217. }
  218. }
  219. for (int i = 0; i < 5; i++)
  220. {
  221. for (int j = 0; j < 5; j++)
  222. {
  223. GraphNode* node = g.mNodes[i * 5 + j];
  224. if (i > 0)
  225. {
  226. node->mAdjacent.emplace_back(g.mNodes[(i - 1) * 5 + j]);
  227. }
  228. if (i < 4)
  229. {
  230. node->mAdjacent.emplace_back(g.mNodes[(i + 1) * 5 + j]);
  231. }
  232. if (j > 0)
  233. {
  234. node->mAdjacent.emplace_back(g.mNodes[i * 5 + j - 1]);
  235. }
  236. if (j < 4)
  237. {
  238. node->mAdjacent.emplace_back(g.mNodes[i * 5 + j + 1]);
  239. }
  240. }
  241. }
  242. NodeToParentMap map;
  243. bool found = BFS(g, g.mNodes[0], g.mNodes[9], map);
  244. std::cout << found << '\n';
  245. }
  246. void testAStar()
  247. {
  248. WeightedGraph g;
  249. for (int i = 0; i < 5; i++)
  250. {
  251. for (int j = 0; j < 5; j++)
  252. {
  253. WeightedGraphNode* node = new WeightedGraphNode;
  254. g.mNodes.emplace_back(node);
  255. }
  256. }
  257. for (int i = 0; i < 5; i++)
  258. {
  259. for (int j = 0; j < 5; j++)
  260. {
  261. WeightedGraphNode* node = g.mNodes[i*5 + j];
  262. if (i > 0)
  263. {
  264. WeightedEdge* e = new WeightedEdge;
  265. e->mFrom = node;
  266. e->mTo = g.mNodes[(i - 1) * 5 + j];
  267. e->mWeight = 1.0f;
  268. node->mEdges.emplace_back(e);
  269. }
  270. if (i < 4)
  271. {
  272. WeightedEdge* e = new WeightedEdge;
  273. e->mFrom = node;
  274. e->mTo = g.mNodes[(i + 1) * 5 + j];
  275. e->mWeight = 1.0f;
  276. node->mEdges.emplace_back(e);
  277. }
  278. if (j > 0)
  279. {
  280. WeightedEdge* e = new WeightedEdge;
  281. e->mFrom = node;
  282. e->mTo = g.mNodes[i*5 + j - 1];
  283. e->mWeight = 1.0f;
  284. node->mEdges.emplace_back(e);
  285. }
  286. if (j < 4)
  287. {
  288. WeightedEdge* e = new WeightedEdge;
  289. e->mFrom = node;
  290. e->mTo = g.mNodes[i*5 + j + 1];
  291. e->mWeight = 1.0f;
  292. node->mEdges.emplace_back(e);
  293. }
  294. }
  295. }
  296. bool found = AStar(g, g.mNodes[0], g.mNodes[9]);
  297. std::cout << found << '\n';
  298. }
  299. struct GameState
  300. {
  301. // (For tic-tac-toe, array of board)
  302. enum SquareState { Empty, X, O };
  303. SquareState mBoard[3][3];
  304. };
  305. struct GTNode
  306. {
  307. // Children nodes
  308. std::vector<GTNode*> mChildren;
  309. // State of game
  310. GameState mState;
  311. };
  312. void GenStates(GTNode* root, bool xPlayer)
  313. {
  314. for (int i = 0; i < 3; i++)
  315. {
  316. for (int j = 0; j < 3; j++)
  317. {
  318. if (root->mState.mBoard[i][j] == GameState::Empty)
  319. {
  320. GTNode* node = new GTNode;
  321. root->mChildren.emplace_back(node);
  322. node->mState = root->mState;
  323. node->mState.mBoard[i][j] = xPlayer ? GameState::X : GameState::O;
  324. GenStates(node, !xPlayer);
  325. }
  326. }
  327. }
  328. }
  329. float GetScore(GameState& state)
  330. {
  331. // Are any of the rows the same?
  332. for (int i = 0; i < 3; i++)
  333. {
  334. bool same = true;
  335. GameState::SquareState v = state.mBoard[i][0];
  336. for (int j = 1; j < 3; j++)
  337. {
  338. if (state.mBoard[i][j] != v)
  339. {
  340. same = false;
  341. }
  342. }
  343. if (same)
  344. {
  345. if (v == GameState::X)
  346. {
  347. return 1.0f;
  348. }
  349. else
  350. {
  351. return -1.0f;
  352. }
  353. }
  354. }
  355. // Are any of the columns the same?
  356. for (int j = 0; j < 3; j++)
  357. {
  358. bool same = true;
  359. GameState::SquareState v = state.mBoard[0][j];
  360. for (int i = 1; i < 3; i++)
  361. {
  362. if (state.mBoard[i][j] != v)
  363. {
  364. same = false;
  365. }
  366. }
  367. if (same)
  368. {
  369. if (v == GameState::X)
  370. {
  371. return 1.0f;
  372. }
  373. else
  374. {
  375. return -1.0f;
  376. }
  377. }
  378. }
  379. // What about diagonals?
  380. if (((state.mBoard[0][0] == state.mBoard[1][1]) &&
  381. (state.mBoard[1][1] == state.mBoard[2][2])) ||
  382. ((state.mBoard[2][0] == state.mBoard[1][1]) &&
  383. (state.mBoard[1][1] == state.mBoard[0][2])))
  384. {
  385. if (state.mBoard[1][1] == GameState::X)
  386. {
  387. return 1.0f;
  388. }
  389. else
  390. {
  391. return -1.0f;
  392. }
  393. }
  394. // We tied
  395. return 0.0f;
  396. }
  397. float MinPlayer(GTNode* node);
  398. float MaxPlayer(GTNode* node)
  399. {
  400. // If this is a leaf, return score
  401. if (node->mChildren.empty())
  402. {
  403. return GetScore(node->mState);
  404. }
  405. float maxValue = -std::numeric_limits<float>::infinity();
  406. // Find the subtree with the maximum value
  407. for (GTNode* child : node->mChildren)
  408. {
  409. maxValue = std::max(maxValue, MinPlayer(child));
  410. }
  411. return maxValue;
  412. }
  413. float MinPlayer(GTNode* node)
  414. {
  415. // If this is a leaf, return score
  416. if (node->mChildren.empty())
  417. {
  418. return GetScore(node->mState);
  419. }
  420. float minValue = std::numeric_limits<float>::infinity();
  421. // Find the subtree with the minimum value
  422. for (GTNode* child : node->mChildren)
  423. {
  424. minValue = std::min(minValue, MaxPlayer(child));
  425. }
  426. return minValue;
  427. }
  428. GTNode* MinimaxDecide(GTNode* root)
  429. {
  430. // Find the subtree with the maximum value, and save the choice
  431. GTNode* choice = nullptr;
  432. float maxValue = -std::numeric_limits<float>::infinity();
  433. for (GTNode* child : root->mChildren)
  434. {
  435. float v = MinPlayer(child);
  436. if (v > maxValue)
  437. {
  438. maxValue = v;
  439. choice = child;
  440. }
  441. }
  442. return choice;
  443. }
  444. float AlphaBetaMin(GTNode* node, float alpha, float beta);
  445. float AlphaBetaMax(GTNode* node, float alpha, float beta)
  446. {
  447. // If this is a leaf, return score
  448. if (node->mChildren.empty())
  449. {
  450. return GetScore(node->mState);
  451. }
  452. float maxValue = -std::numeric_limits<float>::infinity();
  453. // Find the subtree with the maximum value
  454. for (GTNode* child : node->mChildren)
  455. {
  456. maxValue = std::max(maxValue, AlphaBetaMin(child, alpha, beta));
  457. if (maxValue >= beta)
  458. {
  459. return maxValue; // Beta prune
  460. }
  461. alpha = std::max(maxValue, alpha);
  462. }
  463. return maxValue;
  464. }
  465. float AlphaBetaMin(GTNode* node, float alpha, float beta)
  466. {
  467. // If this is a leaf, return score
  468. if (node->mChildren.empty())
  469. {
  470. return GetScore(node->mState);
  471. }
  472. float minValue = std::numeric_limits<float>::infinity();
  473. // Find the subtree with the minimum value
  474. for (GTNode* child : node->mChildren)
  475. {
  476. minValue = std::min(minValue, AlphaBetaMax(child, alpha, beta));
  477. if (minValue <= alpha)
  478. {
  479. return minValue; // Alpha prune
  480. }
  481. beta = std::min(minValue, beta);
  482. }
  483. return minValue;
  484. }
  485. GTNode* AlphaBetaDecide(GTNode* root)
  486. {
  487. // Find the subtree with the maximum value, and save the choice
  488. GTNode* choice = nullptr;
  489. float maxValue = -std::numeric_limits<float>::infinity();
  490. float beta = std::numeric_limits<float>::infinity();
  491. for (GTNode* child : root->mChildren)
  492. {
  493. float v = AlphaBetaMin(child, maxValue, beta);
  494. if (v > maxValue)
  495. {
  496. maxValue = v;
  497. choice = child;
  498. }
  499. }
  500. return choice;
  501. }
  502. void testTicTac()
  503. {
  504. GTNode* root = new GTNode;
  505. root->mState.mBoard[0][0] = GameState::O;
  506. root->mState.mBoard[0][1] = GameState::Empty;
  507. root->mState.mBoard[0][2] = GameState::X;
  508. root->mState.mBoard[1][0] = GameState::X;
  509. root->mState.mBoard[1][1] = GameState::O;
  510. root->mState.mBoard[1][2] = GameState::O;
  511. root->mState.mBoard[2][0] = GameState::X;
  512. root->mState.mBoard[2][1] = GameState::Empty;
  513. root->mState.mBoard[2][2] = GameState::Empty;
  514. GenStates(root, true);
  515. GTNode* choice = AlphaBetaDecide(root);
  516. std::cout << choice->mChildren.size();
  517. }
  518. int main(int argc, char** argv)
  519. {
  520. Game game;
  521. bool success = game.Initialize();
  522. if (success)
  523. {
  524. game.RunLoop();
  525. }
  526. game.Shutdown();
  527. return 0;
  528. }