954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

function to determine the outcome of a game of tictactoe - help required.

I have the task of writing a function to determine the outcome of a game of tictactoe, i at first thought use a couple of for loops but that proved pointless, and then the only way i could think of was to write an if...elif...else statement for each row, column and diagonal. which isnt very impressive, so can anyone show me, or hint at a way to do this?
below is exactly what it says on the site.

In the pencil-and-paper game, Tic-tac-toe, 2 players take turns to mark 'X' and 'O' on a board of 3x3 squares. The player who succeeds in marking 3 successive 'X' or 'O' in vertical, horizontal or diagonal stripe wins the game. Write a function that determines the outcome of a tic-tac-toe game.

Examples

    >>> tictactoe([('X', ' ', 'O'), 
                   (' ', 'O', 'O'), 
                   ('X', 'X', 'X') ])
    "'X' wins (horizontal)."
    >>> tictactoe([('X', 'O', 'X'), 
    ...            ('O', 'X', 'O'), 
    ...            ('O', 'X', 'O') ])
    'Draw.'
    >>> tictactoe([('X', 'O', 'O'), 
    ...            ('X', 'O', ' '), 
    ...            ('O', 'X', ' ') ])
    "'O' wins (diagonal)."
    >>> tictactoe([('X', 'O', 'X'), 
    ...            ('O', 'O', 'X'), 
    ...            ('O', 'X', 'X') ])
    "'X' wins (vertical)."


Help much appreciated.

pwolf
Junior Poster in Training
71 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

Sets are the way to go

# assumes each square is numbered 1 thorugh 9, not 0 through 8
##             rows, columns, & diagonals
winner_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9], \
               [1, 4, 7], [2, 5, 8], [3, 6, 9], \
               [1, 5, 9], [3, 5, 7]]

""" use something like
for winner in winner_list:
    if set(winner).issubset(player_set):

so
tictactoe([('X', ' ', 'O'), 
           (' ', 'O', 'O'), 
           ('X', 'X', 'X') ])
becomes [1, 7, 8, 9] for X
and [3, 5, 6] for O

A tie = all squares filled and no winner
""" 
X=[1, 7, 8, 9]
for winner in winner_list:
    if set(winner).issubset(set(X)):
        print "Is a winner", winner
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: