-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnake.cpp
More file actions
83 lines (68 loc) · 2.28 KB
/
Snake.cpp
File metadata and controls
83 lines (68 loc) · 2.28 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
using namespace std;
#include <iostream>
#include <vector>
#include "Snake.h"
// Initialize the Snake with initial direction and length
Snake::Snake(int startX, int startY, int length, int width, int height)
: currentDirection('D'), gridHeight(height), gridWidth(width) {
for (int i = 0; i < length; ++i) {
body.push_back({startX - i, startY});
}
}
// Set Direction of the snake according to the user input
void Snake::setDirection(char newDirection){
char snakeDirection = 0;
if (newDirection == 'w' || newDirection == 'W') {
snakeDirection = 'W';
} else if (newDirection == 's' || newDirection == 'S') {
snakeDirection = 'S';
} else if (newDirection == 'a' || newDirection == 'A') {
snakeDirection = 'A';
} else if (newDirection == 'd' || newDirection == 'D') {
snakeDirection = 'D';
} else {
return;
}
if ((snakeDirection == 'W' && currentDirection == 'S') ||
(snakeDirection == 'S' && currentDirection == 'W') ||
(snakeDirection == 'A' && currentDirection == 'D') ||
(snakeDirection == 'D' && currentDirection == 'A'))
{
return;
}
currentDirection = snakeDirection;
}
Point Snake::move(char direction, bool grow) {
setDirection(direction);
Point newHead = body[0];
// Determine the position of the head based on the input of the user
switch (currentDirection) {
case 'W': newHead.y--; break;
case 'S': newHead.y++; break;
case 'A': newHead.x--; break;
case 'D': newHead.x++; break;
}
// Store the old tail of the snake before it is removed
Point oldTail = body.back();
// Adding the new head in front of the body of the snake
body.insert(body.begin(), newHead);
// Removing the tail in case the snake is not growing
if (!grow){
body.pop_back();
}
return oldTail;
}
bool Snake::isCollision() const {
const Point& head = body[0];
// Check the collision of the snake with the boundry
if (head.x < 0 || head.x >= gridWidth || head.y < 0 || head.y >= gridHeight){
return true;
}
// Check collision of the snake with itself
for (int i = 1; i < body.size(); ++i){
if (body[i].x == head.x && body[i].y == head.y){
return true;
}
}
return false;
}