Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple text-based Tic Tac Toe implementation. I have no idea why I made this.
#!/usr/bin/env python3
# tictactoe by David Hoppenbrouwers
#
# To the extent possible under law, the person who associated CC0 with
# David Hoppenbrouwers has waived all copyright and related or neighboring rights
# to David Hoppenbrouwers.
#
# You should have received a copy of the CC0 legalcode along with this
# work. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
class Field:
def __init__(self):
self._m = [['_','_','_'],['_','_','_'],['_','_','_']]
def get(self, x, y):
return self._m[x][y]
def set(self, x, y, v):
self._m[x][y] = v
def __str__(self):
m = self._m
return "%c %c %c\n%c %c %c\n%c %c %c" % (
m[0][0], m[1][0], m[2][0],
m[0][1], m[1][1], m[2][1],
m[0][2], m[1][2], m[2][2],
)
def dup(self):
x = []
for a in self._m:
y = []
for b in a:
y.append(b)
x.append(y)
d = Field()
d._m = x
return d
field = Field()
def place(field, x, y):
global cur_player
global next_player
if 0 <= x < 3 and 0 <= y < 3 and field.get(x, y) == '_':
field.set(x, y, cur_player)
return True
return False
def check_victory(field, p, x, y):
if field.get(0, 0) == p and \
field.get(1, 1) == p and \
field.get(2, 2) == p:
return True
if field.get(0, 2) == p and \
field.get(1, 1) == p and \
field.get(2, 0) == p:
return True
if field.get(x, 0) == p and \
field.get(x, 1) == p and \
field.get(x, 2) == p:
return True
if field.get(0, y) == p and \
field.get(1, y) == p and \
p == field.get(2, y):
return True
return False
def det_best_move():
for x in [0,1,2]:
for y in [0,1,2]:
f = field.dup()
place(f, x, y)
if check_victory(f, cur_player, x, y):
return (x, y)
for x in [0,1,2]:
for y in [0,1,2]:
if place(field.dup(), x, y):
return (x, y)
cur_player = 'X'
next_player = 'O'
import random
human_player = 'X' if random.randint(0, 1) else 'O'
print('You are', human_player)
while True:
if cur_player == human_player:
print()
print("X: ", end="")
x = int(input())
print("Y: ", end="")
y = int(input())
else:
x, y = det_best_move()
if place(field, x, y):
print()
print(field)
if check_victory(field, cur_player,x, y):
print()
print(cur_player, "won!")
break
cur_player, next_player = next_player, cur_player
else:
print("Invalid input")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment