I'm relatively new to Python. Here is a Tic Tac Toe game I've created in Python:
def is_valid_move(x,y,board):
return ((0 <= x <= 2) and (0 <= y <= 2)) and (board[x][y] == '_')
def check_win(board):
if board[0][0] == board[0][1] == board[0][2] != '_':
return True
if board[1][0] == board[1][1] == board[1][2] != '_':
return True
if board[2][0] == board[2][1] == board[2][2] != '_':
return True
if board[0][0] == board[0][1] == board[0][2] != '_':
return True
if board[0][1] == board[1][1] == board[2][1] != '_':
return True
if board[0][2] == board[1][2] == board[2][2] != '_':
return True
if board[0][0] == board[1][1] == board[2][2] != '_':
return True
if board[2][0] == board[1][1] == board[0][2] != '_':
return True
return False
def get_input_from_user(message:str):
coord = input(message)
str_x, str_y = coord.split()
return int(str_x), int(str_y)
def make_move(idx,board):
if idx % 2 == 0:
x, y = get_input_from_user("Player X, please enter a move:")
while not is_valid_move(x, y,board):
x,y = get_input_from_user("Invalid move, please try again:")
board[x][y] = 'X'
else:
x, y = get_input_from_user("Player O, please enter a move:")
while not is_valid_move(x, y,board):
x, y = get_input_from_user("Invalid move, please try again:")
board[x][y] = 'O'
def print_board(board):
for i in range(3):
print(board[i])
if __name__ == '__main__':
idx = 0
board = [['_','_','_'] for i in range(3)]
condition = False
while condition is not True or idx <= 8:
make_move(idx,board)
print_board(board)
condition = check_win(board)
if condition is True and idx % 2 == 0:
print("Player X is the Winner!")
elif condition is True:
print("Player O is the Winner!")
idx += 1
if idx > 8 and condition is not True:
print("Its a Draw!")
Here is a simple test run of this code:
Player X, please enter a move:0 2
['_', '_', 'X']
['_', '_', '_']
['_', '_', '_']
Player O, please enter a move:0 1
['_', 'O', 'X']
['_', '_', '_']
['_', '_', '_']
Player X, please enter a move:1 1
['_', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player O, please enter a move:0 0
['O', 'O', 'X']
['_', 'X', '_']
['_', '_', '_']
Player X, please enter a move:2 0
['O', 'O', 'X']
['_', 'X', '_']
['X', '_', '_']
Player X is the Winner!
Let me know your thoughts about my code.