Skip to content

Instantly share code, notes, and snippets.

@mm-wang
Created May 20, 2015 16:57
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 mm-wang/190c775c85b0476b8c43 to your computer and use it in GitHub Desktop.
Save mm-wang/190c775c85b0476b8c43 to your computer and use it in GitHub Desktop.
A Tic Tac Toe Game
def draw_board(board):
''' Prints the board in its current stage
"board" is a list of 9 elements
'''
# Prints the board as it is described at the current stage
# "board" is a list of 9 elements
print(' | | ')
print(' ' + str(board[0]) + ' | ' + str(board[1]) + ' | ' + str(board[2]))
print(' | | ')
print('-----------------')
print(' | | ')
print(' ' + str(board[3]) + ' | ' + str(board[4]) + ' | ' + str(board[5]))
print(' | | ')
print('-----------------')
print(' | | ')
print(' ' + str(board[6]) + ' | ' + str(board[7]) + ' | ' + str(board[8]))
print(' | | ')
print('\n')
def play_board(pos, player, piece):
''' Puts a piece from the player on a specific position.
Checks to see if the position is filled and valid
'''
board = board_contents("status")
valid = board[pos-1] == ' '
while not valid:
if (board[pos-1] == "X") or (board[pos-1] == "O"):
print("Sorry, that spot is already filled. Pick again.")
pos, piece = pick_position(player, piece)
break
elif (board[pos-1] > 9) or (board[pos-1] < 1):
print("That is not a valid position, please try again.")
pos, piece = pick_position(player, piece)
break
else:
valid = True
board = board_contents("play", pos, piece)
return board
def board_contents(option = "status", pos = -1, piece = "+", board = [' ']*9):
''' Fills the board based on the option.
"positions" shows the numeric selection of each spot
"blank" shows a blank board to start
"play" fills the blank board with a symbol at the correct spot
"status" shows the board at its current status
'''
for i in range(9):
if option == "positions":
board[i] = i+1 # defines the positions to play
if option == "blank":
board[i] = ' '
elif option == "play":
board[pos-1] = piece
return board
def play_2players():
''' Prompts for two users' names
'''
first_player = raw_input("What is the name of the first player? ")
second_player = raw_input("What is the name of the second player? ")
return first_player.capitalize(), second_player.capitalize()
def pick_pieces(player):
''' Allows the first player to pick a piece to play, X or O
'''
pieces = ['X','O']
valid = False
while not valid:
first_piece = raw_input("What piece would %s like to play, X or O? " %player)
piece1 = first_piece.upper()
if piece1 in pieces:
valid = True
if pieces.index(piece1) == 0:
piece2 = 'O'
elif pieces.index(piece1) == 1:
piece2 = 'X'
else:
print("Not a valid piece, please pick between X and O.")
return piece1, piece2
def pick_position(player, piece):
''' Allows a player to pick a specific spot to put the piece
Reprompts if the spot is not a valid number
'''
valid = False
while not valid:
try:
spot = int(raw_input("Pick a spot, %s: " % player))
if spot in range(1,10):
valid = True
else:
print("Not a valid position, please pick a spot between 1 and 9")
except ValueError:
print("That's not a number, please pick a spot between 1 and 9")
return spot, piece
def check_win(board, player, piece):
''' Checks to see if someone has won according to the possible selections
'''
wins = [[0,1,2],[3,4,5],[6,7,8], # top, middle, bottom
[0,3,6],[1,4,7],[2,5,8], # left, center, right
[0,4,8],[2,4,6]] # diagonals
for win in wins:
if board[win[0]] == piece and board[win[1]] == piece and board[win[2]] == piece:
print("%s wins! Congratulations %s!") % (piece, player)
return True
return False
def play(p1, p1pick, p2, p2pick):
''' Plays the game in turns between each player until a player has won
or the board is full
Counts the number of rounds of play
Stops the loop if there is a win
'''
results = []
round = 0
win = False
while not win:
print("Round #%d")%(round+1)
spot1, p1pick = pick_position(p1, p1pick)
results = play_board(spot1, p1, p1pick)
draw_board(results)
win = check_win(results, p1, p1pick)
if win or ' ' not in results:
print("Game over!")
break
spot2, p2pick = pick_position(p2, p2pick)
results = play_board(spot2, p2, p2pick)
draw_board(results)
win = check_win(results, p2, p2pick)
round += 1
def start_game():
''' Starts the game with asking for player names, pieces, and displays board spots
'''
print("Welcome! Let's play Tic Tac Toe!")
p1, p2 = play_2players()
p1pick, p2pick = pick_pieces(p1)
print("Okay, %s will play %s and %s will play %s") %(p1, p1pick, p2, p2pick)
print("To select a spot, please refer to the board positions below.")
draw_board(board_contents("positions"))
print("Let's start the game!")
draw_board(board_contents("blank"))
play(p1, p1pick, p2, p2pick)
### PLAY GAME
start_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment