2048-ml

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

Autoplay.py (1322B)


      1 import itertools
      2 import numpy as np
      3 
      4 import Board
      5 
      6 
      7 '''
      8 Functions that play 2048 without user input
      9 '''
     10 
     11 
     12 def convert_and_play(moves):
     13     '''Convert the list of moves and play the game with it'''
     14     return np.mean([play(str().join(moves)) for _ in range(10)])
     15 
     16 
     17 def play(move_str, verbose=False):
     18     '''Play the game by cycling the moves specified'''
     19     board = Board.Board(4, 4)
     20     movement = {
     21         "u": board.up,
     22         "d": board.down,
     23         "l": board.left,
     24         "r": board.right
     25     }
     26     counter = 0
     27     if verbose:
     28         print(board)
     29     for a in itertools.cycle(move_str):
     30         if board.game_over() or counter == len(move_str):
     31             break
     32         if movement[a]():
     33             board.spawn_tile()
     34             counter = 0
     35             if verbose:
     36                 print()
     37                 print(board)
     38         else:
     39             counter += 1
     40     return board.get_score()
     41 
     42 
     43 def model_play(model):
     44     board = Board.Board(4, 4)
     45     movement = {
     46         "u": board.up,
     47         "d": board.down,
     48         "l": board.left,
     49         "r": board.right
     50     }
     51     print(board)
     52     while not board.game_over()and \
     53             movement[model.predict([board.get_game_state()])[0]]():
     54         board.spawn_tile()
     55         print(board)
     56     print("Game over!")
     57     print(f"The model scored {board.get_score()}!")