Created
October 26, 2020 13:25
-
-
Save sXakil/1f05e6302e358d35934d07d50863180f to your computer and use it in GitHub Desktop.
Simple Tic Tac Toe
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from random import randint | |
| board = [ | |
| [0, 0, 0], | |
| [0, 0, 0], | |
| [0, 0, 0], | |
| ] | |
| def eq(arr): | |
| s = set(arr) | |
| if 0 not in s and len(s) == 1: | |
| return True | |
| return False | |
| def checkWinner(): | |
| if eq([board[0][0], board[1][1], board[2][2]]) or eq([board[0][2], board[1][1], board[2][0]]): | |
| return board[1][1] | |
| for row in board: | |
| if eq(row): | |
| return row[0] | |
| for i in range(3): | |
| col = [b[i] for b in board] | |
| if eq(col): | |
| return col[0] | |
| return 0 | |
| def display(): | |
| for row in board: | |
| for cell in row: | |
| symb = '-' | |
| if cell == 1: | |
| symb = 'x' | |
| elif cell == 2: | |
| symb = 'o' | |
| print("|"+symb, end="") | |
| print("|") | |
| print("\n") | |
| gameEnded = True | |
| move = 0 | |
| while True: | |
| display() | |
| result = checkWinner() | |
| if result != 0: | |
| print(['x', 'o'][result-1] + " have won the game!") | |
| break | |
| for row in board: | |
| if 0 in row: | |
| gameEnded = False | |
| break | |
| else: | |
| gameEnded = True | |
| if gameEnded: | |
| print('Draw!') | |
| break | |
| while True: | |
| #[x, y] = list(map(int, input(['x', 'o'][move%2] + "'s move: ").split(' ')))[:2] | |
| x = randint(0, 2) | |
| y = randint(0, 2) | |
| if x > 2 or y > 2 or board[x][y] != 0: | |
| # print('Invalid input, try again: ') | |
| continue | |
| else: | |
| print(['x', 'o'][move%2] + "'s move (" + str(x) + ", " + str(y) +")") | |
| board[x][y] = [1,2][move%2] | |
| move += 1 | |
| break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment