tictac toe python code example
Example: tic tac toe in python
import time
import sys
TITLES = " A B C\n"
INIT_BOARD = "| / | / | / |\n"
A, B, C = 4, 8, 12
board = [f"{x} {INIT_BOARD}" for x in range(3)]
user_turn = ""
taken = True
winner = False
turn_number = 0
SYMBOLS = ["x", "o"]
winner_save = [list(x * 3) for x in SYMBOLS]
score = {symbol: 0 for symbol in SYMBOLS}
class logic:
def __init__(self, ctx, turn, win_template):
self.ctx = ctx
self.turn = turn
self.template = win_template
def winner_check(self):
win_check = [
[board[c][x] for x in range(4, len(board[c])) if x % 4 == 0]
for c in range(3)
]
for x in range(3):
win_check.append([win_check[c][x] for c in range(3)])
win_check.append([win_check[x][x] for x in range(3)])
win_check.append([win_check[x][c] for x, c in zip(range(3)[::-1], range(3))])
for x in win_check:
if x in self.template:
print(f"{self.turn} wins!")
keep = True
break
keep = False
return keep
def take_spot(self):
append_board = board[int(user[1])]
append_board = "".join(
[
append_board[x] if x != eval(user[0]) else self.turn
for x in range(len(append_board))
]
)
return append_board
def spot_taken(self):
board_ctx = board[int(self.ctx[1])][eval(self.ctx[0])]
check_spot = True if board_ctx in ["o", "x"] else False
if check_spot == True:
print("spot already taken :/ try again")
return check_spot
def input_check():
slow_print("location- \n")
ctx = input().upper()
all_input = [x + str(c) for x in ["A", "B", "C"] for c in range(3)]
if ctx in all_input:
pass
else:
while ctx not in all_input:
slow_print("invalid location, try again\n")
slow_print("location- \n")
ctx = input().upper()
return list(ctx)
def slow_print(inpt):
for x in inpt:
sys.stdout.write(x)
time.sleep(0.01)
slow_print(TITLES + "".join(board))
while True:
slow_print(f"{SYMBOLS[0]}'s or {SYMBOLS[1]}'s?- \n")
user_turn = input()
if user_turn in [SYMBOLS[0], SYMBOLS[1]]:
slow_print(f"{user_turn}'s first!\n")
break
else:
slow_print("incorrent input try again!")
while True:
outcome = "None"
while winner == False:
turn_number += 1
if turn_number == 10:
slow_print("Tie!\n")
outcome = None
break
while taken == True:
user = input_check()
init = logic(user, user_turn, winner_save)
taken = init.spot_taken()
ctx_board = init.take_spot()
board[int(user[1])] = ctx_board
slow_print(TITLES + "".join(board))
user_turn = SYMBOLS[0] if user_turn != SYMBOLS[0] else SYMBOLS[1]
taken = True
winner = init.winner_check()
if outcome == None:
pass
else:
score[SYMBOLS[0] if user_turn == SYMBOLS[1] else SYMBOLS[1]] += 1
slow_print(
f"Scores: {SYMBOLS[0]}-{score[SYMBOLS[0]]}, {SYMBOLS[1]}-{score[SYMBOLS[1]]}\n"
)
slow_print("Would you like to play another (Y/N)?- \n")
repeat = input().upper()
if repeat == "Y":
winner = False
board = [f"{x} {INIT_BOARD}" for x in range(3)]
turn_number = 0
continue
else:
break