gpt4 book ai didi

c - 如果 rand() 重复一个数字,则重新为变量赋值

转载 作者:太空宇宙 更新时间:2023-11-04 07:46:18 25 4
gpt4 key购买 nike

我正在制作一个用户与计算机竞争的井字游戏。每当人在 1 到 9 之间选择一个点时,计算机也需要选择一个。为此,我使用 rand()。但是,如果这个位置已经被占用了,我需要电脑重新计算一个。我试过使用 while 和 do-while 循环,但是当我应用它们时,cmd 停止工作并且不允许我继续游戏。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

typedef struct symbol{
int marcado;
char simbolo;
} SPOT;

SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};

void table();
void User();
void AI();

int main(){
system("cls");
User();
AI();
Check();
return 0;
}

void table(){
printf("\n %c | %c | %c ",spot1.symbol,spot2.symbol,spot3.symbol);
}

这是用户选择地点的功能:

void User(){

char choice;

do{

do{
board();
printf("\n\nChoose a spot: ");
fflush(stdin);
scanf("%c",&choice);
}while(choice < '1' || choice > '3');

switch(choice){
case '1': if(choice == '1'){

system("cls");

if(casilla1.marcado == 1){
printf("\noccupied\n");
}

else if(casilla1.marcado == 0){
casilla1.marcado = 1;
casilla1.simbolo = 'X';

AI();
}
}
break;

case '2': if(choice == '2'){

system("cls");

if(casilla2.marcado == 1){
printf("\noccupied\n");
}

else if(casilla2.marcado == 0){
casilla2.marcado = 1;
casilla2.simbolo = 'X';

AI();
}
}
break;

case '3': if(choice == '3'){

system("cls");

if(casilla3.marcado == 1){
printf("\noccupied");
}

else if(casilla3.marcado == 0){
casilla3.marcado = 1;
casilla3.simbolo = 'X';

AI();
}
}
break;

}while(Check() != 0 && Check() != 1);
}

这是计算机的功能。我在“else if”语句中遇到了麻烦,因为我不知道要在其中放入什么。

void AI(){

int random;

srand(time(NULL));

random = rand() % 3 + 1;

if (random == 1){
if(casilla1.marcado == 0){
casilla1.simbolo = 'O';
casilla1.marcado = 1;
}

else if(casilla1.marcado == 1){
random = rand() % 3 + 1
}
}

if (random == 2){
if(casilla2.marcado == 0){
casilla2.simbolo = 'O';
casilla2.marcado = 1;
}

else if(casilla2.marcado == 1){
random = rand() % 3 + 1;
}
}

if (random == 3){
if(casilla3.marcado == 0){
casilla3.simbolo = 'O';
casilla3.marcado = 1;
}

else if(casilla3.marcado == 1){
random = rand() % 3 + 1;
}
}
}

正如我之前所说,我已经尝试将整个 AI() 放入不同类型的循环中,只将 rand() 放入其中,等等,但仍然无法让它工作。

最佳答案

首先,更好地选择数据结构。而不是:

SPOT casilla1 = {0,'1'};
SPOT casilla2 = {0,'2'};
SPOT casilla3 = {0,'3'};

使用

SPOT casilla[3] = { {0,'1'}, {0,'2'}, {0,'3'} };

因此,不再需要 switch 结构。而不是:

if(casilla1.marcado == 0){
if(casilla2.marcado == 0){
if(casilla3.marcado == 0){

使用:

if(casilla[random-1].marcado == 0){

the person chooses a spot between 1 and 9

random = rand() % 9 + 1;

你只有 3 个 casilla。其他 6 个在哪里?


I've tried using while and do-while loops

AI() 中没有循环。也许您可以向我们展示带有循环的代码?


printf("\n\nChoose a spot: ");
fflush(stdin);

您可能想要fflush() stdout

关于c - 如果 rand() 重复一个数字,则重新为变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56697229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com