【发布时间】:2018-08-23 14:40:23
【问题描述】:
我想使用数组和循环在 C++ 中创建一个游戏(连接四个)。
首先我创建了一个 8x5 板。
其次,我提示用户选择从 1 到 6 的列。
当用户选择任一列时,该列的最后一行将从
'.'更改为'X'或'O'。
一切正常,但播放器没有在void TogglePlayer(&player) 中的'X' 和'O' 之间切换
#include <iostream>
#include <iomanip>
using namespace std;
const int rows = 8;
const int columns = 5;
char player = 'X';
//This function creates a 8x5 board
char matrix[rows][columns] = { '.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.',
'.','.','.','.','.' };
//This function displays the board
void display()
{
int width = 3;
cout << setw(width) << "1" << setw(width) << "2" << setw(width) << "3" <<
setw(width) << "4" << setw(width) << "5" << setw(width) << '\n';
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
cout << setw(3) << matrix[i][j] << setw(3);
}
cout << endl;
}
cout << setw(width) << "1" << setw(width) << "2" << setw(width) << "3" << setw(width) << "4" << setw(width) << "5" << setw(width) << '\n';
}
//This the main function that executes the player's selected column
void input(char player)
{
int a;
cout << "Enter the column" << endl;
cin >> a;
if (a > 0 && a < 6)
{
for (int i = 7; i >= 0; i++)
{
if (matrix[i][a - 1] == '.')
{
matrix[i][a - 1] = player;
break;
}
}
}
}
//This function changes the players between 'X' or 'O'
void togglePlayer(char &player)
{
if (player == 'O')
{
player = 'X';
}
else player = 'O';
}
int main()
{
while (true)
{
display();
input(player);
togglePlayer(player);
}
system("pause");
return 0;
}
【问题讨论】:
-
继续盯着下面一行:
for (int i = 7; i >= 0; i++),一直盯着它,直到你看到你的错误。看到后,在 Google 上搜索“未定义的行为”。 -
@SamVarshavchik 当我在
for (int i = 7; i >= 0; i++)上设置断点并执行时,我的程序运行良好,但它没有进入函数TogglePlayer为什么? -
你的
togglePlayer函数对我来说看起来不错,顺便说一句。考虑将您的char player声明移动到 main 中(只需复制/粘贴该行),这样您就有一个效率较低的全局变量,这样就不会混淆全局char player与 togglePlayer 的局部范围char &player -
++一个变量从 7 到 0 需要很长时间。特别是如果您一次调试一行代码。
标签: c++