我想制作一个简单的3个玩家游戏,每个玩家在一个区块中移动,取决于随机函数,每次从1到6个区块,当第一个玩家被移动第二个玩家开始然后然后第三个玩家。为此,我增加了玩家完成移动的阵列rach时间的索引。
我的问题是索引器似乎没有增加,并且即使我增加它也会在播放器1中堆叠。我在C#中有完全相同的代码,它运行良好!
这是C ++中的代码。
int main ()
{
string namesofplayers[] = {"one","two","three"};
int movementofplayers[] = {0,0,0}; // start position of players is
int gamesize = 32; //32 blocks-steps of game
int random;
int y = 0;
a:
y++;
if (y >= 3)
{
y = 0;
}
cout << "it's" << namesofplayers[y] << "turn to play";
int R = (rand() % 6 + 1);
cout << "player " << namesofplayers[y] << " moves to block" << R << endl;
movementofplayers[y] += random;
cout << movementofplayers[y];
if (movementofplayers[y] < gamesize)
{
goto a;
}
else
{
cout << "Player " << namesofplayers[y] << " wins the game" << endl;
}
}
答案 0 :(得分:1)
关于完成工作的机会,我冒昧地编写了一个替代实现,它修复了以前的代码所带来的一些问题,并产生了更多可读输出。我也抛弃了单行,因为它们让我发疯,但这是个人喜好。此外,我倾向于使用适当的范围明确限定标准库中的符号。
摆脱goto
。您可以浏览SO和Web,原因有很多,为什么不使用这样的显式跳转。只需使用循环
修复伪随机数生成器的缺失初始种子。如果您设置了不同的种子,即通过使用某个变量值(例如time(nullptr)
)调用它,您将始终获得相同的“随机”值连续 - 每个 程序调用。
修复变量random
的使用。您尝试将一些垃圾初始化值random
添加到movementofplayers[y]
。有趣的是,g++-4.7
似乎确保变量在用于算术运算之前设置为1
。但是,您需要的正确变量是R
。
从main()
返回明确定义的值。
我希望代码仍能按照您的意图执行:
#include <string>
#include <iostream>
int main ()
{
srand(time(NULL));
std::string namesofplayers[] = {"one","two","three"};
int movementofplayers[] = {0,0,0}; // start position of players is
int gamesize = 32; //32 blocks-steps of game
int y = 1;
while(movementofplayers[y] < gamesize)
{
if (y >= 3)
{
y = 0;
}
std::cout << "it's " << namesofplayers[y] << " turn to play" << std::endl;
int R = (rand() % 6 + 1);
std::cout << "player " << namesofplayers[y] << " moves to block " << R << std::endl;
movementofplayers[y] += R;
std::cout << "movements of player " << namesofplayers[y] <<": " << movementofplayers[y] << std::endl;
y++;
}
std::cout << "Player " << namesofplayers[y] << " wins the game" << std::endl;
return 0;
}
答案 1 :(得分:0)
我会这样做。
为随机数生成器添加了种子,因此您不会每次都获得相同的游戏。
为玩家数量添加了一个常量,以摆脱幻数,并且如果需要,还可以更容易扩展玩家数量。
摆脱了goto。虽然可以以合理的方式使用goto,但它容易被误用,使代码更难以遵循,并使人生气。 :)
我调整了输出并命名了一下,以便让我更容易测试。在这样做的过程中,我纠正了一个问题,即玩家表示玩家移动到阻挡R,这是他们在该回合中的滚动,而不是他们在游戏中的实际位置。
#include <string>
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
std::srand(static_cast<unsigned int>(std::time(0)));
const int gamesize = 32;
const int num_players = 3;
const std::string namesofplayers[num_players] = {"1", "2", "3"};
int movementofplayers[num_players] = {0, 0, 0};
int current_player = 0;
for(;;) //Loop forever, the game logic will exit the loop when a winner is found
{
const int roll = rand() % 6 + 1;
movementofplayers[current_player] += roll;
std::cout << "Player " << namesofplayers[current_player] << " rolls a " << roll << " and moves to block " << movementofplayers[current_player] << std::endl;
//Check if they won and if so, end the game
if(movementofplayers[current_player] >= gamesize)
{
std::cout << "Player " << namesofplayers[current_player] << " wins the game!" << std::endl;
break;
}
current_player = (current_player + 1) % num_players;
}
return 0;
}