|
| 1 | +# W A P to play tic tac toe |
| 2 | + |
| 3 | +import random |
| 4 | + |
| 5 | +def sum(a, b, c): |
| 6 | + return a + b + c |
| 7 | + |
| 8 | +def printBoard(xState, zState): |
| 9 | + zero = 'X' if xState[0] else ('O' if zState[0] else 0) |
| 10 | + one = 'X' if xState[1] else ('O' if zState[1] else 1) |
| 11 | + two = 'X' if xState[2] else ('O' if zState[2] else 2) |
| 12 | + three = 'X' if xState[3] else ('O' if zState[3] else 3) |
| 13 | + four = 'X' if xState[4] else ('O' if zState[4] else 4) |
| 14 | + five = 'X' if xState[5] else ('O' if zState[5] else 5) |
| 15 | + six = 'X' if xState[6] else ('O' if zState[6] else 6) |
| 16 | + seven = 'X' if xState[7] else ('O' if zState[7] else 7) |
| 17 | + eight = 'X' if xState[8] else ('O' if zState[8] else 8) |
| 18 | + |
| 19 | + print("-------------") |
| 20 | + print(f"| {zero} | {one} | {two} |") |
| 21 | + print("|---|---|---|") |
| 22 | + print(f"| {three} | {four} | {five} |") |
| 23 | + print("|---|---|---|") |
| 24 | + print(f"| {six} | {seven} | {eight} |") |
| 25 | + print("-------------") |
| 26 | + |
| 27 | +def checkWin(xState, zState): |
| 28 | + wins = [ |
| 29 | + [0, 1, 2], [3, 4, 5], [6, 7, 8], |
| 30 | + [0, 3, 6], [1, 4, 7], [2, 5, 8], |
| 31 | + [0, 4, 8], [2, 4, 6] |
| 32 | + ] |
| 33 | + for win in wins: |
| 34 | + if sum(xState[win[0]], xState[win[1]], xState[win[2]]) == 3: |
| 35 | + print("\nX Won the match") |
| 36 | + return 1 |
| 37 | + if sum(zState[win[0]], zState[win[1]], zState[win[2]]) == 3: |
| 38 | + print("\nO Won the match") |
| 39 | + return 0 |
| 40 | + return -1 |
| 41 | + |
| 42 | +def computerMove(zState, xState): |
| 43 | + empty_cells = [i for i in range(9) if not (xState[i] or zState[i])] |
| 44 | + return random.choice(empty_cells) |
| 45 | + |
| 46 | +if __name__ == "__main__": |
| 47 | + xState = [0, 0, 0, 0, 0, 0, 0, 0, 0] |
| 48 | + zState = [0, 0, 0, 0, 0, 0, 0, 0, 0] |
| 49 | + turn = 1 |
| 50 | + print("Welcome to Tic Tac Toe\n") |
| 51 | + while True: |
| 52 | + printBoard(xState, zState) |
| 53 | + |
| 54 | + if turn == 1: |
| 55 | + print("\nX's Chance") |
| 56 | + value = int(input("Please enter a value: ")) |
| 57 | + xState[value] = 1 |
| 58 | + else: |
| 59 | + print("\nO's Chance (Computer)") |
| 60 | + value = computerMove(zState, xState) |
| 61 | + zState[value] = 1 |
| 62 | + print(f"Computer's choice: {value}\n") |
| 63 | + |
| 64 | + cwin = checkWin(xState, zState) |
| 65 | + if cwin != -1: |
| 66 | + print("\nMatch over") |
| 67 | + break |
| 68 | + |
| 69 | + turn = 1 - turn |
0 commit comments