Skip to content

Instantly share code, notes, and snippets.

@nf3
Created January 25, 2015 21:06
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 nf3/08b313902cde0500d7f7 to your computer and use it in GitHub Desktop.
Save nf3/08b313902cde0500d7f7 to your computer and use it in GitHub Desktop.
# The MIT License (MIT)
# Copyright (c) 2015 Neil Proctor license@neilproctor.com
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
print("Play Tic-Tac-Toe!!")
# gamewon will check to see if the last played square completes an entire row, col, or diag for the player that
# played it last. By checking just the row col and 2 diags it will
def gamewon(lastx, lasty, lastPlayer):
spaces = ""
# check the diagonals if the square is placed in the backslash \
if (lastx == lasty):
for i in range(0, gridsize):
spaces += str(move_matrix[i][i])
if (spaces == lastPlayer * gridsize):
return True
spaces = ""
# check the diag if the square is placed in the forward slash /
if (gridsize - 1 - lastx == lasty):
for i in range(0, gridsize):
spaces += str(move_matrix[i][gridsize - i - 1])
if (spaces == lastPlayer * gridsize):
return True
# check column that the square was played
spaces = ""
for i in range(0, gridsize):
spaces += str(move_matrix[lastx][i])
if (spaces == lastPlayer * gridsize):
return True
# check row that the square was played
spaces = ""
for i in range(0, gridsize):
spaces += str(move_matrix[i][lasty])
if (spaces == lastPlayer * gridsize):
return True
return False
# Set the defaults for how big the grid is and the upper bounds. 11 is the max for a normal command window to look right
# 2 was choosen as the lower because it is not a game for just 1 person to play. Although 2 really isn't a game either, the
# 1st person always wins, but I kept 2 there for easy testing
default = "3"
bottombound = 2
topbound = 11
nowinner = False
# ask the user to set the game grid size (number of rows/columns)
while True:
try:
user_input = int(
input("Pick a Grid Size [" + default + "]: ") or default)
if (user_input < bottombound) or (user_input > topbound):
raise ValueError(
"Enter an integer " + str(bottombound) + " thru " + str(topbound))
except ValueError as err:
print(err)
else:
break
gridsize = user_input
# Padding is used to figure out how much whitespace to use when square numbers start to take more than a single char
padding = len(str(gridsize * gridsize - 1))
# Draw the grid with all the playable squares
grid = ""
for i in range(0, gridsize):
grid = ""
for j in range(0, gridsize):
grid += " " + str((i) * gridsize + j).rjust(padding, " ") + " "
if (j != gridsize - 1):
grid += "|"
print(grid)
if (i != gridsize - 1):
print("#" * len(grid))
# Data matrix that stores which player played which square
move_matrix = [[0 for x in range(gridsize)] for x in range(gridsize)]
x = 0
y = 0
player = ""
plays = 0
# Until the game is won, alternatingly ask each player to choose a square to play and display the current grid with the last play
while gamewon(x, y, player) == False:
# switch back and forth between players
if (player == "" or player == "O"):
player = "X"
else:
player = "O"
# check to see if the game has tied by seeing if all the squares have been played
if (plays == gridsize * gridsize):
print("Tied, try again")
nowinner = True
break
# ask the player for their square to play and record it in the matrix
while True:
try:
move_input = int(
input(player + " pick your square by entering it's number: "))
if (move_input < 0) or (move_input > gridsize * gridsize - 1):
raise ValueError(
"Enter an integer " + str(0) + " thru " + str(gridsize * gridsize - 1))
x = move_input % gridsize
y = move_input // gridsize
if (move_matrix[x][y] != 0):
raise ValueError("This space has already been taken")
except ValueError as err:
print(err)
else:
move_matrix[x][y] = player
plays += 1
break
# display the grid with the last play
grid = ""
square = ""
for i in range(0, gridsize):
grid = ""
for j in range(0, gridsize):
if (move_matrix[j][i] == 0):
square = str((i) * gridsize + j)
else:
square = move_matrix[j][i]
grid += " " + square.rjust(padding, " ") + " "
if (j != gridsize - 1):
grid += "|"
print(grid)
if (i != gridsize - 1):
print("#" * len(grid))
# if the game was not a tie and there is a winner let that player know they won
if (nowinner == False):
print("Player " + player + " won!! congrats!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment