Skip to content

Instantly share code, notes, and snippets.

@linbug
Last active September 23, 2015 20:12
Show Gist options
  • Save linbug/5a1f96e8b31452d33c30 to your computer and use it in GitHub Desktop.
Save linbug/5a1f96e8b31452d33c30 to your computer and use it in GitHub Desktop.
#TicTacToe (Noughts and Crosses)
######################### Import dependencies
import os
import numpy as np
######################### Functions
def display_title_bar():
''' Clears the terminal screen, and displays a title bar.'''
os.system('clear')
print("\t***********************************************************")
print("\t* Welcome to TicTacToe/ Noughts and Crosses DUEL EDITION *")
print("\t***********************************************************")
print("\n")
def player_move(current_board,player):
'''Player picks a square and makes their move'''
token_dict = {1:'O',2:'X'}
while True:
try:
player_choice = input("Player %d pick a row and a column [row, column]:"%player)
current_board[player_choice[0],player_choice[1]]
break
#if input is invalid, make another choice
except (NameError, TypeError, SyntaxError, IndexError) :
print("Not a valid number! Try again")
#if square is taken, make another choice
while current_board[player_choice[0],player_choice[1]] != '':
player_choice = input("Square already taken! Player %d pick a different row and a column [row, column]:"%player)
current_board[player_choice[0],player_choice[1]] = token_dict[player]
return current_board
def switch(player):
'''switch players after each turn'''
if player == 1:
player = 2
else:
player = 1
return player
def check_uniqueness(array):
'''check any winning combinations in rows and columns'''
unique_array = np.unique(array)
if len(unique_array)==1 and '' not in unique_array:
return 1
else:
return 0
def check_winner(current_board):
'''check the current board to see if there's a winner'''
win = False
for i in range(3):
if 1 in \
{check_uniqueness(current_board[i]), # check rows
check_uniqueness(current_board[:,i]), # check columns
check_uniqueness([current_board[0,0], current_board[1,1], current_board[2,2]]), # diagonals
check_uniqueness([current_board[0,2], current_board[1,1], current_board[2,0]])}: # other diagonals
win = True
return win
######################## Setup
display_title_bar()
current_board = np.array([['','',''],['','',''],['','','']])
player = 1
print(current_board)
######################## Gameplay!
while True:
current_board= player_move(current_board, player)
print current_board
if check_winner(current_board):
print('Player %i is the winner!'%player)
break
elif '' not in current_board:
print("It's a tie!")
break
else:
player = switch(player)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment