Skip to content

Instantly share code, notes, and snippets.

@FedericoPonzi
Created August 7, 2018 15:17
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 FedericoPonzi/a67eb1d7072547d776ac044b2df2f6f4 to your computer and use it in GitHub Desktop.
Save FedericoPonzi/a67eb1d7072547d776ac044b2df2f6f4 to your computer and use it in GitHub Desktop.
A tic tac toe in python3
class IllegalMoveError(ValueError):
pass
class TicTacToe:
def __init__(self):
self.grid = [0 for i in range(9)]
self.turn = "x"
def run(self):
while not self.isOver():
print("")
print("Next turn: '" + self.turn + "'")
self.printGrid()
move = input(">") #a1 b2
try:
self.doMove(move)
except IllegalMoveError as e:
print("You cannot do that move.")
if self.hasWon("x"):
print("X has won!")
elif self.hasWon("o"):
print("O has won!")
else:
print("It's a tie!")
def printGrid(self):
for i, x in enumerate(self.grid):
if(i%3 == 0):
print(chr(97 + i//3), end ="")
print(" ", x, end="")
if(i% 3 == 2):
print("")
print(" --------------")
else:
print(" |", end ="")
print(" ", end ="")
for i in range(3):
print(i, " ", end="")
print("")
def doMove(self, move):
box = ((ord(move[0])- 97) * 3) + int(move[1])
print(ord(move[0]), " -", ord(move[0])-97, " ", box)
if self.grid[box] != 0 :
raise IllegalMoveError()
self.grid[box] = self.turn
#Switch turn:
if self.turn == "x":
self.turn = "o"
else:
self.turn = "x"
def isOver(self):
if 0 not in self.grid:
return True
if self.hasWon("o") or self.hasWon("x"):
return True
def hasWon(self, el):
return self.any([
[0,4,8],
[1,4,7],
[2,4,6],
[3,4,5],
## Ends with middle
## With top left:
[0,3,6],
[0,1,2],
## With bottom right:
[2,5,8],
[6,7,8],
],
el)
def any(self, winningCombinations, el):
toRet = False
for comb in winningCombinations:
toRet = toRet or all(self.grid[x]==el for x in comb)
return toRet
def main():
game = TicTacToe()
game.run()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment