【发布时间】:2021-03-28 23:31:10
【问题描述】:
在观看 Coding Train 在他的视频中使用 JavaScript 制作 TicTacToe 游戏后,我正在用 C++ 制作 TicTacToe 游戏。我不是编程新手,但我是 C++ 新手。
当我尝试更改 2D char 变量时出现问题。
#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);
}
我不知道为什么,但 board[static_cast<int>(input[0]) - 1][static_cast<int>(input[1]) - 1] = player_turn == 1 ? 'X' : 'O'; 似乎并没有改变顶部的 board 变量。我应该添加或更改什么才能使其正常工作?
【问题讨论】:
-
尝试 (input[0] - '1') 而不是 (static_cast
(input[0]) - 1)
标签: c++ arrays c++11 multidimensional-array char