summaryrefslogtreecommitdiff
path: root/src/train.cpp
blob: 2604898ae4322a4c2f2706f1e526b28a1439a4f5 (plain)
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
#include "train.h"

#include "bitmap.h"
#include "level.h"

void Train::update(Level& level)
{
	if (m_next) {
		m_speed = m_next->m_speed;
		m_progress = m_next->m_progress;
	} else {
		auto tile = level.get(x, y);
		if (tile == 0)
			return;
	}

	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(m_sprite, xx, yy, tx, 0, TileSize, TileSize);
}

void Train::setPosition(int tx, int ty)
{
	x = tx;
	y = ty;

	m_progress = 0.f;
	findDirection();
	findNextTile();
}

void Train::addVehicle(Train* newTrain)
{
	if (!m_prev) {
		m_prev = newTrain;
		newTrain->m_next = this;
	} else {
		m_prev->addVehicle(newTrain);
	}
}

void Train::findDirection()
{
	auto tile = m_level.get(x, y);

	if (m_dir == North) {
		if (tile == SouthEast) m_dir = East;
		if (tile == SouthWest) m_dir = West;
		if (tile == EastWest) m_dir = East;
	} else if (m_dir == East) {
		if (tile == NorthWest) m_dir = North;
		if (tile == SouthWest) m_dir = South;
		if (tile == NorthSouth) m_dir = South;
	} else if (m_dir == South) {
		if (tile == NorthEast) m_dir = East;
		if (tile == NorthWest) m_dir = West;
		if (tile == EastWest) m_dir = West;
	} else if (m_dir == West) {
		if (tile == NorthEast) m_dir = North;
		if (tile == SouthEast) m_dir = South;
		if (tile == 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;
	}
}