-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
370 lines (357 loc) · 16.2 KB
/
Copy pathmain.cpp
File metadata and controls
370 lines (357 loc) · 16.2 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
// Include the SFML graphics library for rendering
#include <SFML/Graphics.hpp>
// Include vector for dynamic arrays
#include <vector>
// Include cstdlib and ctime for random number generation
#include <cstdlib>
#include <ctime>
// Enum to represent the different states of the game
// START: Start screen, DIFFICULTY_SELECT: Choosing difficulty, RUNNING: Game in progress, GAME_OVER: Game ended
enum class GameState { START, DIFFICULTY_SELECT, RUNNING, GAME_OVER };
// Main class for the Snake game
class SnakeGame {
public:
// Constructor: Initializes the game window, sets framerate, loads font, and resets the game
SnakeGame() : window(sf::VideoMode(800, 600), "Snake Game"), snake(1), food(0, 0), dir(1, 0), state(GameState::START) {
window.setFramerateLimit(15); // Set the frame rate limit
srand(static_cast<unsigned>(time(0))); // Seed random number generator
if (!font.loadFromFile("C:/Windows/Fonts/arial.ttf")) {
font.loadFromFile("arial.ttf"); // Fallback if default path fails
}
reset(); // Initialize game state
}
// Main game loop: Handles events, updates game state, and draws everything
void run() {
while (window.isOpen()) {
handleEvents(); // Process user input and window events
if (state == GameState::RUNNING) update(); // Update game only if running
draw(); // Render the game
}
}
private:
// Struct to represent a segment of the snake or a position (x, y)
struct Segment {
int x, y;
Segment() : x(0), y(0) {}
Segment(int xPos, int yPos) : x(xPos), y(yPos) {}
};
sf::RenderWindow window; // The game window
std::vector<Segment> snake; // The snake, represented as a vector of segments
Segment food; // The current food position
Segment dir; // The current direction of the snake
GameState state; // The current state of the game
sf::Font font; // Font used for rendering text
int score = 0; // Player's score
int foodEaten = 0; // Number of foods eaten
float moveDelay = 0.15f; // Delay between snake moves (controls speed)
sf::Clock moveClock; // Clock to manage move timing
// Bonus food
bool bonusActive = false; // Is bonus food active?
Segment bonusFood; // Position of bonus food
sf::Clock bonusClock; // Timer for bonus food
float bonusDuration = 15.0f; // Duration bonus food stays on screen
bool mediumObstacles = false; // Are medium obstacles enabled?
bool hardObstacles = false; // Are hard obstacles enabled?
std::vector<Segment> mediumObstacleBlocks; // Positions of medium obstacles
std::vector<Segment> hardObstacleBlocks; // Positions of hard obstacles
void reset() {
snake.clear();
snake.emplace_back(16, 12);
dir = Segment(1, 0);
spawnFood();
score = 0;
foodEaten = 0;
moveDelay = 0.15f;
bonusActive = false;
mediumObstacleBlocks.clear();
hardObstacleBlocks.clear();
if (mediumObstacles) {
// Place two vertical obstacles, each 5 blocks tall, centered vertically
int obsXs[2] = {8, 23};
for (int i = 0; i < 2; ++i) {
int x = obsXs[i];
for (int y = 9; y <= 13; ++y) {
mediumObstacleBlocks.emplace_back(x, y);
}
}
}
// Hard mode obstacles
if (!mediumObstacles && hardObstacles) {
int xs[4] = {6, 12, 18, 24};
for (int i = 0; i < 4; ++i) {
int x = xs[i];
if (i % 2 == 0) { // Touch bottom, now 6 blocks tall
for (int y = 18; y <= 23; ++y) {
hardObstacleBlocks.emplace_back(x, y);
}
} else { // Touch top
for (int y = 1; y <= 5; ++y) {
hardObstacleBlocks.emplace_back(x, y);
}
}
}
}
}
// Handles all user input and window events
void handleEvents() {
sf::Event event;
while (window.pollEvent(event)) {
// Close the window if the close event is triggered
if (event.type == sf::Event::Closed) window.close();
// Handle key press events
if (event.type == sf::Event::KeyPressed) {
// If on start screen and Enter is pressed, go to difficulty selection
if (state == GameState::START && event.key.code == sf::Keyboard::Enter) {
state = GameState::DIFFICULTY_SELECT;
// If on difficulty selection screen, set difficulty based on key pressed
} else if (state == GameState::DIFFICULTY_SELECT) {
if (event.key.code == sf::Keyboard::Num1 || event.key.code == sf::Keyboard::Numpad1) {
moveDelay = 0.18f; // Easy mode: slow speed
mediumObstacles = false;
hardObstacles = false;
state = GameState::RUNNING;
reset(); // Start game with easy settings
} else if (event.key.code == sf::Keyboard::Num2 || event.key.code == sf::Keyboard::Numpad2) {
moveDelay = 0.12f; // Medium mode: medium speed
mediumObstacles = true;
hardObstacles = false;
state = GameState::RUNNING;
reset(); // Start game with medium settings
} else if (event.key.code == sf::Keyboard::Num3 || event.key.code == sf::Keyboard::Numpad3) {
moveDelay = 0.07f; // Hard mode: fast speed
mediumObstacles = false;
hardObstacles = true;
state = GameState::RUNNING;
reset(); // Start game with hard settings
}
// If on game over screen and Enter is pressed, return to start
} else if (state == GameState::GAME_OVER && event.key.code == sf::Keyboard::Enter) {
state = GameState::START;
// If game is running, handle arrow key input for snake direction
} else if (state == GameState::RUNNING) {
if (event.key.code == sf::Keyboard::Up && dir.y != 1) dir = Segment(0, -1); // Up
else if (event.key.code == sf::Keyboard::Down && dir.y != -1) dir = Segment(0, 1); // Down
else if (event.key.code == sf::Keyboard::Left && dir.x != 1) dir = Segment(-1, 0); // Left
else if (event.key.code == sf::Keyboard::Right && dir.x != -1) dir = Segment(1, 0); // Right
}
}
}
}
void update() {
if (moveClock.getElapsedTime().asSeconds() < moveDelay) return;
moveClock.restart();
// Move body
for (size_t i = snake.size() - 1; i > 0; --i) {
snake[i] = snake[i - 1];
}
// Move head
snake[0].x += dir.x;
snake[0].y += dir.y;
// Die if snake touches any boundary block
if (snake[0].x == 0 || snake[0].x == 31 || snake[0].y == 0 || snake[0].y == 23) {
state = GameState::GAME_OVER;
return;
}
// Die if snake touches any medium obstacle block
if (mediumObstacles) {
for (const auto& obs : mediumObstacleBlocks) {
if (snake[0].x == obs.x && snake[0].y == obs.y) {
state = GameState::GAME_OVER;
return;
}
}
}
// Die if snake touches any hard obstacle block
if (hardObstacles) {
for (const auto& obs : hardObstacleBlocks) {
if (snake[0].x == obs.x && snake[0].y == obs.y) {
state = GameState::GAME_OVER;
return;
}
}
}
// Check self collision
for (size_t i = 1; i < snake.size(); ++i) {
if (snake[i].x == snake[0].x && snake[i].y == snake[0].y) {
state = GameState::GAME_OVER;
return;
}
}
// Check bonus food
if (bonusActive && snake[0].x == bonusFood.x && snake[0].y == bonusFood.y) {
score += 10;
bonusActive = false;
}
// Check normal food
if (snake[0].x == food.x && snake[0].y == food.y) {
snake.push_back(snake.back());
spawnFood();
score++;
foodEaten++;
// Speed up every 5 foods, spawn bonus
if (foodEaten % 5 == 0) {
spawnBonusFood();
bonusActive = true;
bonusClock.restart();
if (moveDelay > 0.05f) moveDelay -= 0.02f;
}
}
// Bonus food timer
if (bonusActive && bonusClock.getElapsedTime().asSeconds() > bonusDuration) {
bonusActive = false;
}
}
void draw() {
window.clear(sf::Color::Black);
// Draw red boundaries (same size as snake block: 25x25)
sf::RectangleShape boundary;
boundary.setFillColor(sf::Color::Red);
// Top boundary
for (int i = 0; i < 32; ++i) {
boundary.setSize(sf::Vector2f(25, 25));
boundary.setPosition(i * 25, 0);
window.draw(boundary);
}
// Bottom boundary
for (int i = 0; i < 32; ++i) {
boundary.setSize(sf::Vector2f(25, 25));
boundary.setPosition(i * 25, 23 * 25);
window.draw(boundary);
}
// Left boundary
for (int i = 1; i < 23; ++i) {
boundary.setSize(sf::Vector2f(25, 25));
boundary.setPosition(0, i * 25);
window.draw(boundary);
}
// Right boundary
for (int i = 1; i < 23; ++i) {
boundary.setSize(sf::Vector2f(25, 25));
boundary.setPosition((31) * 25, i * 25);
window.draw(boundary);
}
// Draw vertical obstacles for medium difficulty
if (mediumObstacles) {
sf::RectangleShape obs(sf::Vector2f(25, 25));
obs.setFillColor(sf::Color::Red);
for (const auto& block : mediumObstacleBlocks) {
obs.setPosition(block.x * 25, block.y * 25);
window.draw(obs);
}
}
// Draw obstacles for hard difficulty
if (hardObstacles) {
sf::RectangleShape obs(sf::Vector2f(25, 25));
obs.setFillColor(sf::Color::Red);
for (const auto& block : hardObstacleBlocks) {
obs.setPosition(block.x * 25, block.y * 25);
window.draw(obs);
}
}
// Draw score in a rectangle (not touching boundaries)
sf::RectangleShape scoreRect(sf::Vector2f(150, 40));
scoreRect.setFillColor(sf::Color(30, 30, 30, 200)); // semi-transparent dark
scoreRect.setOutlineColor(sf::Color::White);
scoreRect.setOutlineThickness(2);
scoreRect.setPosition(30, 30); // away from boundaries
window.draw(scoreRect);
drawText("Score: " + std::to_string(score), 24, 45, 35, sf::Color::White);
if (state == GameState::START) {
drawText("Press Enter to Start", 48, window.getSize().x/2-200, window.getSize().y/2-40, sf::Color::White);
} else if (state == GameState::DIFFICULTY_SELECT) {
drawText("Select Difficulty", 48, window.getSize().x/2-200, window.getSize().y/2-100, sf::Color::White);
drawText("1: Easy", 36, window.getSize().x/2-80, window.getSize().y/2-20, sf::Color(100,255,100));
drawText("2: Medium", 36, window.getSize().x/2-100, window.getSize().y/2+40, sf::Color(255,255,100));
drawText("3: Hard", 36, window.getSize().x/2-80, window.getSize().y/2+100, sf::Color(255,100,100));
} else if (state == GameState::GAME_OVER) {
drawText("Game Over!", 48, window.getSize().x/2-120, window.getSize().y/2-80, sf::Color::Red);
drawText("Score: " + std::to_string(score), 32, window.getSize().x/2-60, window.getSize().y/2, sf::Color::White);
drawText("Press Enter to Restart", 32, window.getSize().x/2-170, window.getSize().y/2+60, sf::Color::White);
} else {
// Draw food
sf::RectangleShape foodRect(sf::Vector2f(25, 25));
foodRect.setFillColor(sf::Color(128, 0, 128)); // Set food color to purple
foodRect.setPosition(food.x * 25, food.y * 25);
window.draw(foodRect);
// Draw bonus food
if (bonusActive) {
sf::RectangleShape bonusRect(sf::Vector2f(25, 25));
bonusRect.setFillColor(sf::Color::Yellow);
bonusRect.setPosition(bonusFood.x * 25, bonusFood.y * 25);
window.draw(bonusRect);
// Draw bonus timer
int timeLeft = (int)(bonusDuration - bonusClock.getElapsedTime().asSeconds());
if (timeLeft > 0) {
drawText("Bonus: " + std::to_string(timeLeft) + "s", 18, bonusFood.x * 25, bonusFood.y * 25 - 20, sf::Color::Yellow);
}
}
// Draw snake
for (size_t i = 0; i < snake.size(); i++) {
sf::RectangleShape rect(sf::Vector2f(25, 25));
rect.setFillColor(i == 0 ? sf::Color::Green : sf::Color(0, 180, 0));
rect.setPosition(snake[i].x * 25, snake[i].y * 25);
window.draw(rect);
}
}
window.display();
}
// Draws text on the game window at the specified position, size, and color
void drawText(const std::string& str, int size, int x, int y, sf::Color color) {
sf::Text text;
text.setFont(font); // Set the font for the text
text.setString(str); // Set the string to display
text.setCharacterSize(size); // Set the font size
text.setFillColor(color); // Set the text color
text.setPosition(x, y); // Set the position on the window
window.draw(text); // Draw the text on the window
}
// Spawns food at a random position not occupied by the snake, obstacles, or the score board area
void spawnFood() {
do {
food.x = 1 + rand() % 30; // Random x within boundaries (avoids edges)
food.y = 1 + rand() % 22; // Random y within boundaries (avoids edges)
} while (
isOnSnake(food.x, food.y) || // Ensure food is not on the snake
(mediumObstacles && isOnMediumObstacle(food.x, food.y)) || // Not on medium obstacles
(hardObstacles && isOnHardObstacle(food.x, food.y)) || // Not on hard obstacles
(food.x * 25 >= 30 && food.x * 25 < 180 && food.y * 25 >= 30 && food.y * 25 < 70) // Not in score board area
);
}
// Spawns bonus food at a random position not occupied by the snake, normal food, obstacles, or the score board area
void spawnBonusFood() {
do {
bonusFood.x = 1 + rand() % 30; // Random x within boundaries (avoids edges)
bonusFood.y = 1 + rand() % 22; // Random y within boundaries (avoids edges)
} while (
isOnSnake(bonusFood.x, bonusFood.y) || // Not on the snake
(bonusFood.x == food.x && bonusFood.y == food.y) || // Not on normal food
(mediumObstacles && isOnMediumObstacle(bonusFood.x, bonusFood.y)) || // Not on medium obstacles
(hardObstacles && isOnHardObstacle(bonusFood.x, bonusFood.y)) || // Not on hard obstacles
(bonusFood.x * 25 >= 30 && bonusFood.x * 25 < 180 && bonusFood.y * 25 >= 30 && bonusFood.y * 25 < 70) // Not in score board area
);
}
// Checks if the given (x, y) position is occupied by a hard obstacle
bool isOnHardObstacle(int x, int y) {
for (const auto& obs : hardObstacleBlocks) {
if (obs.x == x && obs.y == y) return true;
}
return false;
}
bool isOnSnake(int x, int y) {
for (const auto& s : snake) {
if (s.x == x && s.y == y) return true;
}
return false;
}
bool isOnMediumObstacle(int x, int y) {
for (const auto& obs : mediumObstacleBlocks) {
if (obs.x == x && obs.y == y) return true;
}
return false;
}
};
int main() {
SnakeGame game;
game.run();
return 0;
}