Skip to content

Instantly share code, notes, and snippets.

@ncdejito
Created June 2, 2022 08:50
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 ncdejito/536ff3809343c83a45e378ed2307a3f6 to your computer and use it in GitHub Desktop.
Save ncdejito/536ff3809343c83a45e378ed2307a3f6 to your computer and use it in GitHub Desktop.
import numpy as np
class Board:
# looks like this:
# 1 2 3
# a x x o
# b x o -
# c - - x
def init(self):
self.contents = np.array(["-" for i in range(9)]).reshape((3,3))
self.won = False
def mark(self,location,symbol):
letter_translator = {'a':0,'b':1,'c':2}
row = letter_translator[location[0]]
col = int(location[1])-1
self.contents[row,col] = symbol
def check_wins(self):
def check_if_all_equal(triplet):
return (
triplet[0] != "-" and triplet[1] != "-" and triplet[2] != "-" and
triplet[0] == triplet[1] and triplet[1] == triplet[2]
)
triplets = []
# horizontal
triplets.append(self.contents[0,:])
triplets.append(self.contents[1,:])
triplets.append(self.contents[2,:])
# vertical
triplets.append(self.contents[:,0])
triplets.append(self.contents[:,1])
triplets.append(self.contents[:,2])
# diagonal
triplets.append(self.contents.diagonal())
triplets.append(self.contents.transpose().diagonal())
checks = []
for triplet in triplets:
checks.append(check_if_all_equal(triplet))
if sum(checks) > 0:
self.won = True
def show(self):
print(
" 1 2 3"
+ "\na " + " ".join(list(self.contents[0,:]))
+ "\nb " + " ".join(list(self.contents[1,:]))
+ "\nc " + " ".join(list(self.contents[2,:]))
)
# main
board = Board()
board.init()
game_over = False
symbol = 'X' # O goes first, will be switched in first step of loop
switch = {'O':'X','X':'O'}
while not game_over:
while not board.won:
symbol = switch[symbol]
board.show()
location = input("Input: ")
board.mark(location,symbol)
board.check_wins()
print(f"Player {symbol} won!!")
val = input("Replay? (y/[n])")
if val == "y":
board.init()
game_over = False
else:
game_over = True
# # AI
# Moves that will block an opponents 2 pattern
# Moves that will form a winning pattern - sorted by how many patterns it can form
# Moves that disorient the opponent - farthest from your existing tiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment