Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Given a 3 by 3 list of lists that represents a Tic Tac Toe game board, tell me whether anyone has won, and tell me which player won, if any.
- Where a 0 means an empty square, a 1 means that player 1 put their token in that space, and a 2 means that player 2 put their token in that space."""
- def Check_hor(board):
- """Checks whether a player had 3 in a row horizontally"""
- win = 0
- rowa = board[0]
- rowb = board[1]
- rowc = board[2]
- if rowa.count(1) == 3 or rowb.count(1) == 3 or rowc.count(1) == 3:
- win = 1
- elif rowa.count(2) == 3 or rowb.count(2) == 3 or rowc.count(2) == 3:
- win = 2
- return win
- def Check_ver(board):
- """Checks whether a player had 3 in a row vertically"""
- win = 0
- ver0 = []
- ver1 = []
- ver2 = []
- for i in range(3):
- ver0.append(board[i][0])
- ver1.append(board[i][1])
- ver2.append(board[i][2])
- if ver0.count(1) == 3 or ver1.count(1) == 3 or ver2.count(1) == 3:
- win = 1
- elif ver0.count(2) == 3 or ver1.count(2) == 3 or ver2.count(21) == 3:
- win = 2
- return win
- def Check_dia(board):
- """Checks whether a player had 3 in a row diagonally"""
- win = 0
- diaM = [board[i][i] for i in range(3)]
- diam = [board[i][2 - i] for i in range(3)]
- if diaM.count(1) == 3 or diam.count(1) == 3:
- win = 1
- elif diaM.count(2) == 3 or diam.count(2) == 3:
- win = 2
- return win
- if __name__=="__main__":
- nums = [int(x) for x in input('Enter a board as 9 integers:\n').split()]
- rowa = nums[:3]
- rowb = nums[3:6]
- rowc = nums[6:]
- board = [rowa, rowb, rowc]
- if Check_hor(board) == 1 or Check_ver(board) == 1 or Check_dia(board) == 1:
- print('Player 1 wins!')
- elif Check_hor(board) == 2 or Check_ver(board) == 2 or Check_dia(board) == 1:
- print('Player 2 wins!')
- else:
- print('No winner')
Add Comment
Please, Sign In to add comment