I'm making a TicTacToe game in C++ after watching Coding Train make it in his video using JavaScript. I'm not new to programming but I'm new to C++.
The problem arose when I tried to change a 2D char variable.
#include <iostream>
#include <string>
#include <vector>
constexpr unsigned int board_x = 3, board_y = 3;
const std::string divider = "--------------------------------------------------";
char board[board_x][board_y]
{
{'-', '-', '-'},
{'-', '-', '-'},
{'-', '-', '-'}
};
std::vector<std::string> available_locations{ "A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3" };
bool is_location_valid(const std::string&);
void change_board(std::string, unsigned short);
void print_available_locations();
void print_board();
void switch_turn(unsigned short&);
void take_turn(unsigned short&, std::string&);
int main()
{
unsigned short player_turn = 1;
std::string user_input;
print_available_locations();
take_turn(player_turn, user_input);
}
bool is_location_valid(const std::string& input)
{
for (std::string& available_location : available_locations)
{
if (available_location == input) return true;
}
std::cout << "Unknown location" << std::endl << std::endl;
return false;
}
void change_board(std::string input, const unsigned short player_turn)
{
if (input.find('A') == 0) input[0] = '1';
else if (input.find('B') == 0) input[0] = '2';
else if (input.find('C') == 0) input[0] = '3';
board[static_cast<int>(input[0]) - 1][static_cast<int>(input[1]) - 1] = player_turn == 1 ? 'X' : 'O';
}
void print_available_locations()
{
std::cout << "Available location: ";
for (unsigned int i = 0; i < available_locations.size(); i++)
{
if (i != available_locations.size() - 1) std::cout << available_locations[i] << ", ";
else std::cout << available_locations[i] << ".\n";
}
}
void print_board()
{
for (char(&i)[3] : board)
{
for (char j : i)
{
std::cout << j << "\t";
}
std::cout << std::endl;
}
}
void switch_turn(unsigned short& player_turn)
{
switch (player_turn)
{
case 1:
player_turn = 2;
break;
case 2:
player_turn = 1;
break;
default:
player_turn = 1;
break;
}
}
void take_turn(unsigned short& player_turn, std::string& user_input)
{
do
{
std::cout << "Player " << player_turn << ", enter board location...\n";
std::getline(std::cin, user_input);
} while (!is_location_valid(user_input));
change_board(user_input, player_turn);
print_board();
std::cout << divider << std::endl;
switch_turn(player_turn);
}
I don't know why but board[static_cast<int>(input[0]) - 1][static_cast<int>(input[1]) - 1] = player_turn == 1 ? 'X' : 'O'; doesn't seem to change the board variable on top. What should I add or change to make it work?
Aucun commentaire:
Enregistrer un commentaire