Skip to content

Instantly share code, notes, and snippets.

@shivams
Created December 31, 2020 22:22
Show Gist options
  • Save shivams/57f03d8a13b7b7df7b4ce5a8193720d2 to your computer and use it in GitHub Desktop.
Save shivams/57f03d8a13b7b7df7b4ce5a8193720d2 to your computer and use it in GitHub Desktop.
This is a game of tic-tac-toe developed for Recurse Center's application.
#!/usr/bin/python
#A game of tic-tac-toe for Recurse Center
#Instead of crosses and zeros, I've used 0's and 1's to depict player-0 and player-1 respectively
import os
def display():
'''
This function displays the board
and refreshes the view everytime it's called
'''
os.system('clear')
print("Cells are numbered frorm 0-8 in the following fashion")
for i in range(9):
print(i, end=' ')
if (i+1)%3 == 0:
print("\n")
print("Now, here is your board:")
for i in range(9):
print(board[i], end=' ')
if (i+1)%3 == 0:
print("\n")
def checkStatus():
'''
This checks the status of the board and
returns the winner if someone has won
else returns False
'''
winConditions = [
{0,1,2}, {3,4,5}, {6,7,8},
{0,4,8}, {2,4,6}, {0,3,6},
{1,4,7}, {2,5,8}
]
for player in range(2):
if player in board:
indices = [i for i, x in enumerate(board) if x == player]
for cond in winConditions:
if cond <= set(indices):
return player
return False
def updateBoard(player, position):
'''
This updates the board
If the board can't be updated, it returns False
'''
if board[position] != '_':
return False
else:
board[position] = player
display()
return True
def takeInput(player):
while True:
try:
position = int(input(f"Player-{player} Turn (type a number between 0 to 8): "))
if updateBoard(player, position):
break
else:
print("Position already occupied. Please enter again.")
except ValueError:
print("Enter a number from 0-8")
status = checkStatus()
return status
def runGame():
while True:
for i in range(2):
response = takeInput(i)
if response is not False:
print(f"And the winner is player-{response}")
return
if __name__ == '__main__':
board = ['_']*9
display()
try:
runGame()
except KeyboardInterrupt:
print('interrupted!')
print("The game has ended")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment