Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.9 kB
1
Indexable
Never
# initialize the board with empty spaces
board = [" " for i in range(9)]

# function to print the board
def print_board():
    row1 = "|{}|{}|{}|".format(board[0], board[1], board[2])
    row2 = "|{}|{}|{}|".format(board[3], board[4], board[5])
    row3 = "|{}|{}|{}|".format(board[6], board[7], board[8])
    
    print(row1)
    print(row2)
    print(row3)

# function to make a move
def make_move(player, position):
    board[position] = player

# function to check if the game is over
def game_over():
    return (board.count("X") + board.count("O")) == 9

# function to check if a player has won
def check_win(player):
    return ((board[0] == player and board[1] == player and board[2] == player) or
    (board[3] == player and board[4] == player and board[5] == player) or
    (board[6] == player and board[7] == player and board[8] == player) or
    (board[0] == player and board[3] == player and board[6] == player) or
    (board[1] == player and board[4] == player and board[7] == player) or
    (board[2] == player and board[5] == player and board[8] == player) or
    (board[0] == player and board[4] == player and board[8] == player) or
    (board[2] == player and board[4] == player and board[6] == player))

# main game loop
def play_game():
    print("Welcome to Tic Tac Toe!")
    print_board()
    
    while not game_over():
        player1_pos = int(input("Player 1, enter a position (1-9): "))
        make_move("X", player1_pos-1)
        print_board()
        
        if check_win("X"):
            print("Player 1 wins!")
            return
        
        if game_over():
            print("Game over. It's a tie!")
            return
        
        player2_pos = int(input("Player 2, enter a position (1-9): "))
        make_move("O", player2_pos-1)
        print_board()
        
        if check_win("O"):
            print("Player 2 wins!")
            return

# start the game
play_game()