This commit is contained in:
DarthMooMancer
2025-11-13 23:15:52 -05:00
parent 9eb93dc691
commit 59c68b7bd3
2 changed files with 19 additions and 19 deletions
+3 -1
View File
@@ -1,6 +1,7 @@
#ifndef ENGINE_HPP
#define ENGINE_HPP
#include <string>
#include <vector>
constexpr int ROW = 11;
@@ -31,7 +32,8 @@ public:
private:
Window win;
std::vector<vec2> buf;
std::vector<vec2> tail;
std::string status;
vec2 head { COL / 2, ROW / 2 };
vec2 fruit { rand() % COL, rand() % ROW };
vec2 prev_head { head.x, head.y };
+16 -18
View File
@@ -2,9 +2,9 @@
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <format>
#include <ncurses.h>
#include <ranges>
#include <iostream>
#include <thread>
#include <chrono>
@@ -38,9 +38,7 @@ Engine::Engine() {
nodelay(stdscr, true);
}
Engine::~Engine() {
endwin();
}
Engine::~Engine() { endwin(); }
void Engine::run() {
while (exit_summary() && process_input()) {
@@ -48,10 +46,14 @@ void Engine::run() {
determine_index_zero_pos();
move_tail_indicies();
win.update_display(head, fruit, buf);
win.update_display(head, fruit, tail);
win.draw_display();
std::this_thread::sleep_for(std::chrono::milliseconds((int) (200)));
}
nodelay(stdscr, false);
mvprintw(12, 0, status.c_str());
refresh();
getch();
}
bool Engine::process_input() {
@@ -67,15 +69,11 @@ bool Engine::process_input() {
}
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(tail.size() >= ROW * COL) {
return status = std::format("You filled the whole board and won! Score: {}\n", m_score), 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;
if(std::any_of(tail.begin(), tail.end(), [&](const vec2& segment) { return segment == head; })) {
return status = std::format("You collided with yourself and died! Score: {}\n", m_score), false;
}
return true;
}
@@ -90,17 +88,17 @@ void Engine::determine_index_zero_pos() {
}
void Engine::move_tail_indicies() {
if(buf.empty()) return;
buf.pop_back();
buf.insert(buf.begin(), prev_head);
if(tail.empty()) return;
tail.pop_back();
tail.insert(tail.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; }));
while (new_pos == head || std::any_of(tail.begin(), tail.end(), [&](const vec2& seg) { return seg == new_pos; }));
fruit = new_pos;
buf.insert(buf.begin(), vec2 { ROW, COL });
tail.insert(tail.begin(), vec2 { ROW, COL });
m_score++;
}