我正在制作一个tic tac toe(没有矩阵),我对此有疑问。
说我的输入是“5”:
printf(" 1 | 2 | 3 \n");
printf("___|___|___\n");
printf(" 4 | 5 | 6 \n");
printf("___|___|___\n");
printf(" 7 | 8 | 9 \n");
printf(" | | \n");
printf("\n");
我想要A.I.选择一个随机框,不包括我的“5”输入。我正在做随机的事情:
srand ( time(NULL) );
int randIndex = rand() % 8;
if (movement == 5 && i == 0){
xslot[randIndex] = 'O';
steps = 1;
}
我不知道如何从这个随机选择中排除“5”。
这是我的阵列:
char xslot[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
谢谢
编辑:完整代码:
main()
{
int movimento,passos;
bool passo1=false,passo2=false,passo3=false,passo4=false,passo5=false;
char oslot[9] = "O";
char xslot[] = {'1', '2', '3', '4', '5', '6', '7', '8', '9'};
srand ( time(NULL) );
printf("\n\n");
printf(" 1 | 2 | 3 \n");
printf("___|___|___\n");
printf(" 4 | 5 | 6 \n");
printf("___|___|___\n");
printf(" 7 | 8 | 9 \n");
printf(" | | \n");
printf("\n");
printf("Digite o numero do seu movimento:");
for(int i =0;i<5;i++){
scanf("%i",&movimento);
if (movimento == 1){
xslot[0] = 'X';
} else if (movimento == 2){
xslot[1] = 'X';
} else if (movimento == 3){
xslot[2] = 'X';
} else if (movimento == 4){
xslot[3] = 'X';
} else if (movimento == 5){
xslot[4] = 'X';
} else if (movimento == 6){
xslot[5] = 'X';
} else if (movimento == 7){
xslot[6] = 'X';
} else if (movimento == 8){
xslot[7] = 'X';
} else if (movimento == 9){
xslot[8] = 'X';
}
//INTELIGENCIA ARTIFICIAL
int randIndex = rand() % 8;
if (movimento == 5 && i == 0){
xslot[randIndex] = 'O';
passos = 1;
}
答案 0 :(得分:1)
使用具有可用选择的数组,并在每次选择选择时“缩小”它:
size_t numSelections = 9;
int selections [] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
while (numSelections > 0) {
size_t const next = rand() % numSelections;
--numSelections;
// move selected selection out of valid array range
int const selection = selections [next];
selections [next] = selections [numSelections];
printf("Selected %d\n", selection);
}
每次选择一个值时,都会将其“移出”数组的有效范围,将(未选中,但现在超出范围)值移回有效数组范围:
1 2 3 4|
;; select the 3, shrink valid range
1 2 3|4
;; move 3 out, bring 4 back in
1 2 4|x
在上面的示例中,选择是随机发生的,但您可以轻松地将其修改为 - 例如 - 在随机选择和用户指导选择之间切换以实现您的游戏
答案 1 :(得分:0)
你不必删除它,你只需要忽略它
int randIndex
while( (randIndex = rand() % 9) != 4 );
您还应检查该职位是否有效,并且您应该写信至oslot
while( (randIndex = rand() % 9) != 4 && oslot[randIndex] != 'O');
oslot[randIndex] = 'O';