Game.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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 "SDL/SDL_image.h"
  10. #include <algorithm>
  11. #include "Actor.h"
  12. #include "SpriteComponent.h"
  13. #include "Random.h"
  14. Game::Game()
  15. :mWindow(nullptr)
  16. ,mRenderer(nullptr)
  17. ,mIsRunning(true)
  18. ,mUpdatingActors(false)
  19. {
  20. }
  21. bool Game::Initialize()
  22. {
  23. if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_AUDIO) != 0)
  24. {
  25. SDL_Log("Unable to initialize SDL: %s", SDL_GetError());
  26. return false;
  27. }
  28. mWindow = SDL_CreateWindow("Game Programming in C++ (Chapter 4)", 100, 100, 1024, 768, 0);
  29. if (!mWindow)
  30. {
  31. SDL_Log("Failed to create window: %s", SDL_GetError());
  32. return false;
  33. }
  34. mRenderer = SDL_CreateRenderer(mWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  35. if (!mRenderer)
  36. {
  37. SDL_Log("Failed to create renderer: %s", SDL_GetError());
  38. return false;
  39. }
  40. if (IMG_Init(IMG_INIT_PNG) == 0)
  41. {
  42. SDL_Log("Unable to initialize SDL_image: %s", SDL_GetError());
  43. return false;
  44. }
  45. Random::Init();
  46. LoadData();
  47. mTicksCount = SDL_GetTicks();
  48. return true;
  49. }
  50. void Game::RunLoop()
  51. {
  52. while (mIsRunning)
  53. {
  54. ProcessInput();
  55. UpdateGame();
  56. GenerateOutput();
  57. }
  58. }
  59. void Game::ProcessInput()
  60. {
  61. SDL_Event event;
  62. while (SDL_PollEvent(&event))
  63. {
  64. switch (event.type)
  65. {
  66. case SDL_QUIT:
  67. mIsRunning = false;
  68. break;
  69. // Process mouse button event
  70. case SDL_MOUSEBUTTONDOWN:
  71. if (event.button.button == SDL_BUTTON_LEFT &&
  72. !mBoardState.IsTerminal())
  73. {
  74. // Convert x into column
  75. int col = event.button.x - 64;
  76. if (col >= 0)
  77. {
  78. col /= 128;
  79. if (col <= 6)
  80. {
  81. bool playerMoved = TryPlayerMove(&mBoardState, col);
  82. if (playerMoved && !mBoardState.IsTerminal())
  83. {
  84. CPUMove(&mBoardState);
  85. }
  86. }
  87. }
  88. }
  89. break;
  90. }
  91. }
  92. const Uint8* keyState = SDL_GetKeyboardState(NULL);
  93. if (keyState[SDL_SCANCODE_ESCAPE])
  94. {
  95. mIsRunning = false;
  96. }
  97. mUpdatingActors = true;
  98. for (auto actor : mActors)
  99. {
  100. actor->ProcessInput(keyState);
  101. }
  102. mUpdatingActors = false;
  103. }
  104. void Game::UpdateGame()
  105. {
  106. // Compute delta time
  107. // Wait until 16ms has elapsed since last frame
  108. while (!SDL_TICKS_PASSED(SDL_GetTicks(), mTicksCount + 16))
  109. ;
  110. float deltaTime = (SDL_GetTicks() - mTicksCount) / 1000.0f;
  111. if (deltaTime > 0.05f)
  112. {
  113. deltaTime = 0.05f;
  114. }
  115. mTicksCount = SDL_GetTicks();
  116. // Update all actors
  117. mUpdatingActors = true;
  118. for (auto actor : mActors)
  119. {
  120. actor->Update(deltaTime);
  121. }
  122. mUpdatingActors = false;
  123. // Move any pending actors to mActors
  124. for (auto pending : mPendingActors)
  125. {
  126. mActors.emplace_back(pending);
  127. }
  128. mPendingActors.clear();
  129. // Add any dead actors to a temp vector
  130. std::vector<Actor*> deadActors;
  131. for (auto actor : mActors)
  132. {
  133. if (actor->GetState() == Actor::EDead)
  134. {
  135. deadActors.emplace_back(actor);
  136. }
  137. }
  138. // Delete dead actors (which removes them from mActors)
  139. for (auto actor : deadActors)
  140. {
  141. delete actor;
  142. }
  143. }
  144. void Game::GenerateOutput()
  145. {
  146. SDL_SetRenderDrawColor(mRenderer, 255, 255, 255, 255);
  147. SDL_RenderClear(mRenderer);
  148. // Draw all sprite components
  149. for (auto sprite : mSprites)
  150. {
  151. sprite->Draw(mRenderer);
  152. }
  153. // For Exercise 4.2
  154. // Draw background
  155. DrawTexture(GetTexture("Assets/Board.png"), Vector2(512.0f, 384.0f),
  156. Vector2(896.0f, 768.0f));
  157. // Draw pieces
  158. for (int i = 0; i < 6; i++)
  159. {
  160. for (int j = 0; j < 7; j++)
  161. {
  162. Vector2 pos(j * 128.0f + 128.0f, i * 128.0f + 64.0f);
  163. if (mBoardState.mBoard[i][j] == BoardState::Yellow)
  164. {
  165. DrawTexture(GetTexture("Assets/YellowPiece.png"), pos,
  166. Vector2(128.0f, 128.0f));
  167. }
  168. else if (mBoardState.mBoard[i][j] == BoardState::Red)
  169. {
  170. DrawTexture(GetTexture("Assets/RedPiece.png"), pos,
  171. Vector2(128.0f, 128.0f));
  172. }
  173. }
  174. }
  175. SDL_RenderPresent(mRenderer);
  176. }
  177. void Game::LoadData()
  178. {
  179. }
  180. void Game::UnloadData()
  181. {
  182. // Delete actors
  183. // Because ~Actor calls RemoveActor, have to use a different style loop
  184. while (!mActors.empty())
  185. {
  186. delete mActors.back();
  187. }
  188. // Destroy textures
  189. for (auto i : mTextures)
  190. {
  191. SDL_DestroyTexture(i.second);
  192. }
  193. mTextures.clear();
  194. }
  195. SDL_Texture* Game::GetTexture(const std::string& fileName)
  196. {
  197. SDL_Texture* tex = nullptr;
  198. // Is the texture already in the map?
  199. auto iter = mTextures.find(fileName);
  200. if (iter != mTextures.end())
  201. {
  202. tex = iter->second;
  203. }
  204. else
  205. {
  206. // Load from file
  207. SDL_Surface* surf = IMG_Load(fileName.c_str());
  208. if (!surf)
  209. {
  210. SDL_Log("Failed to load texture file %s", fileName.c_str());
  211. return nullptr;
  212. }
  213. // Create texture from surface
  214. tex = SDL_CreateTextureFromSurface(mRenderer, surf);
  215. SDL_FreeSurface(surf);
  216. if (!tex)
  217. {
  218. SDL_Log("Failed to convert surface to texture for %s", fileName.c_str());
  219. return nullptr;
  220. }
  221. mTextures.emplace(fileName.c_str(), tex);
  222. }
  223. return tex;
  224. }
  225. void Game::DrawTexture(SDL_Texture* texture, const Vector2& pos, const Vector2& size)
  226. {
  227. SDL_Rect r;
  228. // Scale the width/height by owner's scale
  229. r.w = static_cast<int>(size.x);
  230. r.h = static_cast<int>(size.y);
  231. // Center the rectangle around the position of the owner
  232. r.x = static_cast<int>(pos.x) - r.w / 2;
  233. r.y = static_cast<int>(pos.y) - r.h / 2;
  234. // Draw (have to convert angle from radians to degrees, and clockwise to counter)
  235. SDL_RenderCopy(mRenderer,
  236. texture,
  237. nullptr,
  238. &r);
  239. }
  240. void Game::Shutdown()
  241. {
  242. UnloadData();
  243. IMG_Quit();
  244. SDL_DestroyRenderer(mRenderer);
  245. SDL_DestroyWindow(mWindow);
  246. SDL_Quit();
  247. }
  248. void Game::AddActor(Actor* actor)
  249. {
  250. // If we're updating actors, need to add to pending
  251. if (mUpdatingActors)
  252. {
  253. mPendingActors.emplace_back(actor);
  254. }
  255. else
  256. {
  257. mActors.emplace_back(actor);
  258. }
  259. }
  260. void Game::RemoveActor(Actor* actor)
  261. {
  262. // Is it in pending actors?
  263. auto iter = std::find(mPendingActors.begin(), mPendingActors.end(), actor);
  264. if (iter != mPendingActors.end())
  265. {
  266. // Swap to end of vector and pop off (avoid erase copies)
  267. std::iter_swap(iter, mPendingActors.end() - 1);
  268. mPendingActors.pop_back();
  269. }
  270. // Is it in actors?
  271. iter = std::find(mActors.begin(), mActors.end(), actor);
  272. if (iter != mActors.end())
  273. {
  274. // Swap to end of vector and pop off (avoid erase copies)
  275. std::iter_swap(iter, mActors.end() - 1);
  276. mActors.pop_back();
  277. }
  278. }
  279. void Game::AddSprite(SpriteComponent* sprite)
  280. {
  281. // Find the insertion point in the sorted vector
  282. // (The first element with a higher draw order than me)
  283. int myDrawOrder = sprite->GetDrawOrder();
  284. auto iter = mSprites.begin();
  285. for ( ;
  286. iter != mSprites.end();
  287. ++iter)
  288. {
  289. if (myDrawOrder < (*iter)->GetDrawOrder())
  290. {
  291. break;
  292. }
  293. }
  294. // Inserts element before position of iterator
  295. mSprites.insert(iter, sprite);
  296. }
  297. void Game::RemoveSprite(SpriteComponent* sprite)
  298. {
  299. // (We can't swap because it ruins ordering)
  300. auto iter = std::find(mSprites.begin(), mSprites.end(), sprite);
  301. mSprites.erase(iter);
  302. }