Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def minmax_decision(state):
- def max_value(state):
- if is_terminal(state):
- return utility_of(state)
- v = -infinity
- for (a, s) in successors_of(state):
- v = max(v, min_value(s))
- print('V: ' + str(v))
- return v
- def min_value(state):
- if is_terminal(state):
- return utility_of(state)
- v = infinity
- for (a, s) in successors_of(state):
- v = min(v, max_value(s))
- return v
- infinity = float('inf')
- action, state = argmax(successors_of(state), lambda a: min_value(a[1]))
- return action
- def is_terminal(state):
- no_options = True
- for entry in state:
- if entry > 2: # hvis bunken er større end 2, kan man stadig dele bunken.
- no_options = False
- break
- if no_options:
- return True
- utility = utility_of(state)
- if utility == 0 or utility == 1:
- return True
- else:
- return False
- def utility_of(state):
- '''
- Checks who wins. if 0 min if 1 max
- the check works, because we are sorting the state space to have the biggest number first.
- If the first number in the state space is two, we cannot split the pile anymore.
- If the entry is 2 and modulo is 1, we are on a minimum level,
- minimum cannot divide the piles anymore, and max wins.
- '''
- for entry in state:
- if state[0] == 2 and len(state) % 2 == 1:
- return 1
- elif state[0] == 2 and len(state) % 2 == 0:
- return 0
- return -1
- def successors_of(state):
- """
- The successor seems to create the correct tree
- """
- # Figure out whos' turn it is.
- min_turn = False
- if len(state) % 2 == 1:
- min_turn = True
- # Generate valid moves
- valid_moves = []
- print("State: " , state)
- for i in range(len(state)):
- if state[i] == 1 or state[i] == 2:
- continue
- count = 1
- while count < state[i]/2:
- new_state = state.copy()
- new_state[i] = new_state[i]-count
- new_state.append(count)
- new_state.sort(reverse=True)
- valid_moves.append((count - 1 ,new_state))
- count += 1
- print(valid_moves)
- return valid_moves
- def display(state):
- print("-----")
- print(state)
- '''
- for c in [0, 3, 6]:
- print(state[c + 0], state[c + 1], state[c + 2])
- '''
- def main():
- board = [7]
- while not is_terminal(board):
- board[minmax_decision(board)] = 'X'
- if not is_terminal(board):
- display(board)
- board[int(input('Your move? '))] = 'O'
- display(board)
- def argmax(iterable, func):
- return max(iterable, key=func)
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement