Skip to content

Instantly share code, notes, and snippets.

@arth3mis
Created May 24, 2021 13:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arth3mis/1ca840daa792543546dbed26277cb04e to your computer and use it in GitHub Desktop.
Save arth3mis/1ca840daa792543546dbed26277cb04e to your computer and use it in GitHub Desktop.
Tic Tac Toe in Python, shortest code (17 lines), 2-player console game
f, player = [[0,0,0], [0,0,0], [0,0,0]], 0 # playing field; player turn indicator
while True: # game loop
inp = str.split(input("\nPlayer " + str(player+1) + " (format 'x y'; range 0-2): ").strip(), " ") # placing choice
if f[int(inp[0])][2-int(inp[1])] == 0: # chosen field must be empty
f[int(inp[0])][2-int(inp[1])] = 1 if player == 0 else -1 # player 2 gets -1 value for easier win checking
player = 1 - player # switch player turns for next round
w = [0,0,0, 0,0,0, 0,0] # if a player has won, lines add up to 3 or -3
for i in range(3): # loop for printing the playing field & win checking
for j in range(3):
print(2 if f[j][i] == -1 else f[j][i], "\n" if j == 2 else "", sep=" ", end="") # field display
w[i] += f[i][j] # vertical line
w[3+i] += f[j][i] # horizontal line
w[6] += f[i][i] # diagonal line (top left - bottom right)
w[7] += f[i][2-i] # diagonal line (bottom left - top right)
if (3 in w) or (-3 in w) or (0 not in f[0] and 0 not in f[1] and 0 not in f[2]): # player wins/all fields are full
print("\nPlayer", ("1" if (3 in w) else ("2" if (-3 in w) else "-none-")), "wins.")
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment