Created
August 2, 2017 09:36
-
-
Save rostyq/5a85b4d3e15ef8df71297d05deca1dc5 to your computer and use it in GitHub Desktop.
Exercise on http://www.practicepython.org
Check Tic Tac Toe Exercise 26
This file contains 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
def check_ttt(game_list): | |
# creating list that contain all possible lines in board | |
# 8 lines = 3 horizontal + 3 vertical + 2 diagonal | |
line_list = game_list | |
line_list += list(zip(*game_list)) | |
line_list += [[game_list[i][j] for i, j in zip(range(3), range(3))], | |
[game_list[i][-j] for i, j in zip(range(3), range(1, 4))]] | |
# calculate sum of each line if line have not nulls | |
win_list = [sum(line) for line in line_list if 0 not in line] | |
if 3 in win_list: # sum of line for win to 1st player 1+1+1 = 3 | |
return 1 | |
elif 6 in win_list: # sum of line for win to 1st player 2+2+2 = 6 | |
return 2 | |
else: # if there is no 3 or 6 return 0 -- no winner | |
return 0 | |
if __name__ == '__main__': | |
game = [[1, 2, 0], | |
[2, 1, 0], | |
[2, 1, 1]] | |
winner_is_2 = [[2, 2, 0], | |
[2, 1, 0], | |
[2, 1, 1]] | |
winner_is_1 = [[1, 2, 0], | |
[2, 1, 0], | |
[2, 1, 1]] | |
winner_is_also_1 = [[0, 1, 0], | |
[2, 1, 0], | |
[2, 1, 1]] | |
no_winner = [[1, 2, 0], | |
[2, 1, 0], | |
[2, 1, 2]] | |
also_no_winner = [[1, 2, 0], | |
[2, 1, 0], | |
[2, 1, 0]] | |
print(check_ttt(game), check_ttt(winner_is_2), check_ttt(winner_is_1), | |
check_ttt(winner_is_also_1), check_ttt(no_winner), check_ttt(also_no_winner)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment