2048-ml

git clone git://git.codymlewis.com/2048-ml.git
Log | Files | Refs | README | LICENSE

NeuralNet.py (1341B)


      1 #!/usr/bin/env python3
      2 
      3 from sklearn import neural_network
      4 import random
      5 import sys
      6 
      7 import Autoplay
      8 import Board
      9 
     10 
     11 def learn(epochs, verbose=False):
     12     model = neural_network.MLPClassifier()
     13     board = Board.Board(4, 4)
     14     classes = ["u", "d", "l", "r"]
     15     model.partial_fit(
     16         [board.get_game_state()],
     17         ["u"],
     18         classes=classes
     19     )
     20     for epoch in range(epochs):
     21         board = Board.Board(4, 4)
     22         movement = {
     23             "u": board.up,
     24             "d": board.down,
     25             "l": board.left,
     26             "r": board.right
     27         }
     28         score = board.get_score()
     29         while not board.game_over():
     30             prev_state = board.get_game_state()
     31             prediction = model.predict([prev_state])[0]
     32             while not movement[prediction]():
     33                 prediction = random.choice(classes)
     34             if board.get_score() > score:
     35                 model.partial_fit([prev_state], [prediction])
     36                 score = board.get_score()
     37             board.spawn_tile()
     38         sys.stdout.write("\033[K")
     39         if verbose:
     40             print(f"Epoch {epoch + 1}, score: {board.get_score()}", end="\r")
     41     if verbose:
     42         print()
     43     return model
     44 
     45 
     46 if __name__ == "__main__":
     47     print("Learning to play 2048...")
     48     MODEL = learn(10_000, verbose=True)
     49     Autoplay.model_play(MODEL)