Example #1
0
def playThroughStdin(game: Game2048):
    # 0 - left, 1 - up, 2 - right, 3 - down
    directions = {'W': 1, 'S': 3, 'A': 0, 'D': 2}

    game.reset()
    moveCount = 0

    try:
        while True:
            print(game.boardAsString())
            inStr = input('Enter direction of swipe: ')
            dir = directions[inStr.upper()]
            score, ended, valid = game.swipe(dir)

            if not valid:
                print('Invalid move, try again...')
                continue

            moveCount += 1

            if ended:
                print(
                    f'Game Over. Score: {2**game.score} after {moveCount} turns.'
                )
                return
            else:
                print(f'Swipe #{moveCount} gave {score} points.')

    except KeyboardInterrupt:
        print('Game aborted.')
Example #2
0
    def _makeTurn(self, net: AgentNet, game: Game2048, eps: float):
        state = game.board.copy()

        if random.random() < eps:
            valid = False
            moves = [0, 1, 2, 3]
            while not valid:
                dir = moves[random.randrange(len(moves))]
                reward, ended, valid = game.swipe(dir)
                moves.remove(dir)
        else:
            action = net(net.prepareInputs(state)).squeeze(0)
            valid = False
            while not valid:
                dir = torch.argmax(action).item()
                reward, ended, valid = game.swipe(dir)
                action[dir] = torch.min(action) - 0.1

        return state, dir, reward, ended, game.board.copy()