"""
# Tic Tac Toe

Author: Tlamangile Ngobeni
Lecture: Gary Stewart
Department: University of Cape Town
Website: www.uct.ac.za
Last edited: March 2011
"""

from random import*  # to alternate who play first
def move(position,matrix,symbol): #define the fuction to make a move by replacing to list
    #if statement to check user input move and replace to list
    if position == 1:
        matrix[0][0] =symbol
    if position == 2:
        matrix[0][1] =symbol
    if position == 3:
        matrix[0][2] =symbol
    if position == 4:
        matrix[1][0] =symbol
    if position == 5:
        matrix[1][1] =symbol
    if position == 6:
        matrix[1][2] =symbol
    if position == 7:
        matrix[2][0] =symbol
    if position == 8:
        matrix[2][1] =symbol
    if position == 9:
        matrix[2][2] =symbol
    if position>9:   # invalid move print
        print('Invalid Move!!, try again!')
    if position<=0:  # invalid move print
        print('Invalid Move!!, try again!')
    if 0<position<=9:  # GRID PRINT
        for row in matrix:  # go through the list and break to rows
            for item in row:  # go through rown and break to lines
                print(item, end=' | ') # print line
            print('\n-----------') # print lines below        

def win_check(matrix,player_1,player_2):
    '''This fuction will check if one user won before grid is full, and then terminate the program. I have realised that the fuction consist of sublist and use list to check for winner. I have slice all possible lines and put them in big list, then check for winner'''

    winner='' # intialise winner
    #HORIZONTAL LINES
    hori_win_line=[] # intialise horizontal winning lines
    for row in matrix: # interate matrix row
        hori_win_line.append(row) # add row to horizontal list 
    #VERTICAL LINES
    line_a=[matrix[0][0],matrix[1][0],matrix[2][0]] # 1st vertical line
    line_b=[matrix[0][1],matrix[1][1],matrix[2][1]]# 2nd vertical line
    line_c=[matrix[0][2],matrix[1][2],matrix[2][2]]# 3rd vertical line
    ver_win_line=[line_a,line_b,line_c] # list of vertical possible winning line
    #DIAGONAL LINES
    line_1=[matrix[0][0],matrix[1][1],matrix[2][2]] # 1st diagonal line
    line_2=[matrix[0][2],matrix[1][1],matrix[2][0]] # 2nd diagonal line
    dia_win_line=[line_1,line_2]
    #TOTAL WINNING LINES
    win_lines=hori_win_line+ver_win_line+dia_win_line
    #CHECK THE WINNER
    for row in win_lines:# check if user won
        if row ==['X','X','X']: 
            winner='Player_X'
        if row ==['O','O','O']:
            winner='Player_O'
    #Specify who win and return to main fuction
    if winner=='Player_X':
        winner=player_1
    if winner=='Player_O':
        winner=player_2
    if winner=='':
        winner='Draw!'
    return winner   # returning winner to user

def Scoreboard(winner,player_1,player_2):  # this fuction store score to file
    f=open('Scoreboard.txt','a')  #open file 
    print('THE SCOREBOARD FOR TICTACTOE GAME',end='\n',file=f) # write in file
    print(str(player_1) + ' vs ' + str(player_2),end='\n',file=f) # write in file
    print(player_1, 'played first',end='\n',file=f) # write in file
    print('Score : The winner is '+str(winner)+'\n',file=f) # write in file
    f.close() # close file

def main():
    while True:  # PLAYER 1 NAME INPUT
        try:
            player_1=str(input('Enter Name Player 1:'))
            break
        except ValueError:
            print('Invalid name is entered!, try again')
        except:
            print('Unkown Error is entered!,Try again!!')
    while True:   # PLAYER 2 NAME INPUT
        try:
            player_2=input('Enter name player 2:')
            break
        except ValueError:
            print('Invalid name is entered!, try again')
        except:
            print('Unkown Error is entered!,Try again!!')


    while True:
        matrix=[ ['1','2','3'], ['4','5','6'], ['7','8','9'] ]  # make my 2D list Matrix
        moves_played=[]   #INTIALISE MOVES PLAYED ALREADY
        print("\nGame Start ")
        alternating=[player_1,player_2]
        n=len(alternating)-1
        alternating_who_plays_first=alternating[randint(0,n)].capitalize()
        if alternating[0] !=alternating_who_plays_first:
            alternating_who_plays_second=alternating[0].capitalize()
        elif alternating[1] !=alternating_who_plays_first:
            alternating_who_plays_second=alternating[1].capitalize()

        print('\n',alternating_who_plays_first,'Play first : \n')

        #capitalise the players names
        player_1=alternating_who_plays_first
        player_2=alternating_who_plays_second
        while True: # LOOP TO KEEP USERS PLAYING AFTER ANOTHER
            while True:# LOOP TO CHECK CORRECT MOVE PLAYER 1
                try:
                    move_1=int(input(str(player_1)+" enter move :")) #move by player 1
                    if 0<move_1<=9:
                        if move_1 not in moves_played:
                            moves_played.append(move_1) # apppend played move to move list
                            move(move_1,matrix,'X')    # calling move fuction and prnt grid
                            break
                        else:
                            print('Move already played!,Try again!')
                    else:
                        move1(move_1,matrix,'X')
                except ValueError:
                    print('Invalid move is entered,Try again!')
                except:
                    print('Some error occured, try again!')

            winner= win_check(matrix,player_1,player_2)   
            if winner != 'Draw!':
                print('Game Over!')
                print('Winner is ',winner)
                break
            if len(moves_played)==9:
                print(winner)
                print('GAME IS OVER!!')
                break 
            while True:   # LOOP TO CHECK CORRECT MOVE PLAYER 2
                try:
                    move_2=int(input(str(player_2)+" enter move :"))#move by player 2
                    if 0<move_2<=9:
                        if move_2 not in moves_played:
                            moves_played.append(move_2) # apppend played move to move list
                            move(move_2,matrix,'O')    # calling move fuction and prnt grid
                            break
                        else:
                            print('Move already played!,Try again!')
                    else:
                        move(move_2,matrix,'X')
                except ValueError:
                    print('Invalid move is entered,Try again!')
                except:
                    print('Some error occured, try again!')

            winner= win_check(matrix,player_1,player_2)   
            if winner != 'Draw!':# Abort the program if one user wins
                print('Winner is ',winner)
                break   
            if len(moves_played)==9:# terminate if grid is full
                print(winner)
                print('GAME IS OVER!!')
                break 
        winner= win_check(matrix,player_1,player_2) # determine winner 
        Scoreboard(winner,player_1,player_2) # serve score to file

        try: # this part ask users to play again
            answer=(input('Do you want to play again? (n/y)')).lower()
            if answer!='y':break
        except:
            print('Invalid answer is entered')
            break
main()#calling main fuction
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.