-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlidingPuzzle.cpp
More file actions
124 lines (96 loc) · 2.33 KB
/
SlidingPuzzle.cpp
File metadata and controls
124 lines (96 loc) · 2.33 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
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
124
#include "../Include/defGameEngine.hpp"
#include <array>
using namespace std;
constexpr int MAP_WIDTH = 3;
constexpr int MAP_HEIGHT = 3;
constexpr int CELL_SIZE = 16;
template <typename T>
struct Map
{
Map() = default;
~Map() = default;
array<T, MAP_WIDTH * MAP_HEIGHT> values;
void set(int x, int y, T value)
{
if (x >= 0 && y >= 0 && x < MAP_WIDTH && y < MAP_HEIGHT)
values[y * MAP_WIDTH + x] = value;
}
T* get(int x, int y)
{
if (x >= 0 && y >= 0 && x < MAP_WIDTH && y < MAP_HEIGHT)
return &values[y * MAP_WIDTH + x];
return nullptr;
}
};
class SlidingPuzzle : public def::GameEngine
{
public:
SlidingPuzzle()
{
GetWindow()->SetTitle("Sliding Puzzle");
}
private:
Map<int> map;
def::Vector2i mapSize = { MAP_WIDTH, MAP_HEIGHT };
def::Vector2i cellSize = { CELL_SIZE, CELL_SIZE };
public:
bool OnUserCreate() override
{
srand(time(0));
for (int i = 0; i < map.values.size() - 1; i++)
{
int value;
do { value = rand() % (map.values.size() + 1); }
while (
find(map.values.begin(), map.values.end(), value) != map.values.end() ||
value == map.values.size()
);
map.values[i] = value;
}
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
if (GetInput()->GetButtonState(def::Button::LEFT).pressed)
{
def::Vector2i cellPos = GetInput()->GetMousePosition() / cellSize;
if (cellPos < mapSize && cellPos >= def::Vector2i(0, 0))
{
int* valueOld = map.get(cellPos.x, cellPos.y);
auto check = [&](int ox, int oy)
{
int* valueNew = map.get(cellPos.x + ox, cellPos.y + oy);
if (valueNew != nullptr && *valueNew == 0)
{
*valueNew = *valueOld;
*valueOld = 0;
return true;
}
return false;
};
if (check(-1, 0)) {}
else if (check(0, -1)) {}
else if (check(1, 0)) {}
else if (check(0, 1)) {}
}
}
Clear(def::BLACK);
def::Vector2i pos;
for (pos.x = 0; pos.x < MAP_WIDTH; pos.x++)
for (pos.y = 0; pos.y < MAP_HEIGHT; pos.y++)
{
def::Vector2i cellPos = pos * cellSize;
int value = map.values[pos.y * MAP_WIDTH + pos.x];
DrawRectangle(cellPos, cellSize);
if (value > 0) DrawString(def::Vector2f(cellPos) + def::Vector2f(cellSize) * 0.25f, std::to_string(value));
}
return true;
}
};
int main()
{
SlidingPuzzle demo;
demo.Construct(256, 240, 4, 4);
demo.Run();
return 0;
}