Wednesday, July 4, 2012

Implementing Tic-Tac-Toe in Python

This is my simple tic-tac-toe implementation in Python.
#!/usr/bin/env python

class TicTacToe(object):
    def __init__(self, n=3):
        self.n = n
        self.board = []
        for i in xrange(self.n):
            self.board.append([])
            for j in xrange(self.n):
                self.board[i].append(" ")
        
    def draw(self):
        for x in self.board:
            print x
            
    def move(self, player, x, y):
        if x >= self.n or y >= self.n:
            raise Exception("Invalid move!")
        if self.board[x][y] != " ":
            raise Exception("Invalid move!")
        self.board[x][y] = player
    
    def win(self, player):
        same = True
        for i in xrange(self.n):
            if self.board[0][i] != player: 
                same = False
                break
        if same: return True
        
        same = True
        for i in xrange(self.n):
            if self.board[i][0] != player:
                same = False
                break
        if same: return True
        
        same = True        
        for i in xrange(self.n):
            if self.board[self.n-1][i] != player:
                same = False
                break
        if same: return True

        same = True
        for i in xrange(self.n):
            if self.board[i][self.n-1] != player:
                same = False
                break
        if same: return True
        
        same = True
        for i in xrange(self.n):
            if self.board[i][i] != player:
                same = False
                break
        if same: return True
        
        same = True
        x = -1
        y = self.n
        for i in xrange(self.n):
            x += 1
            y -= 1
            if self.board[x][y] != player:
                same = False
                break
        if same: return True
        return False
                

if __name__ == "__main__":
    player1 = "X"
    player2 = "O"
    
    t3 = TicTacToe()
    
    t3.move(player1, 2, 0)
    t3.move(player2, 1, 2)
    
    t3.move(player1, 1, 1)
    t3.move(player2, 2, 1)
    
    t3.move(player1, 0, 2)
    
    t3.draw()
    
    print "Player1", "won" if t3.win(player1) else "lost"
    print "Player2", "won" if t3.win(player2) else "lost"

No comments:

Post a Comment