-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
98 lines (86 loc) · 2.98 KB
/
Copy pathmain.cpp
File metadata and controls
98 lines (86 loc) · 2.98 KB
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
#include "lifeboard.h"
#include <SDL2/SDL.h>
#include <string>
#include <cmath>
int main(int argc, char *argv[])
{
int rc = 0;
SDL_Window *win = { };
SDL_Renderer *g = { };
try
{
if (SDL_Init(SDL_INIT_VIDEO) < 0)
throw "SDL initialization failed";
win = SDL_CreateWindow("Life game",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
640,
480,
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (!win)
throw "failed to create SDL window";
g = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED);
if (!g)
throw "failed to create renderer";
LifeBoard board;
board.init(100, 100, 0.1f);
bool runLoop = true;
while (runLoop)
{
SDL_Event evt;
while (SDL_PollEvent(&evt) != 0)
{
switch (evt.type)
{
case SDL_QUIT:
runLoop = false;
break;
}
}
// Update game area state
board.update();
// Render the area
SDL_SetRenderDrawColor(g, 0, 0, 0, 0xFFu);
SDL_RenderClear(g);
int winW, winH;
SDL_GetWindowSize(win, &winW, &winH);
const float cellWidth = static_cast<float>(winW) / board.width(),
cellHeight = static_cast<float>(winH) / board.height();
SDL_Rect rCell;
for (int r = 0; r < board.height(); r++)
for (int c = 0; c < board.width(); c++)
{
const int v = board.cell(r, c);
if (v != LifeBoard::EMPTY_CELL)
{
const auto x = c * cellWidth,
y = r * cellHeight;
rCell.x = static_cast<int>(std::floor(x));
rCell.y = static_cast<int>(std::floor(y));
rCell.w = static_cast<int>(std::floor(cellWidth + x - rCell.x));
rCell.h = static_cast<int>(std::floor(cellHeight + y - rCell.y));
const auto clr = board.color(v);
SDL_SetRenderDrawColor(g, clr[0], clr[1], clr[2], 0xFF);
SDL_RenderFillRect(g, &rCell);
}
}
SDL_RenderPresent(g);
}
}
catch (const char *msg)
{
std::string fullMsg = "Initialization error: ";
fullMsg += msg;
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR,
"Error",
fullMsg.c_str(),
win);
rc = 1;
}
if (g)
SDL_DestroyRenderer(g);
if (win)
SDL_DestroyWindow(win);
SDL_Quit();
return rc;
}