2017-12-02 12 views
-4

여기는 처음 질문입니다. 제발 실수를 저 지르지 않고 그냥 고칠 일을 알려 주면 너무 화가 나지 마세요. D :C++ Tic-Tac-Toe AI가 작동하지 않습니다.

CPU에 대해 Tic-Tac-Toe를 실행할 수있는 C++ 코드를 작성하려고합니다. CPU는 반드시이기거나 적어도 동점해야합니다. CPU가 먼저 간다. 플레이어는 행과 열에 각각 2 개의 숫자를 입력해야합니다.

문제는 프로그램을 실행할 때 32 번째 줄부터 시작되는 for 루프의 3 번째 사이클에서 오류 메시지없이 중지된다는 것입니다. 내가 잘못했는지 궁금합니다.

#include <iostream> 

using namespace std; 

void displayBoard(char []);     //displays current board 
bool isValidInput(char [], int, int, int); //checks the user input 
bool isItAScore(char [], char);    //determines if current player won or not 
int getValue(char [], char, int);    //get value of the board by player and number marks 

int main() 
{ 
    char tBoard[9], computer = 'X', player = 'O', empty = '.'; 
    int board[3][3], row = -1, col = -1, temp = 0; 
    bool didSomeoneWin = false; 

    //initializes the board with numbers 0 to 8 
    for(int i = 0; i < 3; i++) 
    { 
     for(int j = 0; j < 3; j++) 
     { 
      board[i][j] = temp; 
      temp++; 
     } 
    } 


    //initialize the actual board with '.'  
    for(int i= 0; i < 9; i++) 
    { 
     tBoard[i] = empty; 
    } 

    //starts the game 
    for(int k = 0; k < 9; k++) //it lasts only 9 turns max 
    { 
     displayBoard(tBoard); 

     if(k % 2 == 1) //player's turn 
     { 
      cout << "Player, row and column: "; 
      cin >> row >> col; //takes user input range of 1 to 3 

      //decreases each value by 1 to work with the array index 0 ~ 2 
      row--; 
      col--; 

      if(isValidInput(tBoard, row, col, board[row][col])) //iff the input is valid 
      { 
       tBoard[board[row][col]] = player; //puts the mark on the position 

       if(k > 4 && isItAScore(tBoard, player)) //iff the current player wins 
       { 
        displayBoard(tBoard); 
        cout << "Player wins."; 
        k = 8; //skips to the end of the loop 
        didSomeoneWin = true; //no tie 
       } 
      } 
      else //if the input is invalid 
      { 
       cout << "Invalid row or column number. Try again.\n"; 
       k--; //redo the loop with same player 
      } 
     } 
     else //computer's turn 
     { 
      cout << "Computer's move\n"; 

      if(k == 0) //first move 
      { 
       tBoard[5] = computer; 
      } 
      else 
      { 
       int value = -100, int position = -1; 

       for(int i = 0; i < 9; i++) 
       { 
        if(tBoard[i] == empty) 
        { 
         tBoard[i] = computer; 

         if(isItAScore(tBoard, computer)) 
         { 
          displayBoard(tBoard); 
          cout << "Computer wins."; 
          i = 8; 
          k = 8; 
          didSomeoneWin = true; 
         } 
         else 
         { 
          int x1 = getValue(tBoard, computer, 1); 
          int x2 = getValue(tBoard, computer, 2); 
          int o1 = getValue(tBoard, player, 1); 
          int o2 = getValue(tBoard, player, 2); 

          if(value < 3 * x2 + x1 - (3 * o2 + o1)) 
          { 
           value = 3 * x2 + x1 - (3 * o2 + o1); 
           position = i; 
          } 
         } 

         if(!didSomeoneWin) 
         { 
          tBoard[i] = empty; 
         } 
        } 
       } 

       tBoard[position] = computer; 
      }  
     } 
    } 

    if(!didSomeoneWin) //in case of tie 
    { 
     displayBoard(tBoard); 
     cout << "The cat wins"; 
    } 

    return 0; 
} 

//display the given board 
void displayBoard(char brd[]) 
{ 
    for(int i = 0; i < 9; i++) 
    { 
     cout << brd[i] << " "; 

     if((i + 1) % 3 == 0) 
     { 
      cout << endl; 
     } 
    } 
} 

//checks the input 
bool isValidInput(char brd[], int i, int j, int k) 
{ 
    if(((i >= 0 && i <= 2) && (j >= 0 && j <= 2)) && brd[k] == '.')  //number between 0 and 2, and not taken by any players 
    { 
     return true; 
    } 
    else 
    { 
     return false; 
    } 
} 

//checks if the given player or computer won or not 
bool isItAScore(char brd[], char c) 
{ 
    //chekcs rows 
    if((brd[0] == c && brd[1] == c && brd[2] == c) || (brd[3] == c && brd[4] == c && brd[5] == c) || (brd[6] == c && brd[7] == c && brd[8] == c)) 
    { 
     return true; 
    } 
    else 
    { 
     //checks columns 
     if((brd[0] == c && brd[3] == c && brd[6] == c) || (brd[1] == c && brd[4] == c && brd[7] == c) || (brd[2] == c && brd[5] == c && brd[8] == c)) 
     { 
      return true; 
     } 
     else 
     { 
      //checks diagonals 
      if((brd[0] == c && brd[4] == c && brd[8] == c) || (brd[2] == c && brd[4] == c && brd[6] == c)) 
      { 
       return true; 
      } 
      //if none of them fails 
      else 
      { 
       return false; 
      } 
     } 
    } 
} 

int getValue(char brd[], char c, int n) 
{ 
    int temp = 0, mark = 0; 
    bool eligible = true; 

    for(int i = 0; i < 9; i + 3) //check rows 
    { 
     for(int j = i; j < i + 3; j++) 
     { 
      if(brd[j] != c) 
      { 
       j = 10; 
       eligible = false; 
      } 
      else 
      { 
       if(brd[j] == c) 
       { 
        temp++; 
       } 
      } 
     } 

     if(eligible && temp == n) 
     { 
      mark++; 
     } 

     eligible = true; 
     temp = 0; 
    } 

    for(int i = 0; i < 3; i++) //check columes 
    { 
     for(int j = i; j < i + 7; j + 3) 
     { 
      if(brd[j] != c) 
      { 
       j = 10; 
       eligible = false; 
      } 
      else 
      { 
       if(brd[j] == c) 
       { 
        temp++; 
       } 
      } 
     } 

     if(eligible && temp == n) 
     { 
      mark++; 
     } 

     eligible = true; 
     temp = 0; 
    } 

    for(int i = 0; i < 9; i + 4) //check '\' diagonal 
    { 
     if(brd[i] != c) 
     { 
      i = 10; 
      eligible = false; 
     } 
     else 
     { 
      if(brd[i] == c) 
      { 
       temp++; 
      } 
     } 
    } 

    if(eligible && temp == n) 
    { 
     mark++; 
    } 

    eligible = true; 
    temp = 0; 

    for(int i = 2; i < 9; i + 2) //check '/' diagonal 
    { 
     if(brd[i] != c) 
     { 
      i = 10; 
      eligible = false; 
     } 
     else 
     { 
      if(brd[i] == c) 
      { 
       temp++; 
      } 
     } 
    } 

    if(eligible && temp == n) 
    { 
     mark++; 
    } 

    eligible = true; 
    temp = 0; 

    return mark; 
} 

은 뭔가라는 최소 최대 (공식)를 사용하려고 노력했다. 의도 한대로 제대로 작동하기를 바랍니다. 그것은 인간에 맞서서 최고의 결과를 가져야합니다 (승리 또는 동점, 패).

오류 메시지없이 중지됩니다. 다음 링크는 온라인 컴파일러 내가 사용하고 있습니다 :

http://cpp.sh/

+8

디버거를 사용하십시오. –

+0

코드에 컴파일 오류가 있습니다. –

+2

http://idownvotedbecau.se/nodebugging/ (@ manni66) 더 많은 건설적인 방법이 있습니다. – user0042

답변

0

내가 이상한 물건을 많이 발견했다. 첫 번째 시도는 cpp?

int value = -100, int position = -1; 

int value = -100; 
int position = -1; 

또는

int value = -100, position = -1; 

컴퓨터의 첫 번째 이동이 중앙의 오른쪽에 토큰을 설정해야하는 코드의 첫 오류이다. 난 당신이, 당신이 무한 루프가 중간 위치

tBoard[5] = computer;// should be tBorad[4] 

다음 문제로 설정 싶은 생각 : 당신은 단지 그것을 읽고 있기 때문에,

for(int i = 0; i < 9; i + 3) // right would be i+=3 

내가 변하지 않는 변수, 그리고하지 않습니다 그것을 써라. 이것은 5 번 발생합니다. 경고가 활성화 된 컴파일러는 이와 같은 버그를 찾는 데 도움이됩니다.

다음 항목은 몇 가지 미친 루프 문 대신 끊기계속을 사용합니다. 대신이의,

for(int i = 2; i < 9; i += 2) //check '/' diagonal 
    { 
     if(brd[i] != c) 
     { 
      i = 10; 
      eligible = false; 
     } 
    } 

사용 휴식 : 거리에 있습니다

for(int i = 2; i < 9; i += 2) //check '/' diagonal 
    { 
     if(brd[i] != c) 
     { 
      eligible = false; 
      break; 
     } 
    } 

이 모든 오류 후, 프로그램이 제대로 작동하는 것 같다. gcc와 같은 실제 컴파일러를 사용해야한다고 생각합니다. gcc를 사용하면 플래그를 사용하여 경고를 볼 수 있습니다.

+0

이와 같은 저품질 질문에 대답하는 것은 시간을 잘 사용하지 못합니다. 이러한 질문은 다운 v 팅되고 닫히는 경향이 있으며, 사용자가 ^을 수있는 담당자와 함 2 결국 h 제됩니다. – dandan78