Created
June 24, 2019 09:00
-
-
Save afiodorov/5c15b7fa99233ec134c9bd1f1ab65a04 to your computer and use it in GitHub Desktop.
Basic tic tac toe
This file contains hidden or 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
import numpy as np | |
class Board: | |
def __init__(self): | |
self.turn = 0 | |
self.state = np.full((3, 3), "_") | |
def __str__(self): | |
r = f"{self.player()}'s turn\n{self.state}'" | |
if self.winner() is not None: | |
r += f"\nWinner: {self.winner()}" | |
return r | |
def player(self): | |
return ["x", "o"][self.turn % 2] | |
def winner(self): | |
for s in ["x", "o"]: | |
c1 = ((self.state == s).sum(axis=0) == 3).any() | |
c2 = ((self.state == s).sum(axis=1) == 3).any() | |
d1 = (self.state.diagonal() == s).sum() == 3 | |
d2 = (np.fliplr(self.state).diagonal() == s).sum() == 3 | |
if c1 or c2 or d1 or d2: | |
return s | |
def is_finished(self): | |
return self.winner() is not None | |
def play(self, b): | |
i, c = b.split(",") | |
i, c = int(i.strip()), int(c.strip()) | |
if not (0 <= i <= 2): | |
return False | |
if not (0 <= c <= 2): | |
return False | |
if self.state[i][c] != "_": | |
return False | |
self.state[i][c] = self.player() | |
self.turn += 1 | |
return True | |
c = Board() | |
while not c.is_finished(): | |
while not c.play(input('(x, y):')): | |
pass | |
print(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment