-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
437 lines (402 loc) · 17.3 KB
/
Copy pathmain.cpp
File metadata and controls
437 lines (402 loc) · 17.3 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
#include <iostream>
#include <cmath>
#include <limits>
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <SFML/Window.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
#include "Physics.cpp"
#include "Physics.hpp"
#include "TileMap.cpp"
#include "player.cpp"
#include "player.hpp"
#include "Enemy.cpp"
#include "Enemy.hpp"
#include "PathFinder.cpp"
#include "Entity.hpp"
#include "Constants.hpp"
// Functions for conversions
inline sf::Vector2i worldToGrid(const Vec2& pos, int tileSize) {
return sf::Vector2i(static_cast<int>(pos.x) / tileSize,
static_cast<int>(pos.y) / tileSize);
}
inline sf::Vector2f gridToWorld(const Node* node, int tileSize) {
return sf::Vector2f(node->x * tileSize + tileSize / 2,
node->y * tileSize + tileSize / 2);
}
// Function for pickup object collision
template <typename PickupType, typename EffectFunc>
void handlePickup(std::vector<PickupType>& pickups,
Object& (playerCollider),
MapLoader& map,
EffectFunc effect) {
for (auto it = pickups.begin(); it != pickups.end();) {
Manifold m = { &(playerCollider), it->collider() };
if (AABBvsAABB(&m)) {
// Apply pickup effect
effect(*it);
// Remove from tilemap
Vec2 pos = it->collider()->pos;
int tileX = static_cast<int>(pos.x) / TILE_SIZE;
int tileY = static_cast<int>(pos.y) / TILE_SIZE;
map.setTile(tileX, tileY, '.');
// Remove from vector
it = pickups.erase(it);
} else {
++it;
}
}
}
int main()
{
sf::Clock clock;
sf::Clock sprintClock;
// Set up audio
sf::SoundBuffer goldPickupBuffer;
sf::SoundBuffer healthPickupBuffer;
// Load audio from files
if (!goldPickupBuffer.loadFromFile("assets/audio/goldPickup.ogg")) {
std::cerr << "Error: Could not load gold pickup sound file!" << std::endl;
return -1;
}
if (!healthPickupBuffer.loadFromFile("assets/audio/healthPickup.ogg")) {
std::cerr << "Error: Could not load health pickup sound file!" << std::endl;
return -1;
}
// Creat sounds
sf::Sound goldPickupSound(goldPickupBuffer);
sf::Sound healthPickupSound(healthPickupBuffer);
// Create list of entities
std::vector<std::shared_ptr<Entity>> entities;
// Default player position
sf::Vector2f pos = {275, 200};
// ---- Load tilemap ----
MapLoader map;
TileMapRenderer renderer;
map.loadFromFile("level.txt");
// Set up pathfinding grid
sf::Vector2i size = map.getSize();
Grid grid(size.x, size.y);
// Find player and walls
for (int y = 0; y < size.y; ++y) {
for (int x = 0; x < size.x; ++x) {
if (map.getTile(x, y) == '#' || map.getTile(x, y) == 'U' || map.getTile(x, y) == 'L' || map.getTile(x, y) == 'R' || map.getTile(x, y) == '%') {
grid.nodes[y][x].wall = true;
}
if (map.getTile(x, y) == 'P') {
// Set player position
pos = sf::Vector2f(static_cast<float>(x * TILE_SIZE + TILE_SIZE / 2.0f), static_cast<float>(y * TILE_SIZE + TILE_SIZE / 2.0f));
}
}
}
// ---- Create a player ----
auto player = std::make_shared<Player>(pos);
entities.push_back(player);
Object playerCollider = (player->playerCollider);
// ---- Set up colliders ----
std::vector<Object*> colliders; // Create colliders list
struct healthPickup {
Object healthPickup;
Object* collider() { return &healthPickup; }
};
std::vector<healthPickup> healthPickups;
struct goldPickup {
Object goldPickup;
Object* collider() { return &goldPickup; }
};
std::vector<goldPickup> goldPickups;
struct chestPickup {
Object chestPickup;
float stateTimer = 0.f;
int state = 0; // 0 = closed, 1 = open-full, 2 = open-empty
Object* collider() { return &chestPickup; }
};
std::vector<chestPickup> chestPickups;
// ---- Set up objects ----
std::vector<Object> wallObjects;
sf::Texture enemyTex;
if (!enemyTex.loadFromFile("assets/images/enemySpritesheet.png"))
throw std::runtime_error("Failed to load enemy spritesheet");
wallObjects.reserve(size.x * size.y);
for (int y = 0; y < size.y; ++y) { // Height
for (int x = 0; x < size.x; ++x) { // Width
// Walls
if (map.getTile(x, y) == '#' || map.getTile(x, y) == 'U' || map.getTile(x, y) == 'L' || map.getTile(x, y) == 'R' || map.getTile(x, y) == '%') {
Object wall;
wall.pos = Vec2(x * TILE_SIZE + TILE_SIZE / 2.0f, y * TILE_SIZE + TILE_SIZE / 2.0f);
wall.aabb.min = Vec2(x * TILE_SIZE, y * TILE_SIZE);
wall.aabb.max = Vec2((x + 1) * TILE_SIZE, (y + 1) * TILE_SIZE);
// Add to colliders
wallObjects.push_back(wall);
colliders.push_back(&wallObjects.back());
}
// Health pickups
if (map.getTile(x, y) == 'H') {
Object pickup;
pickup.pos = Vec2(x * TILE_SIZE + TILE_SIZE / 2.0f, y * TILE_SIZE + TILE_SIZE / 2.0f);
pickup.aabb.min = Vec2(x * TILE_SIZE, y * TILE_SIZE);
pickup.aabb.max = Vec2((x + 1) * TILE_SIZE, (y + 1) * TILE_SIZE);
// Add to list
healthPickups.push_back(healthPickup{pickup});
}
// Gold pickups
if (map.getTile(x, y) == 'G') {
Object pickup;
pickup.pos = Vec2(x * TILE_SIZE + TILE_SIZE / 2.0f, y * TILE_SIZE + TILE_SIZE / 2.0f);
pickup.aabb.min = Vec2(x * TILE_SIZE, y * TILE_SIZE);
pickup.aabb.max = Vec2((x + 1) * TILE_SIZE, (y + 1) * TILE_SIZE);
// Add to list
goldPickups.push_back(goldPickup{pickup});
}
// Chest pickups
if (map.getTile(x, y) == 'C') {
Object pickup;
pickup.pos = Vec2(x * TILE_SIZE + TILE_SIZE / 2.0f, y * TILE_SIZE + TILE_SIZE / 2.0f);
pickup.aabb.min = Vec2(x * TILE_SIZE, y * TILE_SIZE);
pickup.aabb.max = Vec2((x + 1) * TILE_SIZE, (y + 1) * TILE_SIZE);
// Add to list
chestPickups.push_back(chestPickup{pickup});
}
// Enemies
if (map.getTile(x, y) == 'E') {
Vec2 pos(x * TILE_SIZE + TILE_SIZE / 2.0f, y * TILE_SIZE + TILE_SIZE / 2.0f);
entities.push_back(std::make_shared<Enemy>(
toSF(pos), enemyTex, grid, *player
));
}
}
}
// ---- Set up game window ----
// Create game window
sf::RenderWindow window(sf::VideoMode({1500, 800}), "2D Game", sf::Style::Titlebar | sf::Style::Close);
window.setFramerateLimit(60);
// Create game camera
sf::View camera;
sf::Vector2u winSize = window.getSize();
camera.setSize(sf::Vector2f(winSize.x, winSize.y));
camera.setCenter(player->getPosition());
window.setView(camera);
// ---- Events ----
// Timers and keys used for detecting double taps
sf::Time lastClickTime; // The last click of each key
const sf::Time doubleClickTime = sf::milliseconds(500); // Expected time limit for second click to happen
sf::Keyboard::Scancode lastDirection = sf::Keyboard::Scancode::Unknown; // The direction of last key press
std::map<sf::Keyboard::Scancode, bool> keyHeld; // Check if key is held
bool sprint; // If player should sprint or not
bool isDoubleTap = false; // If use has double tapped or not
// Ensures window closes properly when closed
const auto onClose = [&window](const sf::Event::Closed&) {
window.close();
};
bool isPaused = false;
// Check when key is pressed
const auto onKeyPressed = [&window, &player, &sprintClock, &lastClickTime, &doubleClickTime, &lastDirection, &keyHeld, &sprint, &isDoubleTap, &isPaused](const sf::Event::KeyPressed& keyPressed) {
// Ensure window is closed when Escape key is pressed
if (keyPressed.scancode == sf::Keyboard::Scancode::Escape) {
window.close();
}
// Toggle pause when P is pressed
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Scancode::P)) {
isPaused = !isPaused;
}
sf::Time now = sprintClock.getElapsedTime();
// Check for double tap
if (!keyHeld[keyPressed.scancode]) {
// Update key held
keyHeld[keyPressed.scancode] = true;
// Sprint only if within expected click time and facing same direction as last click
if ((keyPressed.scancode == lastDirection) && (now - lastClickTime < doubleClickTime) && (!sprint)) {
isDoubleTap = true;
} else {
isDoubleTap = false;
}
player->sprint(isDoubleTap);
if (isDoubleTap) {
sprint = true;
} else {
sprint = false;
}
}
lastDirection = keyPressed.scancode; // Key that was last clicked
lastClickTime = now; // Time user last clicked
};
// Check when key is released
const auto onKeyReleased = [&window, &keyHeld](const sf::Event::KeyReleased& keyPressed) {
// If double tap movement keys, tell player to sprint
if (keyPressed.scancode == sf::Keyboard::Scan::Right ||
keyPressed.scancode == sf::Keyboard::Scan::D ||
keyPressed.scancode == sf::Keyboard::Scan::Left ||
keyPressed.scancode == sf::Keyboard::Scan::A ||
keyPressed.scancode == sf::Keyboard::Scan::Up ||
keyPressed.scancode == sf::Keyboard::Scan::W ||
keyPressed.scancode == sf::Keyboard::Scan::Down ||
keyPressed.scancode == sf::Keyboard::Scan::S) {
}
// Update key held
keyHeld[keyPressed.scancode] = false;
};
// Add pause button
auto windowSize = window.getSize();
sf::Texture pauseTex("assets/images/PauseButton.png");
sf::Texture playTex("assets/images/PlayButton.png");
sf::Sprite pauseButton(pauseTex);
pauseButton.setScale({0.07, 0.07});
pauseButton.setColor(sf::Color::White);
// To store time paused button was clicked to add a click delay
sf::Clock clickClock;
sf::Time clickDelay = sf::milliseconds(300);
// Game loop
std::cout << "Starting game";
while (window.isOpen()) {
sf::Time delta = clock.restart(); // Time since last frame
float deltaTime = delta.asSeconds(); // Convert to seconds
// Handle events and updates
window.handleEvents(onClose, onKeyPressed, onKeyReleased);
if (!isPaused) {
player->handleInput();
for (auto& e : entities) e->update(deltaTime);
pauseButton.setTexture(pauseTex);
} else {
pauseButton.setTexture(playTex);
}
// Create new window with black background
window.clear(sf::Color::Black);
if (!isPaused) {
//---- Movement ----
Vec2 originalPos = (player->playerCollider).pos;
// X axis
float originalX = (player->playerCollider).pos.x;
(player->playerCollider).pos.x += player->movement.x;
// Stop if colliding with an object that isn't the player and isn't a pickup
for (auto& e : entities) { if (e->type() == EntityType::Player) continue;
if (e->type() == EntityType::Pickup) continue;
Manifold m = { &(player->playerCollider), &e->collider() };
if (AABBvsAABB(&m)) { (player->playerCollider).pos.x = originalX; break; }
}
for (auto& obj : colliders) {
Manifold m = { &(player->playerCollider), obj };
if (AABBvsAABB(&m)) { (player->playerCollider).pos.x = originalX; break; }
}
// Y axis
float originalY = (player->playerCollider).pos.y;
(player->playerCollider).pos.y += player->movement.y;
// Stop if colliding with object
for (auto& e : entities) { if (e->type() == EntityType::Player) continue;
if (e->type() == EntityType::Pickup) continue;
Manifold m = { &(player->playerCollider), &e->collider() };
if (AABBvsAABB(&m)) { (player->playerCollider).pos.y = originalY; break; }
}
for (auto& obj : colliders) { Manifold m = { &(player->playerCollider), obj };
if (AABBvsAABB(&m)) { (player->playerCollider).pos.y = originalY; break; }
}
//---- Damage ----
// Check if enemy is attacking player, if close enough damage player
for (auto& e : entities) {
if (e->type() == EntityType::Enemy) {
float dx = player->getPosition().x - e->getPosition().x;
float dy = player->getPosition().y - e->getPosition().y;
float dist = std::sqrt(dx*dx + dy*dy);
if (e->isAttacking() && dist <= e->getAttackRadius()) {
player->takeDamage(1);
}
}
}
//---- Pickups ----
// Heal player when colliding with health pickups if not at max health
if (player->getHealth() < player->getMaxHealth()) {
handlePickup(healthPickups, (player->playerCollider), map, [&](auto& pickup) {
player->heal(1);
healthPickupSound.play();
});
}
// Give gold when colliding with gold pickups
handlePickup(goldPickups, (player->playerCollider), map, [&](auto& pickup) {
player->addGold(25);
goldPickupSound.play();
});
// Give gold when colliding with chest pickups
for (auto& chest : chestPickups) {
Manifold m = { &(player->playerCollider), chest.collider() };
if (AABBvsAABB(&m)) {
// Open chest
Vec2 pos = chest.collider()->pos;
int tileX = pos.x / TILE_SIZE;
int tileY = pos.y / TILE_SIZE;
if (chest.state == 0) {
map.setTile(tileX, tileY, 'Q');
player->addGold(100);
goldPickupSound.play();
chest.state = 1;
chest.stateTimer = 0.f; // Start animation timer
}
}
}
// Check chest states
for (auto& chest : chestPickups) {
if (chest.state == 1) {
chest.stateTimer += deltaTime;
// After 0.4 seconds, switch to empty chest
if (chest.stateTimer >= 0.4f) {
Vec2 pos = chest.collider()->pos;
int tileX = pos.x / TILE_SIZE;
int tileY = pos.y / TILE_SIZE;
map.setTile(tileX, tileY, 'O');
chest.state = 2;
}
}
}
}
//---- Draw items ----
// Draw tilemap floors
renderer.drawFloors(window, map);
// Draw all shadows for entities (enemies and player)
for (auto& e : entities) { e->drawShadow(window); }
// Draw tilemap walls and items
renderer.drawWalls(window, map);
renderer.drawItems(window, map);
// Sort by Y position before drawing, so that the highest objects are drawn first
std::sort(entities.begin(), entities.end(),
[](const std::shared_ptr<Entity>& a, const std::shared_ptr<Entity>& b) {
return a->getPosition().y < b->getPosition().y;
});
// Draw and update all entity sprites
for (auto& e : entities) { e->draw(window); }
// Draw camera and UI
player->drawUI(window, camera);
camera.setCenter(player->getPosition());
window.setView(camera);
sf::Vector2f viewCenter = camera.getCenter();
sf::FloatRect bounds = pauseButton.getGlobalBounds();
pauseButton.setPosition({ // Center button at top of camera
viewCenter.x - bounds.size.x / 2.f,
viewCenter.y - bounds.size.y / 2.f - 368.f
});
window.draw(pauseButton);
if (player->isDead()) {
}
// Delete dead entities
entities.erase(
std::remove_if(entities.begin(), entities.end(),
[](const std::shared_ptr<Entity>& e) {
return e->isDead();
}),
entities.end()
);
// Display window
window.display();
// Check if pause button pressed
if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) {
sf::Vector2i mousePos = sf::Mouse::getPosition(window);
sf::Vector2f worldPos = window.mapPixelToCoords(mousePos);
// Toggle pause if clicked on and click delay has passed
if (pauseButton.getGlobalBounds().contains(worldPos)) {
if (clickClock.getElapsedTime() > clickDelay) {
isPaused = !isPaused;
clickClock.restart(); // Restart delay
}
}
}
}
return 0;
}