-
Notifications
You must be signed in to change notification settings - Fork 0
/
new.cpp
142 lines (116 loc) · 3.02 KB
/
new.cpp
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
#include <SDL2/SDL.h>
#include <deque>
#include <vector>
#include <algorithm>
int main()
{
SDL_Init(SDL_INIT_EVERYTHING);
auto window = SDL_CreateWindow(
"Snake Game",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
1000,
1000,
0
);
auto renderer = SDL_CreateRenderer(
window,
-1,
0
);
SDL_Event e;
bool running = true;
int dir = 0;
SDL_Rect head {
500,
500,
10,
10
};
// Snake Body Container
std::deque<SDL_Rect> rq;
// int size = 1;
//apples Container
std::vector<SDL_Rect> apples;
for (int i = 0; i < 100; i++)
{
apples.emplace_back(rand()%100*10, rand()%100*10, 10, 10);
}
enum Direction
{
DOWN,
LEFT,
RIGHT,
UP
};
int size=1;
while(running)
{
// Check Input
while(SDL_PollEvent(&e))
{
if(e.type == SDL_QUIT)
{
running = false;
}
if(e.type == SDL_KEYDOWN)
{
if(e.key.keysym.sym == SDLK_DOWN) { dir = DOWN;}
else if(e.key.keysym.sym == SDLK_LEFT) { dir = LEFT;}
else if(e.key.keysym.sym == SDLK_UP) { dir = UP;}
else if(e.key.keysym.sym == SDLK_RIGHT) { dir = RIGHT;}
}
}
// Move
switch (dir)
{
case DOWN:
head.y += 10; break;
case UP:
head.y -= 10; break;
case LEFT:
head.x -= 10; break;
case RIGHT:
head.x += 10; break;
}
// Collision Detection with apples
std::for_each(apples.begin(), apples.end(), [&](auto &apple)
{
if(head.x == apple.x && head.y == apple.y)
{
size += 10;
apple.x = -10;
apple.y = -10;
}
});
// Collision detection with snake body
std::for_each(rq.begin(), rq.end(), [&](auto& snake_segment)
{
if(head.x == snake_segment.x && head.y == snake_segment.y)
{
size = 1;
}
});
// Add newest head to the snake
rq.push_front(head);
while(rq.size() > size)
rq.pop_back();
// Clear Window
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
//Draw apples
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
std::for_each(apples.begin(), apples.end(), [&](auto& apple){
SDL_RenderFillRect(renderer,&apple);
});
// Draw Body
SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);
std::for_each(rq.begin(), rq.end(), [&](auto& snake_segment){
SDL_RenderFillRect(renderer,&snake_segment);
});
SDL_RenderFillRect(renderer, &head);
SDL_RenderPresent(renderer);
SDL_Delay(25);
}
return 0;
}