Skip to content

Instantly share code, notes, and snippets.

@technillogue
Created August 6, 2018 14:26
Show Gist options
  • Save technillogue/f8f4076093abda76a4a626d9db70f7ac to your computer and use it in GitHub Desktop.
Save technillogue/f8f4076093abda76a4a626d9db70f7ac to your computer and use it in GitHub Desktop.
class Board:
def __init__(self, n=3):
self.board = [["*" for i in range(n)] for j in range(n)]
self.n = n
def move(self, player):
raw = raw_input("x,y move for player %s? " % player)
try:
x, y = map(int, raw.split(","))
cell = self.board[y][x]
except ValueError:
print "wrong format!"
return self.move(player)
except IndexError:
print "out of bounds!"
return self.move(player)
if not cell == "*":
print "that cell is already taken!"
return self.move(player)
else:
self.board[y][x] = player
# win cons
for row in self.board:
if row.count(player) == self.n:
return player
for col in range(self.n):
if [row[col] for row in self.board].count(player) == self.n:
return player
if (
[self.board[i][i] for i in range(self.n)].count(player) == self.n or
[self.board[i][self.n - i - 1] for i in range(self.n)].count(player) == self.n
):
return player
def render(self):
print " " + "".join(map(str, range(self.n)))
for i, row in enumerate(self.board):
print str(i) + "".join(row)
def play(self):
while 1:
self.render()
if self.move("X"):
print "player X wins!"
return "X"
self.render()
if self.move("O"):
print "player O wins!"
return "O"
if __name__ == "__main__":
board = Board()
board.play()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment