I am working on a school project in C++.
My issue at the moment is with the 'placePiece' function. I can't seem to get it to properly place the char value for the player into the array that represent the game board, it always seems to assign the 'p' (Player) and 'c' (Computer) values to completely random cells within the game board.
Place piece function:
bool placePiece(char** pBoard, int colSize, int rowSize, int columnSelection, char player)
{
char* pRow = pBoard[columnSelection];
for (int j = colSize; j >0; j--){
if(pRow[j] == ' '){
pRow[j] = player;
return true;
}
}
return false;
}
Print board function:
void printBoard(char** pBoard, int colSize, int rowSize){
for(int i = 0; i < rowSize; i++){ //Print the current values of each cell
char* pRow = pBoard[i];
for (int j = 0; j < colSize; j++) {
if(j==0){
std::cout << "|" << pRow[j] << "|";
}else{
std::cout << pRow[j] << "|";
}
}
std::cout << std::endl<<std::endl;
}
}
int main (To put it all together, there is obviously a lot of missing code to fully complete the project that's not included in here because it has no relevance to the issue at hand.)
int main(){
srand (time(NULL));
int32_t connectedPiecesToWin = 0;
int32_t rowSize = 0;
int32_t colSize = 0;
std::cout << "How many connected pieces does it take to win?" << std::endl;
std::cin >> connectedPiecesToWin;
rowSize = connectedPiecesToWin + 2;
colSize = connectedPiecesToWin + 3;
char** pBoard = NULL;
// initialize board
//Assign first dimension
pBoard = new char*[rowSize];
//Assign second dimension
for(int i = 0; i < rowSize; i++){
pBoard[i] = new char[colSize];
char* pRow = pBoard[i];
for(int j=0;j<colSize;j++){
pRow[j] = ' ';
}
}
char player = 'p';
do
{
int columnChoice = 0;
do
{
if (player == 'p')
{
printBoard(pBoard, colSize, rowSize);
std::cout << "Player's column: ";
std::cin >> columnChoice;
}
else
{
// computers turn
columnChoice = rand() % colSize;
}
} while (!placePiece(pBoard, colSize, rowSize, columnChoice, player));
printBoard(pBoard, colSize, rowSize);
return 0;
}
Related
a beginner computer science student here. The main task of the program is to create 3 options for the user, the user will input numbers (how many numbers depends on the user's choice) then arrange the user input to bubble assortment, selection sort, and heapsort, and then the arranged user input will then be turned to a 2D array.
The problem is I am stuck on turning 1D array to a 2D array. How do I copy my 1D array and place the contents of it onto the 2D array? I have tried various codes and tutorials online and it still doesn't work on my code.
Also should I try getting user input, turning it to 2D array, and then arranging it to bubble, selection, and heapsort? Would that be easier? Thanks.
Here is the output of the program:
#include <iostream>
#include <iomanip>
using namespace std;
int i;
const int sizeRow = 4;
const int sizeCol = 5;
int row, col;
int list[20];
char getMenu(char and);
void getOutput(int list[], int dim);
void getInput(int list[], int dim);
void getBubble(int list[], int dim);
void getBubbleDown(int list[], int dim);
void convert2DimSort(int xlist[][sizeCol]);
void get2Dout(int xlist[][sizeCol]);
int main() {
int sagot;
char ans;
int choice;
string ide;
bool yn = 0;
do {
sagot = getMenu(ans);
cin >> and;
switch (ans) {
case '1': // bubble sort
{
int dim = 20;
int list[dim];
int xlist[sizeRow][sizeCol];
int newlist[sizeRow][sizeCol];
getInput(list, dim);
getBubbleDown(list, dim);
newlist[sizeRow][sizeCol] = list[dim];
convert2DimSort(newlist);
break;
}
case '2': // convert2dimsort
{
int dim = 20;
int list[dim];
getInput(list, dim);
break;
}
case '3': // heapsort
{
int dim = 10;
int list[dim];
getInput(list, dim);
break;
}
case '4': {
cout << "bye bitch";
return 0;
}
}
cout << endl << "try again? y/n: ";
cin >> ide;
if (ide == "y") {
yn = 1;
} else {
yn = 0;
}
} while (yn == 1);
return 0;
}
char getMenu(char ans) {
cout << "-----SORTING-----" << endl
<< "[1] BUBBLE SORT" << endl
<< "[2] SELECTION SORT" << endl
<< "[3] HEAP SORT" << endl
<< "[4] QUIT" << endl
<< endl
<< "----------" << endl
<< "Enter your choice: ";
}
void getInput(int list[], int dim) {
cout << "enter number: " << endl;
for (int i = 0; i < dim; i++) {
cout << "loc[" << i << "] ";
cin >> list[i];
}
}
// used as a tester
void getOutput(int list[], int dim) {
for (int i = 0; i < 20; i++) {
cout << list[i] << " ";
list[dim];
}
}
void getBubble(int list[], int dim) {
int j;
int temp;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < (20 - i - 1); j++) {
if (list[j] < list[j + 1]) {
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
// not used yet
void getBubbleDown(int list[], int dim) {
int j;
int temp;
for (int i = 0; i < 20; i++) {
for (int j = 0; j < (20 - i - 1); j++) {
if (list[j] < list[j + 1]) {
int temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
}
void convert2DimSort(int xlist[][sizeCol]) {
int index = 0;
for (row = 0; row < sizeRow; row++) {
for (col = 0; col < sizeCol; col++) {
xlist[row][col] = list[index++];
}
}
for (row = 0; row < sizeRow; row++) {
for (col = 0; col < sizeCol; col++) {
cout << setw(7) << xlist[row][col];
}
}
}
First of all you cannot use and as a variable name in char getMenu(char and);, since it is a keyword.
From what i can understand, your convert2DimSort is taking a 2D array input. There should be no need for that unless you are going to be using its reference value.
Other then that it looks like it should work.
So just to be clear is the problem that you are not able to compile the problem or that you're getting wrong output? Because for me here it doesn't even compile.
I am running project called Horse Board Game. When it got almost done, it happened an error at the end of the execution part. The error is:
Run-Time Check Failure #2 - Stack around the variable 'board' was corrupted.
Where is the mistake here? Everything seems to work properly, only that error occurs.
#include <iostream>
#include <ctime>
#include <Windows.h>
using namespace std;
void printHorizontalLine(int size) {
for (int i = 0; i < size; i++) {
cout << " -----------";
}
cout << "\n";
}
void printVerticalLine(int size) {
cout << "|";
for (int i = 0; i < size; i++) {
cout << " |";
}
cout << "\n";
}
void displayBoard(int size, char board[50][50]) {
for (int i = 0; i < size; i++) {
printHorizontalLine(size);
printVerticalLine(size);
cout << "|";
if (i % 2 == 0) {
for (int j = 0; j < size; j++) {
cout << " " << board[i][j] << " |";
}
}
else {
for (int j = size - 1; j >= 0; j--) {
cout << " " << board[i][j] << " |";
}
}
cout << "\n";
printVerticalLine(size);
}
printHorizontalLine(size);
}
void init_board(char board[50][50], int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
board[i][j] = ' ';
}
}
}
void enteringPlayerName(char name[], int n) {
for (int i = 0; i < n; i++) {
cout << "Player " << i + 1 << " enter name: " << "\n";
cin >> name[i];
}
}
void beginningPos(int n, int pos[]) {
for (int i = 0; i < n; i++) {
pos[i] = -1;
}
}
void rollDice(int max, char board[50][50], int pos[], char name[], int size, int n, int cur) {
int step = rand() % max + 1;
cout << name[cur] << " roll " << step << "\n";
if (step + pos[cur] > size * size - 1) {
cout << "Cannot move forward\n";
}
else {
pos[cur] += step;
for (int i = 0; i < n; i++) {
if ((pos[cur] == pos[i]) && (i != cur)) {
pos[i] = -1;
cout << name[i] << " is kicked to the Start!!\n";
}
}
}
}
void updatingBoard(char board[50][50], char name[], int pos[], int n, int size) {
init_board(board, size);
for (int k = 0; k < n; k++)
{
int x, i, j;
x = pos[k];
i = x / size;
j = x % size;
board[i][j] = name[k];
}
}
char playGame(int max, int n, int size, char board[50][50], int pos[], char name[], int finish_point) {
char winner = ' ';
int cur_turn = 0;
while (winner == ' ') {
rollDice(max, board, pos, name, size, n, cur_turn % n);
updatingBoard(board, name, pos, n, size);
displayBoard(size, board);
if (pos[cur_turn % n] == finish_point) winner = name[cur_turn % n];
cur_turn++;
}
return winner;
}
int main() {
int size, n;
cin >> size;
cin >> n;
const int MAX = 50;
int max = 3;
int pos[200];
char name[10];
char winner = ' ';
char board[MAX][MAX];
int finish_point = size * size - 1;
srand(time(0));
enteringPlayerName(name, n);
init_board(board, size);
beginningPos(n, pos);
winner = playGame(max, n, size, board, pos, name, finish_point);
if (winner == ' ') cout << "Tie game";
else cout << winner << " is the winner";
return 0;
}```
When I set size to 4 and n to 2 as recommended in the comments section, then the line
board[i][j] = name[k];
in the function updatingBoard causes a buffer underflow.
The first time that line is executed, i has the value 0 and j has the value 0, which is ok, but the second time that line is executed, i has the value 0 but j has the value -1. This is obviously wrong, because board[0][-1] is accessing the array out of bounds.
That is the reason for the error message that you are receiving.
You can easily see this by running your program line by line in a debugger.
I have changed a Tic-Tac-Toe program from using a normal 3x3 grid to a grid-size chosen by the user (between 3 and 9). I am using a global constant 'SIZE' to hold the value the user chooses. My issue is adapting my winMove(); function so that it adjusts to check for the winning move based on the current board size chosen by the user(SIZE). I have tried different loops but can't get it to work. Right now it will only work with a 3x3 board.
I am still learning c++ and I have been stuck on this for a few days so I'm hoping a friendly person can help. This is my full program so far, hope it's not too much of a mess!
#include <iostream>
using namespace std;
struct TicTacToe
{
char **board;
};
void makeBoard(TicTacToe&);
void deallocBoard(TicTacToe&);
void printBoard(TicTacToe);
bool isDraw(TicTacToe);
void convertInput(char, char, int&, int&);
char winMove(TicTacToe, int, int);
bool validateSIZE(int);
int SIZE = 1;
int main(){
while(SIZE < 3 || SIZE > 9)
{
cout << "Enter number between 3 and 9 for the length of board.\n";
cout << "Example: 4 will make a board with 4 rows and 4 columns: ";
cin >> SIZE;
validateSIZE(SIZE);
}
TicTacToe game;
makeBoard(game);
char winner = 0;
char turn = 'X';
char rowIn, colIn;
int row, column;
while(!winner && !isDraw(game))
{
printBoard(game);
cout << "\nPlayer " << turn << "'s move (input format: a1): ";
cin >> rowIn >> colIn;
convertInput(rowIn, colIn, row, column);
if (game.board[row][column]==' ')
{
game.board[row][column] = turn;
if (turn == 'X')
{turn = 'O';}
else
{turn = 'X';}
winner = winMove(game, row, column);
}
else
cout << "Taken, try again!\n";
}
printBoard(game);
if (winner == 'X' || winner == 'O')
{cout << " Congrats, the winner is " << winner << '.' << endl;}
else
{cout << " Game ends in a draw." << endl;}
cout << endl << "Game Over!" << endl << endl;
deallocBoard(game);
return 0;
}
// Need help with this function.
char winMove(TicTacToe gameIn, int i, int j)
{
//row win
if (gameIn.board[i][0]==gameIn.board[i][1] &&
gameIn.board[i][0]==gameIn.board[i][2])
{
return gameIn.board[i][j];
}
//column win
if (gameIn.board[0][j]==gameIn.board[1][j] &&
gameIn.board[0][j]==gameIn.board[2][j])
{
return gameIn.board[i][j];
}
//left diagonal win
if (gameIn.board[0][0] != ' ' &&
gameIn.board[0][0] == gameIn.board[1][1] &&
gameIn.board[0][0] == gameIn.board[2][2])
{
return gameIn.board[i][j];
}
//right diagonal win
if (gameIn.board[0][2] != ' ' &&
gameIn.board[0][2] == gameIn.board[1][1] &&
gameIn.board[0][2] == gameIn.board[2][0])
{
return gameIn.board[i][j];
}
return 0;
}
bool validateSIZE(int SIZE)
{
if(SIZE < 3 || SIZE > 9)
{
cout << "\n\nNumber must be between 3 and 9!\nTry again!\nPlease ";
return false;
}
return true;
};
void makeBoard(TicTacToe& gameIn)
{
gameIn.board = new char*[SIZE];
for(int i = 0; i < SIZE; i++)
{gameIn.board[i] = new char[SIZE];}
for(int j =0; j < SIZE; j++)
for(int k = 0; k < SIZE; k++)
{gameIn.board[j][k] = ' ';}
}
void deallocBoard(TicTacToe& gameIn)
{
for(int i = 0; i < SIZE; i++)
delete [] gameIn.board[i];
delete [] gameIn.board;
gameIn.board = NULL;
}
void printBoard(TicTacToe gameIn)
{
int temp = 1;
cout << " ";
while(temp < SIZE + 1)
{
cout << temp << " ";
temp++;
}
temp = 1;
cout << endl;
for(int i = 0; i < SIZE; i++)
{
cout << char(i + 'a') << '|';
for(int j = 0; j < SIZE; j++)
{
cout << gameIn.board[i][j] << '|';
}
cout << endl;
}
}
bool isDraw(TicTacToe gameIn)
{
bool full = true;
for(int i = 0; full && i < SIZE; i++)
for(int j = 0; full && j < SIZE; j++)
full = gameIn.board[i][j] != ' ';
return full;
}
void convertInput(char rowIn, char colIn, int& row, int& column)
{
row = toupper(rowIn) - 'A';
column = colIn - '1';
}
You can easily use 2 for loops to iterate every starting point and its direction to preform victory checking. Something that would look like this:
// hor ver diagonals
// dx[4] = {1, 0, 1, 1};
// dy[4] = {0, 1, 1, -1};
// check horizontal win
for(int i = 0; i < SIZE; ++i)
{
bool win = true;
for(int j = 1; j < SIZE; ++j)
{
if(gameIn.board[j][i] != gameIn.board[j - 1][i])
{
win = false;
break;
}
}
if(win == true){return ;}
}
// check vertical win
.
.
.
// check diagonal 1 win
for(int i = 1; i < SIZE; ++i)
{
if(gameIn.board[i][i] != gameIn.board[i - 1][i - 1])
break;
if(i == SIZE - 1)return ;
}
// check diagonal 2 win
for(int i = 1; i < SIZE; ++i)
{
if(gameIn.board[i][SIZE - i - 1] != gameIn.board[i - 1][SIZE - i])
break;
if(i == SIZE - 1)return ;
}
I'll leave the vertical win for you.
I did the same question a while ago, but It got closed. I'll try to express myself better this time.
I want to make an algorithm that can solve a sudoku puzzle, looks like It is working, but in the backtracking part(where I need to go back to a previous recursion to test a different value), It doesn't, showing a "segment fault" error.
Also, I use "0" as a blank space, so that's why "if (!board[i][j]) //do something"
// Solves the game
vector<vector<int>> sudokuSolver(vector<vector<int>> board) {
if (isFull(board)) {
return board;
}
bool found = false;
int line = 0;
int col = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) {
line = i;
col = j;
found = true;
break;
}
}
if (found) break;
}
vector<int> possibleNumbers = possibilities(board, line, col);
cout << '\n';
printBoard(board);
cout << '\n';
cout << line << ' ' << col << '\n';
cout << '\n';
printVector(possibleNumbers);
int size = possibleNumbers.size();
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
cout << k << '\n';
sudokuSolver(board);
// the code doesn't pass to the next cout. Why?
cout << "it doesn't reach here :/" << '\n';
}
cout << "backtracking!!" << '\n';
board[line][col] = 0;
cout << "agora:" << '\n';
printBoard(board);
}
I put some "couts" to help me visualize the problem. The "backtracking!!" cout is working properly, but the "it doesn't reach here" cout is not. I thought that, after the code realize It doesn't have possible solutions, It would simply go back to the last recursion, but It's not, giving "segmento fault" error. I don't understand
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
cout << k << '\n';
sudokuSolver(board);
// the code doesn't pass to the next cout. Why?
cout << "it doesn't reach here :/" << '\n';
}
Am I not getting something?
Also, if It's not clear, "isFull" checks if the board is full (base case, game is complete), and possibilities checks the number possibilities of a single cell
Thanks in advance. I guess the details are way better this time, hope I did It right
Edit: The extra couts are ways of showing me where the code is. They are not important for the algorithm itself
Final edit: I did it! Thanks you all. For anyone who wants the full code, here it is:
#include <bits/stdc++.h>
using namespace std;
bool gameRunning = true;
void printBoard(vector<vector<int>> board) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
cout << board[i][j] << ' ';
}
cout << '\n';
}
cout << '\n';
}
void printVector(vector<int> v) {
for (auto x : v) {
cout << x << ' ';
}
cout << '\n';
cout << '\n';
}
// Checks if the board is full, deciding if the game is already won
bool isFull(vector<vector<int>> board) {
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) return false;
}
}
return true;
}
// Generates all number possibilites for a given cell on the board
vector<int> possibilities(vector<vector<int>> board, int i, int j) {
bitset<9> p;
for (int i = 1; i <= 9; i++) {
p[i] = 1;
}
//horizontal check
for (int col = 0; col <= 8; col++) {
if (board[i][col]) {
p[board[i][col]] = 0;
}
}
//vertical check
for (int line = 0; line <= 8; line++) {
if (board[line][j]) {
p[board[line][j]] = 0;
}
}
//mini-square check
int linesquare = (i / 3) * 3;
int colsquare = (j / 3) * 3;
for (int l = linesquare; l <= linesquare + 2; l++) {
for (int c = colsquare; c <= colsquare + 2; c++) {
if (board[l][c]) {
p[board[l][c]] = 0;
}
}
}
vector<int> numberPossibilities;
for (int k = 1; k <= 9; k++) {
if (p[k]) numberPossibilities.push_back(k);
}
return numberPossibilities;
}
// Solves the game
void sudokuSolver(vector<vector<int>> board) {
if (isFull(board)) {
printBoard(board);
gameRunning = false;
}
if (gameRunning) {
bool found = false;
int line = 0;
int col = 0;
for (int i = 0; i <= 8; i++) {
for (int j = 0; j <= 8; j++) {
if (!board[i][j]) {
line = i;
col = j;
found = true;
break;
}
}
if (found) break;
}
vector<int> possibleNumbers = possibilities(board, line, col);
int size = possibleNumbers.size();
for (int k = 0; k < size; k++) {
board[line][col] = possibleNumbers[k];
sudokuSolver(board);
}
board[line][col] = 0;
}
}
int main() {
/*
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
*/
vector<vector<int>> v;
for (int i = 0; i < 9; i++) {
vector<int> hold;
for (int j = 0; j < 9; j++) {
int a;
cin >> a;
hold.push_back(a);
}
v.push_back(hold);
}
cout << '\n';
sudokuSolver(v);
return 0;
}
Bye, have a great day
I'm trying to create a 3x3 sliding tile puzzle game and I made the puzzle in a 2d array and now im trying to get the puzzle to slide a tile.
I'm new to debugging and cannot find out why the program isn't receiving the users input for the slide.
#define SLIDE_UP 1
#define SLIDE_DOWN 2
#define SLIDE_LEFT 3
#define SLIDE_RIGHT 4
void InitializeBoard(int[NUM_ROWS][NUM_COLS]);
void PrintBoard(int[NUM_ROWS][NUM_COLS]);
bool slideTile(int[NUM_ROWS][NUM_COLS], int);
void scrambleBoard(int[NUM_ROWS][NUM_COLS]);
bool isBoardSolved(int[NUM_ROWS][NUM_COLS]);
void DeallocateMemory(int[NUM_ROWS][NUM_COLS]);
int** ppRootPointer = NULL;
int main() {
int slidingBoard[NUM_ROWS][NUM_COLS];
char keyStroke = ' ';
int directionCode = UNSET;
int slideDirection = 0;
InitializeBoard(slidingBoard);
PrintBoard(slidingBoard);
slideTile(slidingBoard,slideDirection);
PrintBoard(slidingBoard);
_getch();
DeallocateMemory(slidingBoard);
return 0;
}
void InitializeBoard(int theBoard[NUM_ROWS][NUM_COLS]) {
ppRootPointer = new(int*[NUM_COLS]);
for (int i = 0; i < NUM_COLS; i++) {
ppRootPointer[i] = new(int[NUM_ROWS]);
}
int counter = 1;
int i = 0, j = 0;
for (i = 0; i < NUM_COLS; i++) {
for (j = 0; j < NUM_ROWS; j++) {
ppRootPointer[i][j] = counter++;
}
}
ppRootPointer[i-1][j-1] = PIVOT;
}
void PrintBoard(int theBoard[NUM_ROWS][NUM_COLS]) {
cout << left;
for (int i = 0; i < NUM_COLS; i++) {
for (int j = 0; j < NUM_ROWS; j++) {
if (ppRootPointer[i][j] != PIVOT) {
cout << setw(3) << ppRootPointer[i][j];
}
else {
cout << setw(3) << (char)PIVOT;
}
}
cout << endl;
}
cout << endl << endl;
}
bool slideTile(int theBoard[NUM_ROWS][NUM_COLS], int slideDirection) {
int pivotRow=0;
int pivotCol=0;
bool slidebool;
//once I declare i and j before the loop they go up to 3 instead of 2
//which causes the loop to not work
int i = 0;
int j = 0;
for (i = 0; i < NUM_COLS; i++) {
for (j = 0; j < NUM_ROWS; j++) {
if (theBoard[i][j] == (char)PIVOT) {
pivotCol = i;
pivotRow = j;
break;
}
}
}
//These are to assign pivotRow and Col because they dont get assigned
//inside of the loop
pivotCol = i;
pivotRow = j;
cout << "please enter a number to slide the tile (1 = up, 2 = down, 3 =
left, 4 = right" << endl;
cin >> slideDirection;
if (slideDirection == SLIDE_UP) {
if (pivotRow + 1 > NUM_ROWS) {
slidebool = false;
}
else {
ppRootPointer[pivotRow + 1][pivotCol] = PIVOT;
ppRootPointer[pivotRow][pivotCol] = ppRootPointer[pivotRow + 1]
[pivotCol];
slidebool = true;
}
}
.I'm hoping for the user to be able to enter an integer 1-4 representing the slide for the tile. This would allow me to build the scramble board function and get closer to finishing the code. Thanks to anyone that reads this and tries to help!!