我正在制作一个用户与计算机竞争的tic tac toe游戏。每当人们在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()放入其中,以此类推,但仍然无法使其工作。
发布于 2019-06-21 13:45:11
首先,更好地选择您的数据结构。而不是:
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){此人在1到9之间选择一个点
和
random = rand() % 9 + 1;您只有3个casilla。其他6个在哪里?
我尝试过使用while和do-while循环的
在AI()中没有循环。也许你可以给我们看一个有循环的代码?
printf("\n\nChoose a spot: ");
fflush(stdin);您可能想对stdout执行fflush()操作
https://stackoverflow.com/questions/56697229
复制相似问题