fruits + deaths

This commit is contained in:
Pedro Costa 2020-02-13 11:10:28 +00:00
parent 347ece1f7d
commit 297095a166

View File

@ -1,5 +1,5 @@
#define BOARD_LENGTH 8 #define BOARD_LENGTH 8
#define SNAKE_MAX_SIZE 12 #define SNAKE_MAX_SIZE 32
struct pair { struct pair {
int x; int x;
@ -12,11 +12,14 @@ private:
int snake_size; int snake_size;
pair pos[64]; pair pos[64];
pair get_next_move(pair p); pair get_next_move(pair p);
pair fruitPos;
bool fruit;
public: public:
Snake() { Snake() {
this->state = 'U'; this->state = 'U';
this->snake_size = 4; this->snake_size = 4;
fruit = false;
for (int i = snake_size - 1; i >= 0; i--) { for (int i = snake_size - 1; i >= 0; i--) {
pair p; pair p;
p.x = 5; p.x = 5;
@ -44,11 +47,36 @@ public:
pair p = pos[i]; pair p = pos[i];
pixels[p.x][p.y] = LOW; // TURN ON PIXELS OF SNAKE pixels[p.x][p.y] = LOW; // TURN ON PIXELS OF SNAKE
} }
if(fruit)
pixels[fruitPos.x][fruitPos.y] = LOW;
} }
void next_move();
pair snake_head() { pair snake_head() {
return pos[0]; return pos[0];
} }
void generate_fruit() {
if(!fruit) {
fruit = true;
fruitPos.x = random(7);
fruitPos.y = random(7);
}
}
void next_move() {
for (int i = snake_size; i > 0; i--) {
pos[i] = pos[i - 1];
}
pos[0] = get_next_move(pos[0]);
if (fruit) {
if (pos[0].x == fruitPos.x && pos[0].y == fruitPos.y) {
grow();
fruit = false;
}
}
}
bool eats_itself() {
for(int i = 1; i < snake_size; i++)
if( pos[0].x == pos[i].x && pos[0].y == pos[i].y ) return true;
return false;
}
}; };
pair Snake::get_next_move(pair p) { pair Snake::get_next_move(pair p) {
@ -74,13 +102,6 @@ pair Snake::get_next_move(pair p) {
return r; return r;
} }
void Snake::next_move() {
for (int i = snake_size; i > 0; i--) {
pos[i] = pos[i - 1];
}
pos[0] = get_next_move(pos[0]);
}
void Snake::grow() { void Snake::grow() {
if (snake_size < SNAKE_MAX_SIZE) { if (snake_size < SNAKE_MAX_SIZE) {
pos[snake_size] = pos[snake_size - 1]; pos[snake_size] = pos[snake_size - 1];
@ -124,14 +145,36 @@ void setup() {
} }
void loop() { void loop() {
if(random(50) == 0) snake.grow(); if(random(20) == 0) snake.generate_fruit();
snake.snake_to_matrix(pixels); snake.snake_to_matrix(pixels);
snake.next_move(); snake.next_move();
// draw the screen: // draw the screen:
if(snake.eats_itself()){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 100; j++)
Display();
delay(500);
}
int dead[8][8] = {
{0,1,1,1,1,1,1,0},
{1,0,1,1,1,1,0,1},
{1,1,0,1,1,0,1,1},
{1,1,1,0,0,1,1,1},
{1,1,1,0,0,1,1,1},
{1,1,0,1,1,0,1,1},
{1,0,1,1,1,1,0,1},
{0,1,1,1,1,1,1,0},
};
for(int i = 0; i < 8; i++)
for(int j = 0; j < 8; j++)
pixels[i][j] = dead[i][j];
while(true) Display();
}
for(int i = 0; i < 30; i++) { for(int i = 0; i < 30; i++) {
Display(); Display();
snake.change_state(read_sensors()); snake.change_state(read_sensors());
} }
} }
void readSensors() { void readSensors() {