dojo-oxo / noughtsandcrosses.py

#!/usr/bin/env python

"""
Noughts and crosses bot created by "Team A"
"""

import sys

def play(board, index):
	proposed_board = list(board)
	proposed_board[index] = our_character
	print ''.join(proposed_board)
	sys.exit(0)

def get_row_indexes():
	for x in range(3):
		yield [(x+y*3) for y in range(3)]

def get_column_indexes():
	for y in range(3):
		yield [(x+y*3) for x in range(3)]

def get_diagonal_indexes():
	yield [(x+y*3) for x in range(3) for y in range(3)]
	yield [(x+y*3) for x in range(3) for y in reversed(range(3))]

def get_corner_indexes():
	return [0, 2, 6, 8]

def get_opposite_corner(index):
	ordered_corner_index = [0, 2, 6, 8]
	index = ordered_corner_index.index(index)
	return ordered_corner_index[-index-1]

def is_middle_square_free(board):
	return board[4] == '-'

def play_next_move(board, our_char):
	pass

def is_game_finished(board):
	for index_type in [ get_diagonal_indexes, get_column_indexes, get_row_indexes ]:
		if squares_all_taken_by_player(board, index_type()):
			return board[index_type()[0][0]]
	return False



def squares_all_taken_by_player(board, indexes_list):
	for indexes in indexes_list:
		squares = [board[i] for i in indexes]
		if '-' in squares:
			return False
		elif squares[0] == squares[1] and squares[1] == squares[2]:
			return squares[0]

board = raw_input()
our_character = sys.argv[1]
their_character = 'XO'['X' == our_character]
#our_character = 'XO'['X' in board]

# play winning move
for index in range(9):
	if board[index] != '-':
		continue
	proposed_board = list(board)
	proposed_board[index] = our_character

	if is_game_finished(proposed_board) == our_character:
		play(board, index)

# Stop losing move
for index in range(9):
	if board[index] != '-':
		continue
	proposed_board = list(board)
	proposed_board[index] = their_character

	if is_game_finished(proposed_board) == their_character:
		play(board, index)

# play middle
if is_middle_square_free(board):
	play(board, 4)

# play opposite corner
for index in get_corner_indexes():
	if board[index] == their_character:
		opposite_corner = get_opposite_corner(index)
		if board[opposite_corner] == '-':
			play(board, get_opposite_corner(index))

# play something possible
play(board, board.index('-'))
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.