Implementação do jogo Tic-Tac-Toe
Regras do jogo
- O jogo deve ser jogado entre duas pessoas (neste programa entre HUMANO e COMPUTADOR).
- Um dos jogadores escolhe 'O' e o outro 'X' para marcar suas respectivas células.
- O jogo começa com um dos jogadores e termina quando um dos jogadores tem uma linha / coluna / diagonal inteira preenchida com seu respectivo caractere ('O' ou 'X').
- Se ninguém ganhar, o jogo está empatado.
Implementação
Em nosso programa, os movimentos executados pelo computador e pelo ser humano são escolhidos aleatoriamente. Usamos a função rand() para isso.O que mais pode ser feito no programa?
O programa não é reproduzido de forma otimizada por ambos os lados porque os movimentos são escolhidos aleatoriamente. O programa pode ser facilmente modificado para que ambos os jogadores joguem da melhor maneira (o que se enquadrará na categoria de Inteligência Artificial). Além disso, o programa pode ser modificado de forma que o próprio usuário forneça a entrada (usando scanf() ou cin).
As alterações acima são deixadas como um exercício para os leitores.Estratégia de vitória - um fato interessante
Se ambos os jogadores jogarem da melhor forma, então está destinado a você nunca perder (“embora a partida ainda possa ser empatada”). Não importa se você joga primeiro ou segundo. De outra forma - “Dois jogadores experientes sempre empatarão”.
Não é interessante?// A C++ Program to play tic-tac-toe
#include<bits/stdc++.h>
using
namespace
std;
#define COMPUTER 1
#define HUMAN 2
#define SIDE 3 // Length of the board
// Computer will move with 'O'
// and human with 'X'
#define COMPUTERMOVE 'O'
#define HUMANMOVE 'X'
// A function to show the current board status
void
showBoard(
char
board[][SIDE])
{
printf
(
"\n\n"
);
printf
(
"\t\t\t %c | %c | %c \n"
, board[0][0],
board[0][1], board[0][2]);
printf
(
"\t\t\t--------------\n"
);
printf
(
"\t\t\t %c | %c | %c \n"
, board[1][0],
board[1][1], board[1][2]);
printf
(
"\t\t\t--------------\n"
);
printf
(
"\t\t\t %c | %c | %c \n\n"
, board[2][0],
board[2][1], board[2][2]);
return
;
}
// A function to show the instructions
void
showInstructions()
{
printf
(
"\t\t\t Tic-Tac-Toe\n\n"
);
printf
(
"Choose a cell numbered from 1 to 9 as below"
" and play\n\n"
);
printf
(
"\t\t\t 1 | 2 | 3 \n"
);
printf
(
"\t\t\t--------------\n"
);
printf
(
"\t\t\t 4 | 5 | 6 \n"
);
printf
(
"\t\t\t--------------\n"
);
printf
(
"\t\t\t 7 | 8 | 9 \n\n"
);
printf
(
"-\t-\t-\t-\t-\t-\t-\t-\t-\t-\n\n"
);
return
;
}
// A function to initialise the game
void
initialise(
char
board[][SIDE],
int
moves[])
{
// Initiate the random number generator so that
// the same configuration doesn't arises
srand
(
time
(NULL));
// Initially the board is empty
for
(
int
i=0; i<SIDE; i++)
{
for
(
int
j=0; j<SIDE; j++)
board[i][j] =
' '
;
}
// Fill the moves with numbers
for
(
int
i=0; i<SIDE*SIDE; i++)
moves[i] = i;
// randomise the moves
random_shuffle(moves, moves + SIDE*SIDE);
return
;
}
// A function to declare the winner of the game
void
declareWinner(
int
whoseTurn)
{
if
(whoseTurn == COMPUTER)
printf
(
"COMPUTER has won\n"
);
else
printf
(
"HUMAN has won\n"
);
return
;
}
// A function that returns true if any of the row
// is crossed with the same player's move
bool
rowCrossed(
char
board[][SIDE])
{
for
(
int
i=0; i<SIDE; i++)
{
if
(board[i][0] == board[i][1] &&
board[i][1] == board[i][2] &&
board[i][0] !=
' '
)
return
(
true
);
}
return
(
false
);
}
// A function that returns true if any of the column
// is crossed with the same player's move
bool
columnCrossed(
char
board[][SIDE])
{
for
(
int
i=0; i<SIDE; i++)
{
if
(board[0][i] == board[1][i] &&
board[1][i] == board[2][i] &&
board[0][i] !=
' '
)
return
(
true
);
}
return
(
false
);
}
// A function that returns true if any of the diagonal
// is crossed with the same player's move
bool
diagonalCrossed(
char
board[][SIDE])
{
if
(board[0][0] == board[1][1] &&
board[1][1] == board[2][2] &&
board[0][0] !=
' '
)
return
(
true
);
if
(board[0][2] == board[1][1] &&
board[1][1] == board[2][0] &&
board[0][2] !=
' '
)
return
(
true
);
return
(
false
);
}
// A function that returns true if the game is over
// else it returns a false
bool
gameOver(
char
board[][SIDE])
{
return
(rowCrossed(board) || columnCrossed(board)
|| diagonalCrossed(board) );
}
// A function to play Tic-Tac-Toe
void
playTicTacToe(
int
whoseTurn)
{
// A 3*3 Tic-Tac-Toe board for playing
char
board[SIDE][SIDE];
int
moves[SIDE*SIDE];
// Initialise the game
initialise(board, moves);
// Show the instructions before playing
showInstructions();
int
moveIndex = 0, x, y;
// Keep playing till the game is over or it is a draw
while
(gameOver(board) ==
false
&&
moveIndex != SIDE*SIDE)
{
if
(whoseTurn == COMPUTER)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = COMPUTERMOVE;
printf
(
"COMPUTER has put a %c in cell %d\n"
,
COMPUTERMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = HUMAN;
}
else
if
(whoseTurn == HUMAN)
{
x = moves[moveIndex] / SIDE;
y = moves[moveIndex] % SIDE;
board[x][y] = HUMANMOVE;
printf
(
"HUMAN has put a %c in cell %d\n"
,
HUMANMOVE, moves[moveIndex]+1);
showBoard(board);
moveIndex ++;
whoseTurn = COMPUTER;
}
}
// If the game has drawn
if
(gameOver(board) ==
false
&&
moveIndex == SIDE * SIDE)
printf
(
"It's a draw\n"
);
else
{
// Toggling the user to declare the actual
// winner
if
(whoseTurn == COMPUTER)
whoseTurn = HUMAN;
else
if
(whoseTurn == HUMAN)
whoseTurn = COMPUTER;
// Declare the winner
declareWinner(whoseTurn);
}
return
;
}
// Driver program
int
main()
{
// Let us play the game with COMPUTER starting first
playTicTacToe(COMPUTER);
return
(0);
}
Saída:
Jogo da velha Escolha uma célula numerada de 1 a 9 como abaixo e jogue 1 2 | 3 -------------- 4 5 | 6 -------------- 7 8 9 - - - - - - - - - - COMPUTADOR colocou um O na célula 6 | | -------------- | | O -------------- | | HUMANO colocou um X na célula 7 | | -------------- | | O -------------- X | | COMPUTADOR colocou um O na célula 5 | | -------------- | O | O -------------- X | | HUMAN colocou um X na célula 1 X | | -------------- | O | O -------------- X | | COMPUTADOR colocou um O na célula 9 X | | -------------- | O | O -------------- X | | O HUMANO colocou um X na célula 8 X | | -------------- | O | O -------------- X | X | O COMPUTADOR colocou um O na célula 4 X | | -------------- O | O | O -------------- X | X | O COMPUTADOR ganhou
Uma variante interessante deste jogo
Como dito acima, se dois jogadores experientes estiverem jogando o Tic-Tac-Toe, o jogo sempre empatará.
Existe outra variante viral deste jogo - Ultimate Tic-Tac-Toe, que visa tornar o Tic-Tac-Toe normal mais interessante e menos previsível.
Dê uma olhada no jogo aqui- Link1 Link2O artigo acima implementa um jogo da velha simples, em que os movimentos são feitos aleatoriamente. Consulte o artigo abaixo para ver como os movimentos ideais são feitos.
Algoritmo Minimax na teoria dos jogos | Conjunto 3 (Tic-Tac-Toe AI - Encontrando o movimento ideal)Grandes discussões sobre a estratégia de “ganhar / nunca perder”
Quora
WikihowEste artigo é contribuído por Rachit Belwariar .Se você gosta GeeksforGeeks e gostaria de contribuir, você também pode escrever um artigo usando contribute.geeksforgeeks.org ou enviar o seu artigo para contribute@geeksforgeeks.org. Veja o seu artigo na página principal do GeeksforGeeks e ajude outros Geeks.
Escreva comentários se encontrar algo incorreto ou se quiser compartilhar mais informações sobre o tópico discutido acima.
Atenção leitor! Não pare de aprender agora. Obtenha todos os conceitos importantes de DSA com o Curso Individual de DSA a um preço acessível ao aluno e prepare-se para a indústria. Para completar sua preparação desde o aprendizado de um idioma até o DS Algo e muitos mais, consulte o Curso Completo de Preparação para Entrevistas .
Caso você deseje assistir a aulas ao vivo com especialistas, consulte DSA Live Classes para profissionais que trabalham e Programação competitiva ao vivo para alunos .
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva