Created
March 2, 2016 19:28
-
-
Save ralsina/1c1a5ec7bc6fd3eef5a8 to your computer and use it in GitHub Desktop.
Tic-Tac-Toe with the computer player
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
| import copy | |
| board = { | |
| 'A': [' ', ' ', ' '], | |
| 'B': [' ', ' ', ' '], | |
| 'C': [' ', ' ', ' '], | |
| } | |
| def print_board(): | |
| for i in "ABC": | |
| print(" | {} | {} | {} |".format(*board[i])) | |
| def check_winner_state(board, mark): | |
| for i in "ABC": | |
| if board[i] == [mark, mark, mark]: | |
| return True | |
| for j in [0,1,2]: | |
| if [board["A"][j], board["B"][j], board["C"][j]] == [mark, mark, mark]: | |
| return True | |
| if [board["A"][0],board["B"][1],board["C"][2]] == [mark, mark, mark]: | |
| return True | |
| if [board["A"][2],board["B"][1],board["C"][0]] == [mark, mark, mark]: | |
| return True | |
| return False | |
| players_marks = "XO" | |
| print_board() | |
| player_names = {} | |
| for mark in players_marks: | |
| whatever = input("Enter your name for %s" % mark) | |
| player_names[mark] = whatever | |
| def human_player(mark): | |
| return input("Enter turn {}: ".format(mark)).upper() | |
| def computer_player(mark): | |
| # Try everything and see if you can win | |
| other_mark = set(players_marks) - set(mark) | |
| for i in 'ABC': | |
| for j in 0,1,2: | |
| _b = copy.deepcopy(board) | |
| if _b[i][j] != ' ': | |
| continue | |
| _b[i][j] = mark | |
| if check_winner_state(_b, mark): | |
| return i+str(j+1) | |
| # So, we can't win. Try not to lose | |
| for i in 'ABC': | |
| for j in 0,1,2: | |
| _b = copy.deepcopy(board) | |
| if _b[i][j] != ' ': | |
| continue | |
| _b[i][j] = other_mark | |
| if check_winner_state(_b, other_mark): | |
| return i+str(j+1) | |
| # fuck it | |
| for i in 'ABC': | |
| for j in 0,1,2: | |
| if board[i][j] == ' ': | |
| return i+str(j+1) | |
| players = [computer_player, computer_player] | |
| selector = 0 | |
| while True: | |
| turn = selector % 2 | |
| mark = players_marks[turn] | |
| inp = players[turn](mark) | |
| if len(inp) != 2: # A1 | |
| print("Bad format: ", inp) | |
| continue | |
| x, y = inp | |
| if x not in "ABC" or y not in "123": | |
| print("Bad format: ", inp) | |
| continue | |
| y = int(y)-1 | |
| if board[x][y] != ' ': | |
| print("Position taken: ", inp) | |
| continue | |
| # mark the input | |
| board[x][y] = mark | |
| print_board() | |
| if check_winner_state(board, mark): | |
| print("%s, you are the winner, congrats!" % player_names[mark]) | |
| break | |
| if selector == 8: | |
| print("No more goes, no one wins, sorry :(") | |
| break | |
| selector += 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment