Created
November 12, 2017 21:29
-
-
Save Sparrow1029/100d49bf8fcc50cd206f52e9fa94dd07 to your computer and use it in GitHub Desktop.
(Practice Python) Check win state in a game of tic-tac-toe using matrices
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
#!/usr/bin/env python3 | |
#-*- coding: utf-8 -*- | |
""" | |
Check matrix list for win in Tic-tac-toe | |
""" | |
from itertools import chain | |
winner_is_1 = [[1, 2, 0], | |
[2, 1, 0], | |
[2, 0, 1]] | |
win_1_row = [[1, 0, 2], | |
[1, 1, 1], | |
[2, 2, 0]] | |
winner_is_2 = [[2, 1, 0], | |
[2, 2, 1], | |
[2, 1, 1]] | |
check_0 = [[0, 0, 0], | |
[1, 2, 0], | |
[2, 2, 1]] | |
draw = [[2, 1, 2], | |
[1, 1, 2], | |
[1, 2, 1]] | |
test_list = [winner_is_1, winner_is_2, win_1_row, check_0, draw] | |
def line_win(board): | |
rng = range(3) | |
# Check rows | |
for row in board: | |
chk = set(row) | |
if len(chk) == 1 and 0 not in row: | |
print("Player {} Wins!".format(row[0])) | |
for x in rng: | |
col = set([board[y][x] for y in rng]) | |
if (0 not in col) and len(col) == 1: | |
print("Player {} Wins!".format(board[x][0])) | |
return | |
return False | |
def diag_win(board): | |
l_to_r = list(zip(range(3), range(3))) | |
r_to_l = list(zip(range(3), range(-1, -4, -1))) | |
diags = [l_to_r, r_to_l] | |
# print(l_to_r, r_to_l) | |
for line in diags: | |
nums = [] | |
for coord in line: | |
x, y = coord | |
nums.append(board[x][y]) | |
test = set(nums) | |
if 0 not in test and len(test) == 1: | |
print("Player {} Wins!".format(nums[0])) | |
return | |
return False | |
def stalemate(board): | |
if 0 not in list(chain.from_iterable(board)): | |
if not diag_win(board) and not line_win(board): | |
print("DRAW!") | |
for i in test_list: | |
print("\ntesting {}\n".format(i)) | |
diag_win(i) | |
line_win(i) | |
stalemate(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment