I am working on a basic tetris game for school. I am not sure how can i develop a game loop since this is my first time making a game.
I am using opengl to do the drawing. Do I make a main loop that will wait certain amount of time before it redrawn the scene?
Here's a basic (very high level pseudo-code) game loop:
void RunGameLoop()
{
// record the frame time and calculate the time since the last frame
float timeTemp = time();
float deltaTime = timeTemp - lastFrameTime;
lastFrameTime = timeTemp;
// iterate through all units and let them update
unitManager->update(deltaTime);
// iterate through all units and let them draw
drawManager->draw();
}
The purpose of passing deltaTime (the time since the last frame in seconds) to unitManager->update() is so that when the units are updating, they can multiply their movement by deltaTime so their values can be in units per second.
abstract class Unit
{
public:
abstract void update(float deltaTime);
}
FallingBlockUnit::update(float deltaTime)
{
moveDown(fallSpeed * deltaTime);
}
The draw manager is going to be responsible for managing the draw buffers (I suggest double buffering to prevent screen flicker)
DrawManager::draw()
{
// set the back buffer to a blank color
backBuffer->clear();
// draw all units here
// limit the frame rate by sleeping until the next frame should be drawn
// const float frameDuration = 1.0f / framesPerSecond;
float sleepTime = lastDrawTime + frameDuration - time();
sleep(sleepTime);
lastDrawTime = time();
// swap the back buffer to the front
frontBuffer->draw(backBuffer);
}
For further research, here's a book that my Game Programming professor wrote about 2d game programming. http://www.amazon.com/Graphics-Programming-Games-John-Pile/dp/1466501898