Guest User

Untitled

a guest
Apr 19th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. class Field:
  2. val = " "
  3. pos = 0
  4. weight = 0
  5.  
  6. def __init__(self, n):
  7. self.pos = n
  8. self.val = str(n)
  9.  
  10.  
  11. def display_board(b):
  12. br = 1
  13.  
  14. for i in b:
  15. if br >= 3:
  16. print("[", i.val, "]", end='n')
  17. br = 0
  18. else:
  19. print("[", i.val, "]", end='')
  20.  
  21. br += 1
  22.  
  23.  
  24. def did_player_won(b, t):
  25. indexes = (
  26. (0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows
  27. (0, 3, 6), (1, 4, 7), (2, 5, 8), # Cols
  28. (0, 4, 8), (2, 4, 6) # Diag
  29. )
  30.  
  31. for idx in indexes:
  32. if sum(b[i].weight for i in idx if b[i].val == t) == 15:
  33. return True
  34.  
  35.  
  36. def get_move(b, turn):
  37. # Get user input while it's wrong
  38. while True:
  39. try:
  40. move = int(input("Player %s turn!n>>>" % turn))
  41. # if input isn't an integer
  42. except ValueError:
  43. print("Wrong field!")
  44. continue
  45. else:
  46. if 0 < move < 10:
  47. for item in b:
  48. if item.pos == move:
  49. # Check if place is taken
  50. if item.val == "X" or item.val == "O":
  51. print("Field is taken!")
  52. continue
  53. else:
  54. item.val = turn
  55. item.weight = 5
  56. print("Player %s took place %d" % (turn, move))
  57. return True
  58. else:
  59. print("Incorrect field!")
  60. continue
  61.  
  62.  
  63. def next_turn(currentturn):
  64. if currentturn == "X":
  65. return "O"
  66. else:
  67. return "X"
  68.  
  69.  
  70. def reset_game():
  71. global board
  72. global turn
  73. global turns
  74.  
  75. board = [Field(7), Field(8), Field(9),
  76. Field(4), Field(5), Field(6),
  77. Field(1), Field(2), Field(3)]
  78.  
  79. turn = "X"
  80. turns = 0
  81.  
  82.  
  83. board = [Field(7), Field(8), Field(9),
  84. Field(4), Field(5), Field(6),
  85. Field(1), Field(2), Field(3)]
  86.  
  87. turn = "X"
  88. turns = 0
  89. moveMessage = "Player (%s) move: " % turn
  90.  
  91. while True:
  92. display_board(board)
  93.  
  94. if turns >= 9:
  95. display_board(board)
  96. print("Draw!")
  97. choice = input(">>>")
  98.  
  99. if choice == "play":
  100. reset_game()
  101. else:
  102. break
  103.  
  104. if get_move(board, turn):
  105. if did_player_won(board, turn):
  106. display_board(board)
  107. print("Player %s won! Congrats Comrade! It's OUR win!" % turn)
  108. choice = input(">>>")
  109.  
  110. if choice == "play":
  111. reset_game()
  112. else:
  113. break
  114. else:
  115. turn = next_turn(turn)
  116. turns += 1
Add Comment
Please, Sign In to add comment