Tic-Tac-Toe

A Python implementation of the classic game of Tic-Tac-Toe that you can play right in your browser.

Project Details

Tic-Tac-Toe Project

About This Project

This is a command-line implementation of the classic Tic-Tac-Toe game built in Python. It features:

  • Two-player gameplay (X and O)
  • Visual board representation
  • Win detection for rows, columns, and diagonals
  • Tie game detection
  • Option to play again after a game ends
Python Game Command Line

Python Code

# Tic-Tac-Toe def clear(): # import OS is not available in Skulpt, pretend this clears the output # def clear(): # if os.name == 'nt': # os.system('cls') # else: # os.system('clear') pass def print_board(board, players, turn): clear() print() for i, row in enumerate(board): print(" | ".join(row)) if i < 2: print("-" * (len(row) * 4 - 3)) player = players[turn % 2] print(f"\nPlayer {player}'s turn") def check_winner(board, player): for i in range(3): if all(board[i][j] == player for j in range(3)) or \ all(board[j][i] == player for j in range(3)): return True if all(board[i][i] == player for i in range(3)) or \ all(board[i][2 - i] == player for i in range(3)): return True return False def play(): clear() board = [[" "] * 3 for _ in range(3)] players = ['X', 'O'] turn = 0 while True: print_board(board, players, turn) while True: try: row = int(input("Enter row (1-3): ")) - 1 print_board(board, players, turn) col = int(input("Enter column (1-3): ")) - 1 if col == 'back': return print_board(board, players, turn) if 0 <= row < 3 and 0 <= col < 3 and board[row][col] == " ": break else: print_board(board, players, turn) print("That spot was already played or is invalid. Please try again.") except ValueError: print_board(board, players, turn) print("Invalid input. Please try again.") board[row][col] = players[turn % 2] if check_winner(board, players[turn % 2]): print_board(board, players, turn) if input(f"Player {players[turn % 2]} wins!\nWould you like to play again? (y/n):\n") == 'y': play() else: clear() break break if all(all(cell != " " for cell in row) for row in board): print_board(board, players, turn) if input("It's a tie!\nWould you like to play again? (y/n):\n") == 'y': play() else: input("Thanks for playing!\nPress enter to exit...") clear() break turn += 1 play() input("Thanks for playing!\nPress enter to exit...") clear()

Output

Click "Run Code" to see the program output here
Waiting for input...

How To Play

This Tic-Tac-Toe game is played on a 3x3 grid. Here's how to play:

Game Setup

The game is played between two players: X and O. The board is represented as a grid with positions numbered by row and column.

Taking Turns

Players take turns placing their mark (X or O) on an empty position by entering the row (1-3) and column (1-3).

Winning the Game

A player wins by placing three of their marks in a horizontal, vertical, or diagonal row.

Draw Game

If all positions are filled and no player has won, the game ends in a draw.