Question

use python to do it implement the tic-tac-toe game. What to submit: 1. Your source code...

use python to do it

implement the tic-tac-toe game. What to submit: 1. Your source code 2. Two runs, one user wins and one user loses.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

#code

import random

# method to check if a player has three consecutive occurrences horizontally
def check_horizontally(ticTac, player):
    # Horizontal check for win
    # Loop through each row
   
for row in ticTac:
        # assuming user has won
       
winDetected = True
        for
j in row:
            if j != player:
                # current value does not belong to the player, so not won
               
winDetected = False
                break
        if
winDetected:
            return True
    return False



# method to check if a player has three consecutive occurrences vertically
def check_vertically(ticTac, player):
    # vertical check
   
for j in range(len(ticTac[0])):
        winDetected = True
        for
i in range(len(ticTac)):
            if ticTac[i][j] != player:
                winDetected = False
                break
        if
winDetected:
            return True
    return False



# method to check if a player has three consecutive occurrences diagonally
def check_diagonally(ticTac, player):
    # Diagonal check 1 (top left to bottom right)
   
winDetected = True
    for
i in range(len(ticTac)):
        if ticTac[i][i] != player:
            winDetected = False
            break
    if
winDetected:
        return True

   
# Diagonal check 2 (top right to bottom left)
   
winDetected = True
    for
i in range(len(ticTac)):
        if ticTac[len(ticTac) - 1 - i][i] != player:
            winDetected = False
            break
    if
winDetected:
      return True
    return False



# method to check if a player has won. This will use other methods to check if
# a player with given value has won. To see if X has won, pass tic tac toe board
# and 'X' to the method, To see if O has won, pass tic tac toe board
# and 'O' to the method,

def hasWon(ticTac, player):
    # checking if user has won horizontally, vertically or diagonally
   
if check_horizontally(ticTac, player):
        return True
    if
check_vertically(ticTac, player):
        return True
    if
check_diagonally(ticTac, player):
        return True
    return False


#method to make move to the board, here ticTac is the board
#player is player's character and computer is a flag to denote if
#this is computer's turn or not

def make_move(ticTac, player, computer=False):
    #if no more moves left, not doing anything
   
if no_moves_left(ticTac):
        return
   
#if computer's turn, generating a random move
   
if computer:
        #loops until a random empty location is found
       
while True:
            i=random.randint(0,len(ticTac)-1)
            j=random.randint(0,len(ticTac[0])-1)
            if ticTac[i][j]==' ':
                #found
               
print('Computer chose row: {} and col: {}'.format(i,j))
                ticTac[i][j]=player
                break #end of loop
   
else:
        #loops until valid row, column indices are entered
       
while True:
            print('Your turn')
            i =int(input('Row index: '))
            j = int(input('Column index: '))
            if i<0 or i>=len(ticTac) or j<0 or j>=len(ticTac[0]):
                #invalid
               
print('Invalid row/column')
                continue #continuing loop
           
if ticTac[i][j] == ' ':
                #valid
              
ticTac[i][j] = player
                break
            else
:
                print('That position is already occupied, try another')

#method to check if there are no more moves left
def no_moves_left(ticTac):
    for i in range(len(ticTac)):
        for j in range(len(ticTac[0])):
            if ticTac[i][j]==' ':
                #empty space found
               
return False
    return True
#no empty spaces

#method to print the board

def print_board(ticTac):
    for i in ticTac:
        for j in i:
          print('[{}]'.format(j),end=' ')
        print()

#method to play the game for once
def play():
    #creating board
   
ticTac=[]
    for i in range(3):
        ticTac.append([' ',' ',' '])
    #defining characters for player and computer
   
player='X'
   
computer='O'
   
#starting with random player's turn(either computer or player)
   
player_turn = True
    if
random.randint(0,1)==0:
        player_turn=False
   
print('Player take X and Computer take O')
    if player_turn:
        print('Player starts first')
    else:
        print('Computer starts first')
    #loops until no_moves_left or win
   
while not no_moves_left(ticTac):
        #printing board
       
print_board(ticTac)
        #checking if player's turn
       
if player_turn:
            #making player's move
           
make_move(ticTac,player,computer=False)
            #checking if won
           
if hasWon(ticTac,player):
                #won
               
print('Congratulations, user wins')
                break
        else
:
            #computer's move
           
make_move(ticTac,computer,computer=True)
            if hasWon(ticTac,computer):
                print('Computer wins')
                break
       
#checking if tied
       
if no_moves_left(ticTac):
            print('Its a tie!')
        player_turn=not player_turn

#playing one round
play()

#output 1



Player take X and Computer take O

Player starts first

[ ] [ ] [ ]

[ ] [ ] [ ]

[ ] [ ] [ ]

Your turn

Row index: 0

Column index: 0

[X] [ ] [ ]

[ ] [ ] [ ]

[ ] [ ] [ ]

Computer chose row: 0 and col: 2

[X] [ ] [O]

[ ] [ ] [ ]

[ ] [ ] [ ]

Your turn

Row index: 1

Column index: 0

[X] [ ] [O]

[X] [ ] [ ]

[ ] [ ] [ ]

Computer chose row: 2 and col: 0

[X] [ ] [O]

[X] [ ] [ ]

[O] [ ] [ ]

Your turn

Row index: 1

Column index: 1

[X] [ ] [O]

[X] [X] [ ]

[O] [ ] [ ]

Computer chose row: 0 and col: 1

[X] [O] [O]

[X] [X] [ ]

[O] [ ] [ ]

Your turn

Row index: 1

Column index: 2

Congratulations, user wins







#output 2





Player take X and Computer take O

Computer starts first

[ ] [ ] [ ]

[ ] [ ] [ ]

[ ] [ ] [ ]

Computer chose row: 0 and col: 0

[O] [ ] [ ]

[ ] [ ] [ ]

[ ] [ ] [ ]

Your turn

Row index: 0

Column index: 1

[O] [X] [ ]

[ ] [ ] [ ]

[ ] [ ] [ ]

Computer chose row: 0 and col: 2

[O] [X] [O]

[ ] [ ] [ ]

[ ] [ ] [ ]

Your turn

Row index: 1

Column index: 0

[O] [X] [O]

[X] [ ] [ ]

[ ] [ ] [ ]

Computer chose row: 2 and col: 1

[O] [X] [O]

[X] [ ] [ ]

[ ] [O] [ ]

Your turn

Row index: 1

Column index: 1

[O] [X] [O]

[X] [X] [ ]

[ ] [O] [ ]

Computer chose row: 1 and col: 2

[O] [X] [O]

[X] [X] [O]

[ ] [O] [ ]

Your turn

Row index: 2

Column index: 0

[O] [X] [O]

[X] [X] [O]

[X] [O] [ ]

Computer chose row: 2 and col: 2

Computer wins
Add a comment
Know the answer?
Add Answer to:
use python to do it implement the tic-tac-toe game. What to submit: 1. Your source code...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT