Last active
June 24, 2024 18:37
-
-
Save Babatunde13/37d114cbd8b8a89d78d05dadbb3464a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def getInput(availablePositions): | |
print("Available positions 👇🏽") | |
print(availablePositions) | |
rowIdx = int(input('Which row are you playing? ')) | |
colIdx = int(input('Which column are you playing? ')) | |
while [rowIdx, colIdx] not in availablePositions: | |
print("Position not available") | |
getInput(availablePositions) | |
return [rowIdx, colIdx] | |
def hasWon(board): | |
row1, row2, row3 = board[0], board[1], board[2] | |
col1, col2, col3 = ( | |
[board[0][0], board[1][0], board[2][0]], | |
[board[0][1], board[1][1], board[2][1]], | |
[board[0][2], board[1][2], board[2][2]] | |
) | |
diag1, diag2 = ( | |
[board[0][0], board[1][1], board[2][2]], | |
[board[0][2], board[1][1], board[2][0]] | |
) | |
same_row1 = row1[0] == row1[1] == row1[2] and row1[0] != '_' | |
same_row2 = row2[0] == row2[1] == row2[2] and row2[0] != '_' | |
same_row3 = row3[0] == row3[1] == row3[2] and row3[0] != '_' | |
same_col1 = col1[0] == col1[1] == col1[2] and col1[0] != '_' | |
same_col2 = col2[0] == col2[1] == col2[2] and col2[0] != '_' | |
same_col3 = col3[0] == col3[1] == col3[2] and col3[0] != '_' | |
same_diag1 = diag1[0] == diag1[1] == diag1[2] and diag1[0] != '_' | |
same_diag2 = diag2[0] == diag2[1] == diag2[2] and diag2[0] != '_' | |
return ( | |
same_row1 or same_row2 or same_row3 or | |
same_col1 or same_col2 or same_col3 or | |
same_diag1 or same_diag2 | |
) | |
def printArr(arr): | |
for row in arr: | |
for cell in row: | |
print(cell, end=" ") | |
print() | |
def ticTacToeGame (): | |
board = [ | |
["_", "_", "_"], | |
["_", "_", "_"], | |
["_", "_", "_"] | |
] | |
availablePositions = [ | |
[1, 1], [1, 2], [1, 3], | |
[2, 1], [2, 2], [2, 3], | |
[3, 1], [3, 2], [3, 3] | |
] | |
won = False | |
currPlayer = 'X' | |
while won == False and len(availablePositions) != 0: | |
print(f"It's {currPlayer} player's turn") | |
playerPosition = getInput(availablePositions) | |
availablePositions.remove(playerPosition) | |
board[playerPosition[0]-1][playerPosition[1]-1] = currPlayer | |
won = hasWon(board) | |
print(f"board after player {currPlayer} played") | |
print() | |
printArr(board) | |
if won: | |
break | |
currPlayer = 'O' if currPlayer == 'X' else 'X' | |
if won: | |
print(f'{currPlayer} won') | |
else: | |
print('Tie') | |
ticTacToeGame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment