Guest User

Untitled

a guest
Apr 26th, 2018
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. import random
  2.  
  3. board = {
  4. 1: 0, 2: 0, 3: 0,
  5. 4: 0, 5: 0, 6: 0,
  6. 7: 0, 8: 0, 9: 0
  7. }
  8.  
  9. computer = 1
  10. player = 2
  11.  
  12. def copy(item):
  13. new = {}
  14. for k, v in item.items():
  15. new[k] = v
  16. return new
  17.  
  18. def check_winner(b, l):
  19. return ((b[1]==l and b[2]==l and b[3]==l) or
  20. (b[4]==l and b[5]==l and b[6]==l) or
  21. (b[7]==l and b[8]==l and b[9]==l) or
  22. (b[1]==l and b[4]==l and b[7]==l) or
  23. (b[2]==l and b[5]==l and b[8]==l) or
  24. (b[3]==l and b[6]==l and b[9]==l) or
  25. (b[1]==l and b[5]==l and b[9]==l) or
  26. (b[3]==l and b[5]==l and b[7]==l))
  27.  
  28. def full_board():
  29. for i in range(1, 10):
  30. if board[i]==0:
  31. return False
  32. return True
  33.  
  34. def free_space(board, space):
  35. return (board[space]==0)
  36.  
  37. def get_computer(comp, opp):
  38.  
  39. #win first
  40. for i in range(1, 10):
  41. cop = copy(board)
  42. if free_space(cop, i):
  43. make_move(cop, i, comp)
  44. if check_winner(cop, comp):
  45. return i
  46.  
  47. #check edges
  48. for i in range(1, 10):
  49. cop = copy(board)
  50. if free_space(cop, i):
  51. make_move(cop, i, opp)
  52. if check_winner(cop, opp):
  53. return i
  54.  
  55. while True:
  56. move = random.choice([1, 3, 7, 9])
  57. if free_space(board, move):
  58. return move
  59.  
  60. if free_space(board, 5):
  61. return 5
  62.  
  63. while True:
  64. move = random.choice([2, 6, 4, 8])
  65. if free_space(board, move):
  66. return move
  67.  
  68. def get_player():
  69. pass
  70.  
  71. def make_move(board, slot, p):
  72. board[slot] = p
  73.  
  74. def format_board(b):
  75. k = {
  76. 0: " ",
  77. 1: "X",
  78. 2: "O"
  79. }
  80.  
  81. string = """
  82. %s | %s | %s
  83. ---+---+---
  84. %s | %s | %s
  85. ---+---+---
  86. %s | %s | %s
  87. """ % (k[b[1]], k[b[2]], k[b[3]], k[b[4]], k[b[5]], k[b[6]], k[b[7]], k[b[8]], k[b[9]])
  88. return string
  89.  
  90. print(format_board(board))
  91.  
  92. while True:
  93. if full_board():
  94. print "No Winner"
  95. break
  96. #comp1
  97. move = get_computer(computer, player)
  98. make_move(board, move, computer)
  99. print format_board(board)
  100. if check_winner(board, computer):
  101. print "Comp1 (X) Won"
  102. break
  103. if full_board():
  104. print "No Winner"
  105. break
  106. #comp2
  107. move = get_computer(player, computer)
  108. make_move(board, move, player)
  109. print format_board(board)
  110. if check_winner(board, player):
  111. print "Comp2 (O) Won"
  112. break
Add Comment
Please, Sign In to add comment