Game.cpp
Code: Select all
#include "MainWindow.h"
#include "Game.h"
Game::Game( MainWindow& wnd )
:
wnd( wnd ),
gfx( wnd ),
rng(std::random_device()())
{
for (int i = 0; i < maxEnemy; i++)
{
enemy[i] = Enemy(0, 0);
}
}
void Game::Go()
{
gfx.BeginFrame();
UpdateModel();
ComposeFrame();
gfx.EndFrame();
}
void Game::UpdateModel()
{
for (int i = 0; i < index; i++)
{
if (enemy[i].isDestroyed())
{
enemy[i] = enemy[index];
index--;
i--;
}
else
{
enemy[i].update();
}
}
registerEnemy();
}
void Game::registerEnemy()
{
if (timeLeft > 0)
{
timeLeft--;
}
else
{
timeLeft = maxTime;
if (index < maxEnemy)
{
std::uniform_int_distribution<int> yDist(0, Graphics::ScreenHeight - 30);
index++;
enemy[index].moveTo(Graphics::ScreenWidth, yDist(rng));
}
}
}
void Game::ComposeFrame()
{
for (int i = 0; i < index; i++)
{
if (!enemy[i].isDestroyed())
{
enemy[i].draw(gfx);
}
}
}
Code: Select all
class Game
{
public:
Game( class MainWindow& wnd );
Game( const Game& ) = delete;
Game& operator=( const Game& ) = delete;
void Go();
private:
void ComposeFrame();
void UpdateModel();
/********************************/
/* User Functions */
void registerEnemy();
/********************************/
private:
MainWindow& wnd;
Graphics gfx;
/********************************/
/* User Variables */
static constexpr int maxEnemy = 30;
int index = 0;
Enemy enemy[maxEnemy];
std::mt19937 rng;
int timeLeft = 0;
int maxTime = 10;
/********************************/
};
Code: Select all
Enemy::Enemy(int x, int y)
{
_x = x;
_y = y;
}
void Enemy::moveTo(int x, int y)
{
_x = x - _width;
_y = y;
_destroyed = false;
}
void Enemy::destroy()
{
_destroyed = true;
_x = 0;
_y = 0;
}
bool Enemy::isDestroyed()
{
return _destroyed;
}
void Enemy::update()
{
if (_x - _speed <= 0)
{
destroy();
}
else
{
_x = _x - _speed;
}
}
void Enemy::draw(Graphics& gfx)
{
gfx.DrawRectDim(_x, _y, _width, _height, _c);
}
Code: Select all
class Enemy
{
private:
int _x;
int _y;
bool _destroyed = true;
Color _c = Colors::Green;
static constexpr int _width = 20;
static constexpr int _height = 20;
static constexpr int _speed = 7;
void destroy();
public:
Enemy() = default;
Enemy(int x, int y);
void moveTo(int x, int y);
bool isDestroyed();
void update();
void draw(Graphics& gfx);
};