I'm trying to make my first game and I'm having issues creating a gameboard. I want to make a 3x3 matrix from user input string. I'm still beginner and I'm very stuck with this.
I dont know how I could get this 3x3 matrix in the right place, see the comments before and after the code, there you can see how the gameboard should look like and how it looks in my code.
I would really appreciate if someone knows how this should be done. Thank you a lot.
/* Gameboard should look like this when input is "1 1 4 2 1 4 2 3 5":
=============
| | 1 2 3 |
-------------
| 1 | 1 1 4 |
| 2 | 2 1 4 |
| 3 | 2 3 5 |
=============
*/
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
using Board = std::vector<vector<int>>;
const unsigned int BOARD_SIDE = 3;
const unsigned char EMPTY = ' ';
void initBoard(Board& board) { // start questions vector formation
while (true) {
cout << "Select start (R for random, I for input): ";
string start;
cin >> start;
if (start == "i" or start == "I") {
cout << "Input: ";
string input = "";
cin.ignore();
getline(cin, input);
istringstream is { input };
vector<vector<int>> board(3, vector<int>(3)); // board is now 2D vector including 9 user input values
for (auto& row : board)
{
for(auto& column : row)
{
is >> column;
}
}
for(const auto& row : board)
{
for (const auto column : row)
{
cout << column << " ";
}
cout << "\n";
}
break;
}
}
}
void printBoard(const Board& board)
{
// prints a board vector whose elements are vectors
cout << "=============" << endl;
cout << "| | 1 2 3 |" << endl;
cout << "-------------" << endl;
for(unsigned int row = 0; row < BOARD_SIDE; row)
{
cout << "| " << row 1 << " | ";
for(unsigned int column = 0; column < BOARD_SIDE; column)
{
if(board.at(row).at(column) == 0)
{
cout << EMPTY << " ";
}
else
{
cout << board.at(row).at(column) << " ";
}
}
cout << "|" << endl;
}
cout << "=================" << endl;
}
int main()
{
Board board;
initBoard(board);
printBoard(board);
}
/* But it looks like this:
1 1 4
2 1 4
2 3 5
=============
| | 1 2 3 |
-------------
*/
CodePudding user response:
The following line in your initBoard
function is the problem:
vector<vector<int>> board(3, vector<int>(3)); // board is now 2D vector including 9 user input values
This declares a new local variable that is also called "board", and all subsequent interactions are to this local variable. This effectively leaves the passed in board
as empty, which is why at
crashes with an std::out_of_range exception.
Instead, initialize board
properly in your main
function:
int main()
{
Board board(3, vector<int>(3)); // board is now 2D vector including 9 user input values
initBoard(board);
printBoard(board);
}
CodePudding user response:
The matrix is well constructed but you get an "out of range" error when printing and the code stops. Try switching to regular array for yout game.