Files
snake/src/engine.cpp
T
2025-11-07 10:51:43 -05:00

107 lines
2.8 KiB
C++

#include <engine.hpp>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <ncurses.h>
#include <ranges>
#include <iostream>
#include <thread>
#include <chrono>
void Window::draw_display() {
for(int i : std::ranges::views::iota(0, ROW)) {
for(int j : std::ranges::views::iota(0, COL)) {
mvaddch(i, j * 2, view[i][j]);
}
}
refresh();
}
void Window::update_display(vec2 &head, vec2 &fruit, std::vector<vec2> &buf) {
for(auto& row : view) row.fill('.');
view[head.y][head.x] = '*';
view[fruit.y][fruit.x] = 'o';
for(const auto& segment : buf) {
if(segment.x < COL && segment.y < ROW) {
view[segment.y][segment.x] = '~';
}
}
}
Engine::Engine() {
std::srand(std::time(0));
initscr();
cbreak();
noecho();
curs_set(0);
nodelay(stdscr, true);
}
Engine::~Engine() {
endwin();
}
void Engine::run() {
while (exit_summary() && process_input()) {
add_tail_and_respawn_fruit();
determine_index_zero_pos();
move_tail_indicies();
win.update_display(head, fruit, buf);
win.draw_display();
std::this_thread::sleep_for(std::chrono::milliseconds((int) (200)));
}
}
bool Engine::process_input() {
int ch;
while((ch = getch()) != ERR) {
if(ch == 'q') { return false; }
else if(ch == 'w') { if(dir != Direction::DOWN) dir = Direction::UP; }
else if(ch == 's') { if(dir != Direction::UP) dir = Direction::DOWN; }
else if(ch == 'd') { if(dir != Direction::LEFT) dir = Direction::RIGHT; }
else if(ch == 'a') { if(dir != Direction::RIGHT) dir = Direction::LEFT; }
}
return true;
}
bool Engine::exit_summary() {
if(buf.size() >= ROW * COL) {
std::cout << "You filled the whole board and won! Score: " << m_score << "\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
return false;
}
if(std::any_of(buf.begin(), buf.end(), [&](const vec2& segment) { return segment == head; })) {
std::cout << "You collided with yourself and died! Score: " << m_score << "\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
return false;
}
return true;
}
void Engine::determine_index_zero_pos() {
prev_head.set(head.x, head.y);
if(dir == Direction::LEFT) { head.x = (head.x + COL - 1) % COL; }
else if(dir == Direction::RIGHT) { head.x = (head.x + 1) % COL; }
else if(dir == Direction::UP) { head.y = (head.y + ROW - 1) % ROW; }
else if(dir == Direction::DOWN) { head.y = (head.y + 1) % ROW; }
}
void Engine::move_tail_indicies() {
if(buf.empty()) return;
buf.pop_back();
buf.insert(buf.begin(), prev_head);
}
void Engine::add_tail_and_respawn_fruit() {
if(fruit != head) return;
vec2 new_pos { 0, 0 };
do { new_pos.set((rand() % ROW), (rand() % COL)); }
while (new_pos == head || std::any_of(buf.begin(), buf.end(), [&](const vec2& seg) { return seg == new_pos; }));
fruit = new_pos;
buf.insert(buf.begin(), vec2 { ROW, COL });
m_score++;
}