Here is my little snake game which I made in c++ using the SFML library. The game is very simple. I have also included a screenshot of how the GUI looks. The files which I am loading are 30x30 colored squares. Yellow is the background. Red represents the snake. White is the cherry/fruit/prize to increase the size of the snake
#include<SFML/graphics.hpp>
#include<windows.h>
using namespace sf;
struct position{
int x;
int y;
}snake[200];
char direction = 'r';
int length = 2;
void update(){
for(int i = length-1;i > 0;i--){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
if (direction == 'u') snake[0].y-=1;
else if (direction == 'd') snake[0].y+=1;
else if (direction == 'r') snake[0].x+=1;
else if (direction == 'l') snake[0].x-=1;
}
int fruitx = 5;
int fruity = 5;
void genrand(){
int rx = rand() % 20;
int ry = rand() % 20;
fruitx = rx;
fruity = ry;
}
int main(){
snake[0].x = 5;
snake[0].y = 5;
RenderWindow window(VideoMode(620,620),"Snake c++");
Texture t;
Texture t2;
Texture t3;
t3.loadFromFile("images/green.png");
t2.loadFromFile("images/red.png");
t.loadFromFile("images/yellow.png");
Sprite bg(t);
Sprite sn(t2);
Sprite fruit(t3);
const int size = 31;
while(window.isOpen()){
Event e;
while(window.pollEvent(e)){
if(e.type == Event::Closed)
window.close();
if(e.type == Event::KeyPressed){
if(e.key.code == Keyboard::Key::Up && direction != 'd') direction = 'u';
else if(e.key.code == Keyboard::Key::Down && direction != 'u') direction = 'd';
else if(e.key.code == Keyboard::Key::Left && direction != 'r') direction = 'l';
else if(e.key.code == Keyboard::Key::Right && direction != 'l') direction = 'r';
}
}
Sleep(60);
update();
window.clear();
for(int i = 0;i < 20;i++){
for(int j = 0;j < 20;j++){
bg.setPosition(i*size,j*size);
window.draw(bg);
}
}
for(int i = 0;i < length;i++) {
if (snake[i].x < 0) snake[i].x+=20;
if (snake[i].x > 19) snake[i].x-=20;
if (snake[i].y < 0) snake[i].y+=20;
if (snake[i].y > 19) snake[i].y-=20;
sn.setPosition(snake[i].x*size,snake[i].y*size);
if (i != 0){
if(snake[i].x == snake[0].x && snake[i].y == snake[0].y)
length = 2;
}
if (snake[i].x == fruitx && snake[i].y == fruity){
length+=1;
genrand();
fruit.setPosition(fruitx*size,fruity*size);
}
window.draw(sn);
}
window.draw(fruit);
window.display();
}
return 0;
}
The snake is represented by an array of position
objects.
When I detect any collision I just reset the length of the snake.