Ai ML Lab - 3: Write A Python Program For Tic Tac Toe
Ai ML Lab - 3: Write A Python Program For Tic Tac Toe
report
Shreyash hire
20190802114
Code:
def win(i, board, mark):
temp_board = list(board)
temp_board[i] = mark
if winning(mark, temp_board):
return True
else:
return False
def playerinput(mark):
while True:
inp = input(f" '{mark}' Enter your choice:")
if inp.isdigit() and int(inp) < 10 and int(inp) > 0:
inp = int(inp)
if board[inp] == " ":
return inp
else:
print(f" '{mark}' place taken.")
else:
print(f" '{mark}' Enter valid option (1 - 9).")
def display_board():
print()
print(' reference:')
print(' | | ', 10 * ' ', ' | | ', )
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3] + ' ', 10 * ' ', '
1 | 2 | 3 ')
print('-----+----+-----', 10 * ' ', "-----+----+-----")
print(' | | ', 10 * ' ', " | | ")
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6] + ' ', 10 * ' ', "
4 | 5 | 6 ")
print('-----+----+-----', 10 * ' ', "-----+----+-----")
print(' | | ', 10 * ' ', " | | ")
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9] + ' ', 10 * ' ', "
7 | 8 | 9 \n\n")
def main_game():
global board
play = True
board = ['', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
human, cpu = 'x','o'
display_board()
while play:
if human == 'x':
x = playerinput(human)
board[x] = human
display_board()
play = win_check(human, cpu)
if play:
o = cpu_input(cpu, human, board)
print(f'Computer Entered:{o}')
board[o] = cpu
display_board()
play = win_check(human, cpu)
else:
x = cpu_input(cpu, human, board)
print(f'Computer Entered:{x}')
board[x] = cpu
display_board()
play = win_check(human, cpu)
if play:
o = playerinput(human)
board[o] = human
display_board()
play = win_check(human, cpu)
if __name__ == '__main__':
main_game()
Output:
Conclusion: Thus, using Python, we were able to create the code for tic tac toe game.