Skip to content

Instantly share code, notes, and snippets.

@timrprobocom
Created May 20, 2024 00:32
Show Gist options
  • Save timrprobocom/a7b8ce9a0fc55ab553b0c4421ff7be1a to your computer and use it in GitHub Desktop.
Save timrprobocom/a7b8ce9a0fc55ab553b0c4421ff7be1a to your computer and use it in GitHub Desktop.
import random
def display_board(board):
print(board[0] + "|" + board[1] + "|" + board[2])
print("------")
print(board[3] + "|" + board[4] + "|" + board[5])
print("------")
print(board[6] + "|" + board[7] + "|" + board[8])
def player_input(first_move):
while 1:
m = input(f'Player {first_move} picks first. Would you like X or O?')
if m in 'XO':
break
print("Sorry, that is not a valid input! Try again")
marker = [' ',' ']
marker[first_move-1] = m
marker[2-first_move] = 'O' if m=='X' else 'X'
print(f"Player 1 is {marker[0]} and Player 2 is {marker[1]}")
return marker
def place_marker(board, marker):
while 1:
position = input(f"{marker}: Where would you like to place the marker? (1 - 9): ")
if position.isdigit():
position = int(position)
if position in range(1,10):
break
print("Invalid input")
board[position-1] = marker
def choose_first():
first_move = random.randint(1,2)
if first_move == 1:
print("Player 1 (Left) will go first!")
else:
print("Player 2 (Right) will go first!")
return first_move
def full_board_check(board):
return all(b != ' ' for b in board)
def replay():
while play_again not in 'yn':
play_again = input("Would you like to play again? y or n: ")
return play_again=='y'
def win_check(board, marker):
return (board[0] == board[1] == board[2] == marker) or \
(board[3] == board[4] == board[5] == marker) or \
(board[6] == board[7] == board[8] == marker) or \
(board[0] == board[3] == board[6] == marker) or \
(board[1] == board[4] == board[7] == marker) or \
(board[2] == board[5] == board[8] == marker) or \
(board[0] == board[4] == board[8] == marker) or \
(board[2] == board[4] == board[6] == marker)
def game():
board = [" "," "," "," "," "," "," "," "," "]
display_board(board)
print("Welcome to Tic Tac Toe")
#Choose with player will go first
move = choose_first()
#Ask player1 if they want to be X or O?
marker1, marker2 = player_input(move)
#start game
while not full_board_check(board):
marker = [marker1,marker2][move-1]
place_marker(board,marker)
display_board(board)
if win_check(board, marker):
print(f"Player {marker} has won!")
break
if full_board_check(board) == 1:
print("Game has tied!")
break
move = 3-move
while 1:
game()
if not replay():
break
print("Thank you for playing!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment