Advertisement
Guest User

Untitled

a guest
May 19th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.58 KB | None | 0 0
  1. import itertools
  2.  
  3.  
  4. # Function to play game
  5. def play_game(current, player=0, row=0, column=0, display=False):
  6. print(" " + " ".join([str(i) for i in range(game_size)]))
  7. if not display:
  8. current[row][column] = player
  9. for count, row in enumerate(current):
  10. print(count, row)
  11. return current
  12.  
  13.  
  14. # Function to determine who is winner
  15. def winner(current):
  16. # Horizontal Winner
  17. for row in current:
  18. if row.count(row[0]) == len(current[0]) and row[0] != 0:
  19. print(f"Play {row[0]} is the horizontal winner.")
  20. return True
  21.  
  22. # Vertical Winner
  23. for col in range(len(current[0])):
  24. check = []
  25. for row in current:
  26. check.append(row[col])
  27. if check.count(check[0]) == len(check) and check[0] != 0:
  28. print(f"Player {check[0]} is the vertical winner.")
  29. return True
  30.  
  31. # Diagonal Winner
  32. # Case(\):
  33. # if current[0][0] == current[1][1] == current[2][2]:
  34. # print("Winner")
  35. diags = []
  36. for row, col in enumerate(range(len(current[0]))):
  37. diags.append(current[row][col])
  38. if diags.count(diags[0]) == len(diags) and diags[0] != 0:
  39. print(f"Player {diags[0]} is the diagonal winner (\\)")
  40. return True
  41.  
  42. # Case(/):
  43. # if current[0][2] == current[1][1] == current[2][0]:
  44. # print("Winner")
  45. diags = []
  46. for row, col in enumerate(reversed(range(len(current[0])))):
  47. diags.append(current[row][col])
  48. if diags.count(diags[0]) == len(diags) and diags[0] != 0:
  49. print(f"Player {diags[0]} is the diagonal winner (/)")
  50.  
  51. return False
  52.  
  53.  
  54. play = True
  55. players = [1, 2]
  56. while play:
  57.  
  58. game_size = int(input("What size game TicTacToe? "))
  59. game = [[0 for i in range(game_size)] for i in range(game_size)]
  60.  
  61. won = False
  62. player_cycle = itertools.cycle(players)
  63. play_game(game, display=True)
  64. while not won:
  65. current_player = next(player_cycle)
  66. played = False
  67. while not played:
  68. print(f"Current player is {current_player}")
  69. column_choice = int(input("Choose column: "))
  70. row_choice = int(input("Choose row: "))
  71. played = play_game(game, player=current_player, row=row_choice, column=column_choice)
  72.  
  73. if winner(game):
  74. won = True
  75. restart = input("Would you like to play again? ")
  76. if restart.lower() == "y":
  77. print("Restarting!")
  78. elif restart.lower() == "n":
  79. print("Good bye")
  80. play = False
  81. else:
  82. print("Invalid answer.")
  83. play = False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement