Created
September 17, 2015 14:54
-
-
Save jason-feng/670dc37907ff54af4728 to your computer and use it in GitHub Desktop.
A simple python command line tic tac toe game
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 pprint | |
# Returns a row in a given column | |
def column(matrix, i): | |
return [row[i] for row in matrix] | |
# Checks if a given row or column has all of the same value | |
def check(list): | |
if len(set(list)) <= 1: | |
if list[0] != 0: | |
return list[0] | |
return None | |
def checkDiagLeft(board): | |
if (board[0][0] == board[1][1] and board[1][1] == board[2][2]): | |
if board[0][0] != 0: | |
return board[0][0] | |
return None | |
def checkDiagRight(board): | |
if (board[2][0] == board[1][1] and board[1][1] == board[0][2]): | |
if board[2][0] != 0: | |
return board[2][0] | |
return None | |
def placeItem(row, column, board, current_player): | |
if board[row][column] != 0: | |
return None | |
else: | |
board[row][column] = current_player | |
def swapPlayers(player): | |
if (player == 2): | |
return 1 | |
else: | |
return 2 | |
# checks if any player has won the game | |
def winner(board): | |
for rowIndex in board: | |
if check(rowIndex) is not None: | |
return check(rowIndex) | |
for columnIndex in range(len(board[0])): | |
if check(column(board, columnIndex)) is not None: | |
return check(column(board, columnIndex)) | |
if checkDiagLeft(board) is not None: | |
return checkDiagLeft() | |
if checkDiagRight(board) is not None: | |
return checkDiagRight(board) | |
return 0 | |
def getLocation(): | |
location = raw_input("Choose where to play. Enter two numbers seperated by a comma, for example: 1,1 ") | |
coordinates = map(int, location.split(',')) | |
while (len(coordinates) != 2 or coordinates[0] < 0 or coordinates[0] > 2 or coordinates[1] < 0 or coordinates[1] > 2): | |
print "You inputted a location in an invalid format" | |
location = raw_input("Choose where to play. Enter two numbers seperated by a comma, for example: 1,1 ") | |
coordinates = map(int, location.split(',')) | |
return coordinates | |
def gamePlay(): | |
num_moves = 0; | |
pp = pprint.PrettyPrinter(width=20) | |
current_player = 1 | |
board = [[0 for x in range(3)] for x in range(3)] | |
while (num_moves < 9 and winner(board) == 0): | |
print "This is the current board: " | |
pp.pprint(board) | |
coordinates = getLocation(); | |
placeItem(coordinates[0], coordinates[1], board, current_player) | |
current_player = swapPlayers(current_player) | |
if winner(board) != 0: | |
print "%s won!" % winner(board) | |
num_moves += 1 | |
print "There is no winner, the game is over!" | |
gamePlay() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment