Skip to content

Instantly share code, notes, and snippets.

@santosh
Created January 28, 2019 14:34
Show Gist options
  • Save santosh/609aed00d0795f9f74ff257026131c92 to your computer and use it in GitHub Desktop.
Save santosh/609aed00d0795f9f74ff257026131c92 to your computer and use it in GitHub Desktop.
Tic-Tac-Toe using Python dictionaries.
# Tic-Tac-Toe game; uses numpad for entries
the_board = {
'7': ' ',
'8': ' ',
'9': ' ',
'4': ' ',
'5': ' ',
'6': ' ',
'1': ' ',
'2': ' ',
'3': ' ',
}
def print_board(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])
turn = 'X'
for i in range(9):
print_board(the_board)
print('Turn for', turn + '. Move on which space?')
move = input()
the_board[move] = turn
if the_board['7'] == the_board['8'] == the_board['9'] == turn:
print(turn, 'Won!')
break
if the_board['4'] == the_board['5'] == the_board['6'] == turn:
print(turn, 'Won!')
break
if the_board['1'] == the_board['2'] == the_board['3'] == turn:
print(turn, 'Won!')
break
if the_board['7'] == the_board['4'] == the_board['1'] == turn:
print(turn, 'Won!')
break
if the_board['8'] == the_board['5'] == the_board['2'] == turn:
print(turn, 'Won!')
break
if the_board['9'] == the_board['6'] == the_board['3'] == turn:
print(turn, 'Won!')
break
if the_board['7'] == the_board['5'] == the_board['3'] == turn:
print(turn, 'Won!')
break
if the_board['9'] == the_board['5'] == the_board['1'] == turn:
print(turn, 'Won!')
break
if turn == 'X':
turn = 'O'
else:
turn = 'X'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment