Last active
July 9, 2020 02:52
-
-
Save ifeLawal/a3e73213a8c0c501fcc0cf026e966ded to your computer and use it in GitHub Desktop.
A simple tic tac toe game for 2. Easily run it in your terminal and begin!
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
import random, numpy as np, sys | |
trueFalseArr = [True, False] # used for randomly choosing who goes first | |
# Return tuple of (winner or '' string if no winner, bool value for if game is tied) | |
def checkGameState(board): | |
gameIsNotTied = True | |
winner = '' | |
# check horizontal wins | |
for x in range(len(board)): | |
if(board[x][0] != '_' and all(marker == board[x][0] for marker in board[x])): | |
print('Horizontal win') | |
winner = board[x][0] | |
return winner, gameIsNotTied | |
numpy_array = np.array(board) # store board in a numpy array | |
transpose = numpy_array.T # transpose 2Dimensional array so the vertical matches are in a horizontal array layout | |
# check vertical wins | |
for x in range(len(transpose)): | |
if(transpose[x][0] != '_' and all(marker == transpose[x][0] for marker in transpose[x])): | |
print('Vertical win') | |
winner = transpose[x][0] | |
return winner, gameIsNotTied | |
# check diagonal wins | |
if(board[0][0] != '_' and board[0][0] == board[1][1] and board[1][1] == board[2][2]): | |
print('Diagonal win') | |
winner = board[0][0] | |
return winner, gameIsNotTied | |
if(board[0][2] != '_' and board[0][2] == board[1][1] and board[1][1] == board[2][0]): | |
print('Diagonal win') | |
winner = board[0][2] | |
return winner, gameIsNotTied | |
# check for gameTied | |
for x in range(len(board)): | |
if(any(marker == '_' for marker in board[x])): # if there are any _ markers the game isNotTied | |
return winner, gameIsNotTied | |
return winner, not(gameIsNotTied) | |
# Create initial 2D board | |
def createBoard(): | |
twoDimensionalBoard = [['_','_','_'],['_','_','_'],['_','_','_']] | |
return twoDimensionalBoard | |
# Ask if they want a player vs player game or player vs npc game and check if | |
# the input is a Y or N | |
def requestUserGameChoiceAndCheckIfValid(): | |
userMove = "failure" | |
print("Would you like to have two players? y to have two players, n to play against NPC") | |
for x in range(0, 4): # try 4 times | |
try: | |
userMove = raw_input('--> ').lower() | |
except (AttributeError), e: | |
if(x == 2): | |
print("1 more chance to choose y to have two players or n to play against NPC") | |
elif (x < 3): | |
print("Please only enter either a y or n value") | |
continue | |
if userMove != "y" and userMove != "n": | |
if(x == 2): | |
print("1 more chance to choose y to have two players or n to play against an NPC") | |
elif (x < 3): | |
print("Please only enter either a y or n value") | |
else: | |
if(userMove == "y"): | |
print("You are playing with two players") | |
else: | |
print("You are playing with npc") | |
break | |
if(userMove != "y" and userMove != "n"): | |
print("Too many invalid inputs!") | |
sys.exit() | |
return userMove.upper() | |
# Request user input and check if it's an integer between 0 and 2 | |
def requestUserMoveAndCheckIfValid(): | |
userMove = 'failure' | |
for x in range(0, 4): # try 4 times | |
try: | |
userMove = int(raw_input()) | |
except (NameError, SyntaxError, ZeroDivisionError, ValueError), e: | |
if(x == 2 and x < 3): | |
print("1 more chance for a valid number between 0 and 2") | |
elif (x < 3): | |
print('Please enter an integer') | |
continue | |
if userMove > 2 or userMove < 0: | |
if(x == 2 and x < 3): | |
print("1 more chance for a valid number between 0 and 2") | |
elif (x < 3): | |
print('Please enter an integer between 0 and 2') | |
else: | |
break | |
return userMove | |
# Print 2D board to terminal | |
def printBoard(board): | |
for x in range(len(board)): | |
print(board[x]) | |
# A two player game of tic tac toe | |
def playerVsPlayerGame(ticTacToeBoard): | |
winner = '' | |
gameIsNotTied = True | |
# randomize who starts first | |
playerXTurn = random.choice(trueFalseArr) | |
# run the game | |
while(gameIsNotTied and winner == ''): | |
# check for keyboard interrupt to stop the game | |
try: | |
# notify players of whose turn it is | |
if(playerXTurn): | |
print("It's player 1 (X's) turn!") | |
else: | |
print("It's player 2 (O's) turn!") | |
# take user input to place a marker on the board | |
print("To place your marker, choose your row") | |
rowInput = requestUserMoveAndCheckIfValid() | |
if(rowInput == "failure"): | |
raise KeyboardInterrupt | |
print("Choose your column") | |
columnInput = requestUserMoveAndCheckIfValid() | |
if(columnInput == "failure"): | |
raise KeyboardInterrupt | |
print(rowInput, columnInput) | |
if(ticTacToeBoard[rowInput][columnInput] != "_"): | |
print("That position already has a value, that means:") | |
continue | |
else: | |
ticTacToeBoard[rowInput][columnInput] = "X" if playerXTurn else "O" | |
printBoard(ticTacToeBoard) | |
winner, gameIsTied = checkGameState(ticTacToeBoard) | |
# if no winner swap turns | |
if(winner == '' and gameIsNotTied): | |
playerXTurn = not(playerXTurn) | |
elif(not(gameIsNotTied)): | |
print("This game was tied! Well done to both players!") | |
else: | |
playerWon = 'Player 1 (X)' if playerXTurn else 'Player 2 (O)' | |
print("Player %s won this game. \nThanks for playing!" % (playerWon)) | |
except KeyboardInterrupt: | |
print("\nThanks for checking out Tic Tac Toe in Python!") | |
break | |
# A game with a human player vs NPC | |
def playerVsNPCGame(ticTacToeBoard): | |
print("Game type to come!") | |
sys.exit() | |
# Play through a tic tac toe game | |
def playGame(): | |
# welcome players | |
print("Welcome to Tic Tac Toe in Python. \nHere is the board!") | |
# create and print board in terminal | |
ticTacToeBoard = createBoard() | |
printBoard(ticTacToeBoard) | |
playerVPlayer = True if "Y" == requestUserGameChoiceAndCheckIfValid() else False | |
if(playerVPlayer): | |
playerVsPlayerGame(ticTacToeBoard) | |
else: | |
playerVsNPCGame(ticTacToeBoard) | |
# Play a game a game of Tic Tac Toe | |
playGame() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment