#include #include #define N 3 #define MAX 100 using namespace std; void inicializa_matriz(char mat[N][N]) { int i, j; i=0; while (i < N) { j = 0; while (j < N) { mat[i][j] = '.'; j = j + 1; } i = i +1; } } void imprime_matriz(char mat[N][N]) { int i, j; system("clear"); // system("cls") no windows i=0; while (i < N) { j=0; while (j < N) { cout << mat[i][j] << " "; j = j + 1; } cout << endl; i = i + 1; } } // retorna 0 se nao terminou // retorna 1 se o jogador 1 ganhou // retorna 2 se o jogador 2 ganhou // retorna 3 se empatou int joga(char mat[N][N], int jogador, char nome[MAX]) { int i, j, conta; cout << "Jogada do(a) "<< nome <<": "; cin >> i >> j; conta = 1; while ((i < 0 || i >= N || j < 0 || j >= N || mat[i][j] != '.') && conta < 3) { cout << "Jogada invalida! Jogue novamente: "; cin >> i >> j; conta = conta + 1; } if (conta == 3) { cout << "Seu topeira!" << endl; if (jogador == 1) return 2; else return 1; } if (jogador == 1) { mat[i][j] = 'X'; } else { mat[i][j] = 'O'; } // verificar se o jogo terminou // verifica se ha uma linha cheia i=0; while (i < N) { if (mat[i][0] == mat[i][1] && mat[i][0] == mat[i][2] && mat[i][0] != '.') { if (mat[i][0] == 'X') { return 1; } else { return 2; } } i = i+1; } // verifica se ha uma coluna cheia j=0; while (j < N) { if (mat[0][j] == mat[1][j] && mat[0][j] == mat[2][j] && mat[0][j] != '.') { if (mat[0][j] == 'X') { return 1; } else { return 2; } } j = j+1; } // verifica as diagonais if (mat[0][0] == mat[1][1] && mat[0][0] == mat[2][2] && mat[0][0] !='.') { if (mat[0][0] == 'X') { return 1; } else { return 2; } } if (mat[2][0] == mat[1][1] && mat[2][0] == mat[0][2] && mat[2][0] != '.') { if (mat[2][0] == 'X') { return 1; } else { return 2; } } // a matriz tem ponto? i = 0; while (i < N) { j = 0; while (j < N) { if (mat[i][j] == '.') { return 0; } j = j + 1; } i = i +1; } // empatou return 3; } int main() { char matriz[N][N]; char nome1[MAX], nome2[MAX]; int i, j, r; cout << "Bem vindo ao jogo da velha!" << endl; cout << "Nome do jogador 1: "; cin >> nome1; cout << "Nome do jogador 2: "; cin >> nome2; inicializa_matriz(matriz); imprime_matriz(matriz); i = 0; r = joga(matriz, 1, nome1); imprime_matriz(matriz); while (r == 0) { if (i%2 == 0) { r = joga(matriz, 2, nome2); } else { r = joga(matriz, 1, nome1); } i = i+1; imprime_matriz(matriz); } if (r == 3) { cout << "Empatou!" << endl; } else { if (r == 1) { cout << "Jogador " << nome1 << " venceu!" << endl; } else { cout << "Jogador " << nome2 << " venceu!" << endl; } } return 0; }