Wow, many thanks for all the help. I tried to incorporate as much as I can.
First I changed the includes:
#include <list>
#include <ncurses.h>
#include <cstdlib>
#include <ctime>
After that I changed the class to a struct. I didn't know it's possible to have initialization lists in a structure.
Also, I wasn't aware you can use parameters which have got the same name as member variables.
struct snake_point {
int x, y;
snake_point(int x, int y):x(x),y(y) {}
};
Of course I had to change the methods calls, too.
compression! -->
switch( ch ) {
case KEY_UP: y--; break;
case KEY_DOWN: y++; break;
case KEY_RIGHT: x++; break;
case KEY_LEFT: x--; break;
}
-->
y += ch==KEY_UP?1:ch==KEY_DOWN?-1:0;
x += ch==KEY_RIGHT?1:ch==KEY_LEFT?-1:0;
I think I can't use this as is because the source code above would only move the snake when a key is pressed. I have to save the direction somewhere.
So I came up with:
dir = (ch == KEY_UP) ? 1 : (ch == KEY_RIGHT) ? 2 : (ch == KEY_DOWN) ? 3 : (ch == KEY_LEFT) ? 4 : dir;
quit = (ch == 'q') ? true : false;
and
int x = logic.x;
int y = logic.y;
x += (dir == 2) ? 1 : (dir == 4) ? -1 : 0;
y += (dir == 3) ? 1 : (dir == 1) ? -1 : 0;
I think it's always a good idea to split input and logic: Input -> Logic -> Output.
I couldn't have done those improvements and the compression without you, thanks again.
~Flops
EDIT: I sent the changes to github,
https://github.com/FlopsKa/cppNcursesSnake .
EDIT 2: According to cloc.pl it's 61 lines of code. Is it possible to go below 50?