Skip to content

Instantly share code, notes, and snippets.

@sertdfyguhi
Last active April 21, 2023 16:32
Show Gist options
  • Save sertdfyguhi/e09f510aa5362b5b910ec0ede92fe322 to your computer and use it in GitHub Desktop.
Save sertdfyguhi/e09f510aa5362b5b910ec0ede92fe322 to your computer and use it in GitHub Desktop.
Tic tac toe in python
from itertools import chain
from sys import exit
BOARD_TEMPLATE = '''
| |
{} | {} | {}
| |
---+---+---
| |
{} | {} | {}
| |
---+---+---
| |
{} | {} | {}
| |
'''
PRINT_MAPPINGS = [ ' ', 'X', 'O' ]
# 0 is empty
# 1 is player 1 (X)
# 2 is player 2 (O)
board = [
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
turn = 1
def print_board():
l = [ PRINT_MAPPINGS[el] for row in board for el in row ]
print(BOARD_TEMPLATE.format(*l))
def check():
checks = [check_hor(), check_ver(), check_diag()]
if any(check for check in checks):
win()
def check_hor():
return any(row == [turn, turn, turn] for row in board)
def check_ver():
columns = [ [ row[i] for row in board ] for i in range(3) ]
return any(col == [turn, turn, turn] for col in columns)
def check_diag():
diag = [
[ board[0][0], board[1][1], board[2][2] ],
[ board[0][2], board[1][1], board[2][0] ]
]
return any(d == [turn, turn, turn] for d in diag)
def win():
print_board()
print(f'player {turn} wins!')
exit()
def tie():
print_board()
print('tie!')
def prompt():
global turn
print_board()
inp = int(input(f'player {turn}: ')) - 1
pos = ( inp // 3, inp % 3 )
if inp > len(list(chain(*board))) - 1 or inp < 0:
print('That is not a valid space.\n')
return
if board[pos[0]][pos[1]] != 0:
print('That space is already taken!\n')
return
board[pos[0]][pos[1]] = turn
check()
turn = 2 if turn == 1 else 1
while any(el == 0 for el in list(chain(*board))):
prompt()
tie()
@BimarDwi
Copy link

Just created something like this, thank you for uploading.

@sertdfyguhi
Copy link
Author

Just created something like this, thank you for uploading.

No problem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment