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
125
126
127
128
129
130
131
|
#include "level.h"
#include "train.h"
#include "util.h"
Level::Level(int width, int height, Bitmap& tileSprites)
: m_width(width), m_height(height), m_tileSprites(tileSprites)
{
m_tiles = new uint8_t[width * height];
memset(m_tiles, TileGround, width * height);
}
uint8_t Level::get(int x, int y)
{
if (inBounds(x, y))
return m_tiles[x + y * m_width];
else
return TileGround;
}
void Level::set(int x, int y, uint8_t tile)
{
if (inBounds(x, y))
m_tiles[x + y * m_width] = tile;
}
void Level::update()
{
for (Train* vehicle : m_vehicles) {
if (vehicle) vehicle->update();
}
}
void Level::draw(Bitmap& bitmap, int xo, int yo)
{
for (int y = 0; y < 32; ++y) {
for (int x = 0; x < 32; ++x) {
auto tile = get(x, y);
int xx = (x - y) * (TileSize / 2) - xo;
int yy = (x + y) * (TileSize / 4) - yo;
int tx = (x + y) % 2;
int ty = 0;
if (TILE_TYPE(tile) == TileTrack) {
uint8_t dir = TILE_DATA(tile);
if (dir == NorthSouth) {
tx = 0;
ty = 2;
} else if (dir == EastWest) {
tx = 1;
ty = 2;
} else if (dir == SouthEast) {
tx = 0;
ty = 3;
} else if (dir == SouthWest) {
tx = 3;
ty = 3;
} else if (dir == NorthWest) {
tx = 1;
ty = 3;
} else if (dir == NorthEast) {
tx = 2;
ty = 3;
}
}
bitmap.blit(m_tileSprites, xx, yy, tx * TileSize, ty * TileSize, TileSize, TileSize);
}
}
for (Train* vehicle : m_vehicles) {
if (vehicle) vehicle->draw(bitmap, xo, yo);
}
}
void Level::addVehicle(Train& vehicle)
{
m_vehicles.emplace_back(&vehicle);
}
void Level::toggleTile(int x, int y)
{
static const auto updateDirection = [&](int xt, int yt) {
if (TILE_TYPE(get(xt, yt)) == TileTrack)
set(xt, yt, MAKE_TILE(TileTrack, ChooseDirection(*this, xt, yt)));
};
if (inBounds(x, y)) {
auto tile = get(x, y);
if (TILE_TYPE(tile) == TileTrack)
tile = TileGround;
else
tile = MAKE_TILE(TileTrack, ChooseDirection(*this, x, y));
m_tiles[x + y * m_width] = tile;
updateDirection(x - 1, y);
updateDirection(x + 1, y);
updateDirection(x, y - 1);
updateDirection(x, y + 1);
}
}
TrackDirection ChooseDirection(Level& level, int x, int y)
{
if (!level.inBounds(x, y)) return NorthSouth;
bool n = TILE_TYPE(level.get(x, y - 1)) == TileTrack;
bool e = TILE_TYPE(level.get(x + 1, y)) == TileTrack;
bool s = TILE_TYPE(level.get(x, y + 1)) == TileTrack;
bool w = TILE_TYPE(level.get(x - 1, y)) == TileTrack;
if ((n || s) && !(e || w)) {
return NorthSouth;
}
if ((e || w) && !(n || s)) {
return EastWest;
} else if (s && e) {
return SouthEast;
} else if (s && w) {
return SouthWest;
} else if (n && w) {
return NorthWest;
} else if (n && e) {
return NorthEast;
}
return NorthSouth;
}
|