Files
snake/src/element.cpp
T

80 lines
2.3 KiB
C++

// Used ptr to take a copy of the head, move head move tail at end of array to previous head position from copy and make the old tail a nullptr
#include "element.hpp"
#include <cstdlib>
#include <ctime>
int _score = 0;
void Point::set_new_point(int row, int col) {
m_row = row;
m_col = col;
}
void Point::set_new_point(Point &point) {
set_new_point(point.m_row, point.m_col);
}
Fruit::Fruit() {
m_point.set_new_point((rand() % ROW), (rand() % COL));
}
void Fruit::get_new_pos(char (&board)[ROW][COL], Head &head) {
int row, col;
if(m_point.m_row == head.m_head.m_row && m_point.m_col == head.m_head.m_col) {
do {
row = (rand() % ROW);
col = (rand() % COL);
} while (board[row][col] != '.');
m_point.set_new_point(row, col);
_score++;
}
}
void get_new_pos(Point* (*board)[COL], Point** segments) {
Point new_point;
new_point.m_row = segments[0]->m_row;
new_point.m_col = segments[0]->m_col;
if (segments[0]->m_direction == -1) {
if (new_point.m_col <= 0) new_point.m_col = COL - 1;
else new_point.m_col--;
} else if (segments[0]->m_direction == 1) {
if (new_point.m_col >= COL - 1) new_point.m_col = 0;
else new_point.m_col++;
} else if (segments[0]->m_direction == -2) {
if (new_point.m_row <= 0) new_point.m_row = ROW - 1;
else new_point.m_row--;
} else if (segments[0]->m_direction == 2) {
if (new_point.m_row >= ROW - 1) new_point.m_row = 0;
else new_point.m_row++;
}
board[segments[0]->m_row][segments[0]->m_col] = nullptr;
segments[0]->m_row = new_point.m_row;
segments[0]->m_col = new_point.m_col;
board[segments[0]->m_row][segments[0]->m_col] = segments[0];
}
bool Body::check_collision(Head &head) {
for(int i = 0; i < m_body.size(); i++) {
if(m_body[i].m_tail_pos.m_row != head.m_head.m_row) continue;
if(m_body[i].m_tail_pos.m_col != head.m_head.m_col) continue;
return true;
}
return false;
}
void Body::check_new_tail() {
if(_score > m_body.size()) m_body.push_back(Tail{});
}
void Body::get_new_pos(Head &head) {
if(m_body.empty()) return;
m_body[0].m_previous_tail_pos.set_new_point(head.m_previous_head);
for (int i = 1; i < m_body.size(); i++) {
m_body[i].m_previous_tail_pos.set_new_point(m_body[i - 1].m_tail_pos);
}
for (int i = 0; i < m_body.size(); i++) {
m_body[i].m_tail_pos.set_new_point(m_body[i].m_previous_tail_pos);
}
}