1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
|
#include "Game.h"
Game::Game()
{
gameState = STATE::PLAY;
}
Game::~Game()
{
SDL_Quit();
}
void Game::Init(int width, int height, std::string title)
{
SDL_Init(SDL_INIT_EVERYTHING);
const char* cTitle;
cTitle = title.c_str();
window = SDL_CreateWindow(
cTitle,
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
width,
height,
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
player1.SetUp(5, height / 2, 20, 100);
player2.SetUp(width - 25, height / 2, 20, 100);
//SDL CHECK ERROR
InitErrorCheck();
}
void Game::Update()
{
while (gameState != STATE::EXIT)
{
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
CheckInput();
Destroy();
player1.Draw(renderer);
player2.Draw(renderer);
}
}
void Game::Run()
{
Init(800,600,"Pong");
Update();
}
void Game::InitErrorCheck()
{
if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
printf("Error Initializing SDL: %s\n", SDL_GetError());
exit(1);
}
if (window == NULL)
{
printf("Error Creating Window: %s\n", SDL_GetError());
exit(1);
}
if (renderer == NULL)
{
printf("Error Creating Renderer %s\n", SDL_GetError());
}
}
void Game::CheckInput()
{
SDL_Event evnt;
while (SDL_PollEvent(&evnt) == 1)
{
switch (evnt.type)
{
case SDL_QUIT:
gameState = STATE::EXIT;
break;
case SDL_MOUSEMOTION:
player1.MouseMove(5, renderer, evnt.motion);
player2.MouseMove(5, renderer, evnt.motion);
//std::cout << evnt.motion.x << " " << evnt.motion.y << std::endl;
break;
case SDL_KEYDOWN:
switch (evnt.key.keysym.sym)
{
case SDLK_w:
player1.MoveUp(5, renderer);
break;
case SDLK_s:
player1.MoveDown(5, renderer);
break;
}
}
}
}
//Free resources with this function
void Game::Destroy()
{
if (gameState == STATE::EXIT)
SDL_Quit();
if (renderer == NULL)
SDL_DestroyRenderer(renderer);
}
|