Created
August 3, 2020 22:41
-
-
Save cdw/8763e1fa9989cb0e823fbd76b9d699ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
from typing import List, Union | |
import numpy as np | |
class TicTacToe: | |
"""Play a game of tictactoe, optionally against a human""" | |
def __init__(self, human_opponent: bool = True): | |
self.board = np.tile(" ", (3, 3)) | |
self._sides = ("X", "O") | |
self.human_opponent = human_opponent | |
while not self.who_won(): | |
for side in self._sides: | |
self.turn(side) | |
if self.who_won(): | |
break | |
def __repr__(self): | |
b = self.board | |
rows = [f" {r[0]} ║ {r[1]} ║ {r[2]} \n" for r in self.board] | |
sep = "═══╬═══╬═══\n" | |
return sep.join(rows) | |
def printboard(self): | |
"""Pretty print the board""" | |
print("Current board is:\n" + self.__repr__()) | |
def who_won(self): | |
"""Has either side won? If so which?""" | |
rows = self.board | |
cols = self.board.T | |
diag = (self.board.diagonal(), self.board.T.diagonal()) | |
for side in self._sides: | |
wrow = any([all([v == side for v in row]) for row in rows]) | |
wcol = any([all([v == side for v in col]) for col in cols]) | |
wdia = any([all([v == side for v in dia]) for dia in diag]) | |
side_won = any((wrow, wcol, wdia)) | |
if side_won: | |
return side | |
if " " not in self.board.flat: | |
return "Neither" | |
return False | |
def set_position(self, row: int, col: int, side: str): | |
"""Set a loc (row, col) to belong to side, False illegal""" | |
if self.board[row, col] == " ": | |
self.board[row, col] = side | |
return True | |
else: | |
return False | |
def turn(self, side): | |
"""Take a turn""" | |
self.printboard() | |
if side == "X": | |
print("X's turn, input as row,col:") | |
row, col = [int(x) for x in input().split(",")] | |
elif side == "O" and self.human_opponent: | |
print("O's turn, input as row,col:") | |
row, col = [int(o) for o in input().split(",")] | |
elif side == "O" and not self.human_opponent: | |
print("O's turn, computer version") | |
row, col = 0, 0 | |
pass | |
while not self.set_position(row, col, side): | |
print("Invalid move, try again:") | |
row, col = [int(o) for o in input().split(",")] | |
if self.who_won() != False: | |
print(f"{self.who_won()} won") | |
if __name__ == "__main__": | |
print(TicTacToe()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment