I'm trying to make a Tic Tac Toe game in C++ and I have a problem I've been stuck on for 6 days (ahhh!)
I get an "vector subscript is out of range" error.
Edit: here's my mre hope it helps
Edit: It says that "vector subscript is out of range." Does that help?
Edit: I edited the code. It's COMPLETELY different, but it gives the same error and I'm pretty sure it's the same thing. If you solve this, you'll solve the other problem.
tictactoe.cpp:
#include "engine.h"
int main()
{
Engine engine;
while (engine.getRunning() == true)
{
engine.input();
engine.update();
engine.draw();
}
return 0;
}
engine.h
#include "grid.h"
class Engine
{
private:
sf::RenderWindow window;
sf::VideoMode vm;
bool running = true;
Grid grid;
public:
Engine() : grid(95.f, 95.f, 3)
{
vm.width = 600, vm.height = 400;
window.create(vm, "thing");
}
bool getRunning()
{
return running;
}
// input
void update()
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed || event.key.code == sf::Keyboard::Escape)
{
window.close();
running = false;
}
if (event.type == sf::Event::MouseButtonPressed)
{
if (event.mouseButton.button == sf::Mouse::Left)
{
sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
sf::Vector2f mousePositionFloat(static_cast<float>(mousePosition.x),
static_cast<float>(mousePosition.y));
const sf::FloatRect& node1 = grid.getNode(0, 0);
if (node1.contains(mousePositionFloat))
{
window.close();
}
}
}
}
}
// draw
};
grid.h:
#include <vector>
#include <SFML/Graphics.hpp>
class Grid
{
private:
std::vector<sf::FloatRect> nodes;
std::vector<std::vector<int>> grid;
sf::Vector2f currPos;
float nodeWidth, nodeHeight;
int nodesPerRow;
int currentRow, currentColumn;
public:
Grid(float width, float height, int perRow) :
currPos(0.f, 0.f), nodeWidth(width), nodeHeight(height),
nodesPerRow(perRow), currentRow(0), currentColumn(0) {}
const sf::FloatRect& getNode(int row, int col) const {
int index = row * nodesPerRow + col;
return nodes[index];
}
};
I included some stuff like draw and input so that it makes sense like as a game. Kinda like for context.
Please tell me if I need to add (or delete) anything and please be nice, I know it's none of your business but as you can imagine this is stressing me out.
Edit: I don't know why the subscript would be out of range.