spacepaste

  1.  
  2. # TREE BUILDER
  3. # This is meant to build the tree for the minimax algorithm to navigate
  4. #======================================================================
  5. class Node(object):
  6. def __init__(self, depth, player, board, value = 0):
  7. self.depth = depth
  8. self.player = player
  9. self.board = board
  10. self.value = value
  11. self.children = []
  12. self.makechildren()
  13. def makechildren(self):
  14. for i in range(0, 7):
  15. if self.depth > 0:
  16. v, new_board = self.get_value(i)
  17. self.children.append(Node(self.depth - 1, self.player*-1, new_board, v))
  18. def get_value(self, column):
  19. new_board, valid_pos = placepiece(column, self.board, self.player)
  20. if valid_pos == True:
  21. if checkwin(new_board):
  22. value = player*maxsize
  23. else:
  24. value = 0
  25. else:
  26. value = -player*maxsize
  27. return value, new_board
  28. #======================================================================
  29. def placepiece(column, new_board, player):
  30. valid_pos = False
  31. for y in range(0, 5):
  32. if new_board[y][column] == 0:
  33. new_board[y][column] = player
  34. valid_pos = True
  35. break
  36. return new_board, valid_pos
  37. def checkwin(board):
  38. win = False
  39. #check horizontal
  40. for y in range(0,6):
  41. for x in range(0, 4):
  42. value = board[x][y]
  43. if board[x][y] == board[x+1][y] == board[x+2][y] == board[x+3][y] != 0:
  44. win = True
  45. # check vertical
  46. for x in range(0,5):
  47. for y in range(0, 5):
  48. value = board[x][y]
  49. if board[x][y] == board[x][y+1] == board[x][y+2] == board[x][y+3] != 0:
  50. win = True
  51. # check / diagonal
  52. for x in range(0,4):
  53. for y in range(0, 5):
  54. if board[x][y] == board[x+1][y+1] == board[x+2][y+2] == board[x+3][y+3] != 0:
  55. win = True
  56. # check \ diagonal
  57. for y in range(7,3, -1):
  58. for x in range(0,4):
  59. if board[x][y] == board[x+1][y-1] == board[x+2][y-2] == board[x+3][y-3] != 0:
  60. win = True
  61. return win
  62. def printboard(board):
  63. for j in range(0,6):
  64. for i in range(0, 7):
  65. print(" ", board[j][i], end = "");
  66. print("");
  67. print(("-")*50)
  68. # IMPLEMENTATION
  69. #======================================================================
  70. depth = int(input("depth": ))
  71. player = 1
  72. board = [[0 for x in range(8)] for y in range(7)]
  73. node = Node(depth, player, board)
  74.