Last active
January 31, 2024 02:21
-
-
Save nicolethenerd/d29399c756c0571f6c98f5e0cb37db0e to your computer and use it in GitHub Desktop.
Terminal Tic Tac Toe
This file contains 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
print("================ Tic Tac Toe ================") | |
def printBoard(gameState): | |
"""Print out the current state of the board""" | |
boardString = ''' | |
0 |1 |2 | |
{0} | {1} | {2} | |
_____|_____|_____ | |
3 |4 |5 | |
{3} | {4} | {5} | |
_____|_____|_____ | |
6 |7 |8 | |
{6} | {7} | {8} | |
| | | |
''' | |
print(boardString.format(*gameState)) | |
def checkWinner(gameState): | |
"""Return "X" or "O" if there is a winner, and None otherwise""" | |
lines = [ | |
[0, 1, 2], | |
[3, 4, 5], | |
[6, 7, 8], | |
[0, 3, 6], | |
[1, 4, 7], | |
[2, 5, 8], | |
[0, 4, 8], | |
[2, 4, 6], | |
] | |
for line in lines: | |
[a, b, c] = line | |
if gameState[a] != " " and gameState[a] == gameState[b] and gameState[a] == gameState[c]: | |
return gameState[a] | |
hasComputerPlayer = False | |
isXsTurn = True | |
def turn(gameState): | |
"""Handle a single turn of Tic Tac Toe""" | |
global isXsTurn | |
printBoard(gameState) | |
if isXsTurn: | |
print("X's Turn") | |
num = int(input("Where will you place your X? (0-8) ")) | |
else: | |
print("O's Turn") | |
if hasComputerPlayer: | |
num = computerTurn() | |
else: | |
num = int(input("Where will you place your O? (0-8) ")) | |
if num in range(0, 9): | |
if gameState[num] == " ": | |
gameState[num] = ("X" if isXsTurn else "O") | |
isXsTurn = not isXsTurn | |
else: | |
print("That square is occupied. Try again.") | |
else: | |
print("Be sure to pick a number in the range 0-8. Try again.") | |
def computerTurn(): | |
# TODO Return a number from 0-8 where the computer will place an O | |
return -1 | |
def playGame(): | |
"""Play a game of Tic Tac Toe""" | |
gameState = [" "] * 9 | |
isXsTurn = True | |
winner = checkWinner(gameState) | |
while winner == None: | |
turn(gameState) | |
winner = checkWinner(gameState) | |
printBoard(gameState) | |
print("Winner: %s" % checkWinner(gameState)) | |
playGame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment