[Community Puzzle] TicTacToe

https://www.codingame.com/training/easy/tictactoe

Send your feedback or ask for help here!

Created by @LaFayette,validated by @alze,@GiB and @lhm.
If you have any issues, feel free to ping them.

using namespace std;
char board[3][3] = { { '1','2','3' },{ '4','5','6' },{ '7','8','9' } };
char turn = 'X';
int row, column;
bool draw = false;
void display_board()
{
	system("cls");
	cout << " TIC TAC TOE \n";
	cout << "\tPLAYER1 [X] \n \tPLAYER2 [O]" << endl;
	cout << "\t\t                    |                 |                 \n";
	cout << "\t\t   " << board[0][0] << "                |    " << board[0][1] << "            |    " << board[0][2] << "\n";
	cout << "\t\t____________________|_________________|_________________\n";
	cout << "\t\t                    |                 |                 \n";
	cout << "\t\t   " << board[1][0] << "                |    " << board[1][1] << "            |    " << board[1][2] << "            \n";
	cout << "\t\t____________________|_________________|_________________\n";
	cout << "\t\t                    |                 |                 \n";
	cout << "\t\t   " << board[2][0] << "                |    " << board[2][1] << "            |    " << board[2][2] << "            \n";
}
void player_turn()
{
	int choice;
	if (turn == 'X')
		cout << "\n\tPlayer1 [X] turn:\n";
	if (turn == 'O')
		cout << "\n\tPlayer2 [O] turn:\n";
	cin >> choice;
	switch (choice)
	{
	case 1:
		row = 0; column = 0;
		break;
	case 2:
		row = 0; column = 1;
		break;
	case 3:
		row = 0; column = 2;
		break;
	case 4:
		row = 1; column = 0;
		break;
	case 5:
		row = 1; column = 1;
		break;
	case 6:
		row = 1; column = 2;
		break;
	case 7:
		row = 2; column = 0;
		break;
	case 8:
		row = 2; column = 1;
		break;
	case 9:
		row = 2; column = 2;
		break;
	default:
		cout << "invalid choice\n";
		break;
	}
	if (turn == 'X' && board[row][column] != 'X' && board[row][column] != 'O')
	{
		board[row][column] = 'X';
		turn = 'O';
	}
	else if (turn == 'O' && board[row][column] != 'X' && board[row][column] != 'O')
	{
		board[row][column] = 'O';
		turn = 'X';
	}
	else {
		cout << "BOX already filled! please try again!!\n";
		player_turn();
	}
	display_board();
}
bool game_over() {
	for (int i = 0; i < 3; i++)
		if (board[i][0] == board[i][1] && board[i][0] == board[i][2] || board[0][i] == board[1][i] && board[0][i] == board[2][i])
			return false;
	if (board[0][0] == board[1][1] && board[0][0] == board[2][2] || board[0][2] == board[1][1] && board[0][2] == board[2][0])
		return false;
	for (int i = 0; i < 3; i++)
		for (int j = 0; j < 3; j++)
			if (board[i][j] != 'X' && board[i][j] != 'O')
				return true;
	draw = true;
	return false;
}

int main()
{
	while (game_over())
	{
		display_board();
		player_turn();
		game_over();
	}
	if (turn == 'X' && draw == false)
		cout << "Player 2 wins\n";
	else if (turn == 'O' && draw == false)
		cout << "Player 2 wins\n";
	else cout << "Draw\n";
	system("pause");
	return 0;
}

MY CODE ISN’T RUNNING ON CODINGGAME .HELP ME

1 Like

Hi !

So I have a problem with the validation of my solution in PHP. In the IDE it works but not with the first three validators to avoid hard coded part.

But I do not understand why it is happening.

I know that it might not be the best solution, but it worked.

Here is my code, thanks for your help :

<?php
/**
 * Auto-generated code below aims at helping you parse
 * the standard input according to the problem statement.
 **/

// Function
function checkWinningMove($vect_values) {
    if (!array_key_exists("X",$vect_values) && array_key_exists("O",$vect_values)) {
        // Check if there is already two O
        if($vect_values["O"] == 2) {
            return true;
        }
    }
    return false;
}

// Init Grid
$grid = [];
for ($i = 0; $i < 3; $i++)
{
    $line = str_split(stream_get_line(STDIN, 3 + 1, "\n"));
    array_push($grid, $line);
}

// Search for winning move, by searching in diagonal
$win_move = false;
for ($i = 0; $i < count($grid); $i++) {
    if ($win_move) break;
    switch($i) {
        case 0:
            // Search in line vector
            $line_vector = $grid[$i];
            $line_count_val = array_count_values($line_vector);
            $win_move = checkWinningMove($line_count_val);
            if ($win_move) {
                // Get the column were it is an empty square
                $index = array_search(".", $line_vector);
                $grid[$i][$index] = "O";
                break;
            }
            // Search in col vector
            $col_vector = [
                $grid[$i][$i],
                $grid[$i+1][$i],
                $grid[$i+2][$i]
            ];
            $col_count_val = array_count_values($col_vector);
            $win_move = checkWinningMove($col_count_val);
            if ($win_move) {
                // Get the line were it is an empty square
                $index = array_search(".", $col_vector);
                $grid[$index][$i] = "O";
                break;
            }
            break;   
        case 1:
            // Search diagnonal from the left
            $diagonal_left = array_count_values([
                $grid[$i-1][$i-1],
                $grid[$i][$i],
                $grid[$i+1][$i+1] 
            ]);
            $left_count_val = array_count_values($diagonal_left);
            $win_move = checkWinningMove($left_count_val);
            if ($win_move) {
                // Get the column were it is an empty square
                $index = array_search(".", $diagonal_left);
                if ($index == 0) {
                    $grid[$i-1][$i-1] = "O";

                } else if ($index == 1) {
                    $grid[$i][$i] = "O";
                } else {
                    $grid[$i+1][$i+1] = "O";
                }
                break;
            }
            // Search diagnonal from the right
            $diagonal_right = [
                $grid[$i+1][$i+1],
                $grid[$i][$i],
                $grid[$i-1][$i-1] 
            ];
            $right_count_val = array_count_values($diagonal_right);
            $win_move = checkWinningMove($right_count_val);
            if ($win_move) {
                // Get the column were it is an empty square
                $index = array_search(".", $diagonal_right);
                if ($index == 0) {
                    $grid[$i+1][$i+1] = "O";

                } else if ($index == 1) {
                    $grid[$i][$i] = "O";
                } else {
                    $grid[$i-1][$i-1] = "O";
                }
                break;
            }
            break;
        case 2:
            // Search in line vector
            $line_vector = $grid[$i];
            $line_count_val = array_count_values($line_vector);
            $win_move = checkWinningMove($line_count_val);
            if ($win_move) {
                // Get the column were it is an empty square
                $index = array_search(".", $line_vector);
                $grid[$i][$index] = "O";
                break;
            }
            // Search in col vector
            $col_vector = [
                    $grid[$i-2][$i],
                    $grid[$i-1][$i],
                    $grid[$i][$i]
            ];
            $col_count_val = array_count_values($col_vector);
            $win_move = checkWinningMove($col_count_val);
            if ($win_move) {
                // Get the line were it is an empty square
                $index = array_search(".", $col_vector);
                $grid[$index][$i] = "O";
                break;
            }
        break;
    }
}

// Write an answer using echo(). DON'T FORGET THE TRAILING \n
// To debug: error_log(var_export($var, true)); (equivalent to var_dump)
if ($win_move) {
    foreach($grid as $line) {
        $result = implode("", $line);
        echo "$result\n";
    }
} else {
    echo "false";
}
?>

Sorry but I disagree with the second part of the sentence.

Your code need to check all cases but :

  • middle column not checked
  • middle line not checked
  • your diagonals tests check the same

So 3 winning configuration out of 8 are missed

2 Likes

Oh god, my bad ! I missed these out ! :upside_down_face:

Thank you @dwarfie, you are my savior :smile:

Salut, je suis débutant j’ai réussit les test dans l’IDE mais apparemment pour la diagonale (le test3) je l’ai fait en dur, mais ça me parait correct…
Voici ma démarche si quelqu’un peut m’aider, j’ai codé en C :

  • j’ai fait une fonction pour vĂ©rifier les deux diagonales en passant en paramètre la grille
  • j’ai fais 6 condition du style : si en 0,0 c’est O et en 1,1 c’est . et en 2,2 c’est 0 alors je met un 0 en 2,2 et je retourne une valeur vraie (qui sert Ă  la fin pour savoir si il est possible de gagner)
  • si on arrive pas au bout des 6 conditions j’ai retournĂ© faux

si quelqu’un peut m’aider, merci d’avance ^^

please write in English in the forum.

Here’s the validator you fail:

Input:

..O
...
O..

Output:

..O
.O.
O..

Hey, I fail on validator 4, and I have no idea why… could you show me what the validator looks like?

Here you go:

Input

O.O
XO.
X.X

Output

OOO
XO.
X.X
3 Likes

Nice little puzzle.

Though I feel the description is incomplete. I think should mention that
If a winning move exists, then (in case of the puzzle) the winning move is unique.

In general, tic-tac-toe may have multiple winning moves of course

Hi guys,
I have made my solution, all tests passes, but it says like real validators are not what I see in the IDE, and they don’t pass. My code seems to work, I pass throught lines, columns and diagonals, so I don’t understand where the problem is:

[mod edit: please avoid posting code on the forum]

There are just a few possible inputs (9 possibilities for “No opponent - column” and 6 for “No opponent - diagonal”), so you can just try them all to see for which ones your code fails to output the correct answer.

Also, please be reminded not to post the full code on the forum. Try to describe your approach first, and mention which validators you fail.