Skip to content

Instantly share code, notes, and snippets.

@arthuro555
Created September 29, 2022 20:46
Show Gist options
  • Save arthuro555/6b1741847ab49e8bf4305f92bad2b07b to your computer and use it in GitHub Desktop.
Save arthuro555/6b1741847ab49e8bf4305f92bad2b07b to your computer and use it in GitHub Desktop.
Tic tac toe python (made >1h)
def create_row():
return { "left": " ", "center": " ", "right": " " }
def create_board():
return { "up": create_row(), "center": create_row(), "down": create_row() }
board = create_board()
def print_board():
print("")
print("The board now looks as following:")
print("")
print("╭ ╮")
print(" " + board["up"]["left"] + " " + board["up"]["center"] + " " + board["up"]["right"] + " ")
print(" ┼ ┼ ")
print(" " + board["center"]["left"] + " " + board["center"]["center"] + " " + board["center"]["right"] + " ")
print(" ┼ ┼ ")
print(" " + board["down"]["left"] + " " + board["down"]["center"] + " " + board["down"]["right"] + " ")
print("╰ ╯")
print("")
player = "X"
def player_input(question):
return input("[Player " + player + "] " + question + " > ")
def switch_player():
global player
player = "X" if player == "O" else "O"
rows = ["up", "center", "down"]
columns = ["left", "center", "right"]
def ask_for(input_type, answers):
answer = ""
while not answer in answers:
answer = player_input("Please enter the " + input_type + " to cross")
if not answer in answers:
print("The answer must be one of " + ", ".join(answers) + "!")
return answer
def winner_in_serie(serie):
if serie == "XXX":
return "X"
if serie == "YYY":
return "Y"
return False
def check_win_col(col):
col_state = board["up"][col] + board["center"][col] + board["down"][col]
return winner_in_serie(col_state)
def check_win_row(row):
row_obj = board[row]
row_state = row_obj["left"] + row_obj["center"] + row_obj["right"]
return winner_in_serie(row_state)
def check_win_diag():
# Dont check only in the modified col & row, as that would be computionally more intensive, contrary to sinple row and col checks
diag1_state = board["up"]["left"] + board["center"]["center"] + board["down"]["right"]
diag2_state = board["up"]["right"] + board["center"]["center"] + board["down"]["left"]
return winner_in_serie(diag1_state) or winner_in_serie(diag2_state)
def check_win(col, row):
return check_win_col(col) or check_win_row(row) or check_win_diag()
def game_loop():
while True:
column = ask_for("column", columns)
row = ask_for("row", rows)
if board[row][column] != " ":
print("This case is already taken! Please chose another one.")
continue
board[row][column] = player
print_board()
winner = check_win(column, row)
if winner:
print("And therefore, we have a winner! Congratulations, Player '" + winner + "'!")
break
switch_player()
game_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment