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
|
#include "train.h"
#include "bitmap.h"
#include "level.h"
static const Bitmap SPRITES("res/car.png");
void Train::update()
{
if (m_next) {
m_speed = m_next->m_speed;
m_progress = m_next->m_progress;
} else {
auto tile = m_level.get(x, y);
if (TILE_TYPE(tile) != TileTrack)
return;
}
m_speed *= m_acceleration;
if (m_progress < 1.f) {
m_progress += m_speed;
return;
}
if (m_next) {
x = m_nextX;
y = m_nextY;
m_nextX = m_next->x;
m_nextY = m_next->y;
m_progress = 0.f;
findDirection();
}
setPosition(m_nextX, m_nextY);
}
void Train::draw(Bitmap& bitmap, int xo, int yo)
{
float xi = ((float)x + (float)(m_nextX - x) * m_progress) * TileSize;
float yi = ((float)y + (float)(m_nextY - y) * m_progress) * TileSize;
int xx = (int)((xi - yi) / 2.f - (float)xo);
int yy = (int)((xi + yi) / 4.f - (float)yo);
int tx = 0;
if (m_dir == East || m_dir == West) tx = 24;
bitmap.blit(SPRITES, xx, yy, tx, 0, TileSize, TileSize);
}
void Train::setPosition(int tx, int ty)
{
x = tx;
y = ty;
m_progress = 0.f;
findDirection();
findNextTile();
}
Point2D Train::getSpritePosition() const
{
int xi = ceil((float)x + (float)(m_nextX - x) * m_progress);
int yi = ceil((float)y + (float)(m_nextY - y) * m_progress);
return { xi, yi };
}
void Train::addVehicle(Train* newTrain)
{
if (!m_prev) {
m_prev = newTrain;
newTrain->m_next = this;
} else {
m_prev->addVehicle(newTrain);
}
}
void Train::findDirection()
{
auto dir = TILE_DATA(m_level.get(x, y));
if (m_dir == North) {
if (dir == SouthEast) m_dir = East;
if (dir == SouthWest) m_dir = West;
if (dir == EastWest) m_dir = East;
} else if (m_dir == East) {
if (dir == NorthWest) m_dir = North;
if (dir == SouthWest) m_dir = South;
if (dir == NorthSouth) m_dir = South;
} else if (m_dir == South) {
if (dir == NorthEast) m_dir = East;
if (dir == NorthWest) m_dir = West;
if (dir == EastWest) m_dir = West;
} else if (m_dir == West) {
if (dir == NorthEast) m_dir = North;
if (dir == SouthEast) m_dir = South;
if (dir == NorthSouth) m_dir = North;
}
}
void Train::findNextTile()
{
if (m_dir == North) {
m_nextX = x;
m_nextY = y - 1;
}
if (m_dir == East) {
m_nextX = x + 1;
m_nextY = y;
}
if (m_dir == South) {
m_nextX = x;
m_nextY = y + 1;
}
if (m_dir == West) {
m_nextX = x - 1;
m_nextY = y;
}
}
|