Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
    <script src="https://angular-ui.github.io/ui-router/release/angular-ui-router.min.js"></script>
    
  </head>
  <body ng-app="gridDropApp">
    <div class="container">
      <div ui-view="content"></div>
    </div>
    
    <script id="templates/main.html" type="text/ng-template">
      <div ng-cloak>
      <div class="well">
        <div style="margin-bottom: 5px;" class="row">
            <span class="col-md-4 text-center">
                <label translate="main.score"></label>
                {{ totalScore }}
            </span>
            <div class="col-md-4">
                <select class="form-control"
                        ng-model="currentShape"
                        ng-change="updateCells()"
                        ng-options="shape as shape.displayName for shape in shapes">
                    <option></option>
                </select>
            </div>
            <div class="col-md-4">
                <button ng-click="resetGame()" class="btn btn-primary">
                    Reset Game
                </button>
            </div>
        </div>
        <div ng-if="gameOver" class="text-center row alert alert-danger">Game Over!</div>
    </div>
      <div class="row">
        <div class="col-md-6">
            <grid-drop-square size="3" is-palette="true" content="initial" drag-target="true"></grid-drop-square>
          <div style="clear:both"></div>
        </div>
       
        <div class="col-md-6">
            <div ng-repeat="row in contents track by $index" ng-init="x=$index">
                <div ng-repeat="col in row track by $index" ng-init="y=$index">
                    <grid-drop-square size="3"
                                      grid-drop-x="x"
                                      grid-drop-y="y"
                                      content="contents[x][y]"
                                      drop-target
                                      drag-target="false">

                    </grid-drop-square>
                </div>
            </div>
        </div>
    </div>
    </div>
    </script>
    <script id="templates/grid-drop-square.html" type="text/ng-template">
      <div ng-style="{ 'background-color' : content.color }" class="{{ chosenClass }}">
        <div class="grid-square-content">
          <div class="grid-table">
            <h2 class="grid-table-cell grid-drop-text-border">
              {{ content.score }}
            </h2>
          </div>
        </div>
      </div>
    </script>
  </body>
  
  
</html>

              
            
!

CSS

              
                $gridSize: 14;

.grid {
    width: 50%;
    border-collapse: collapse;
    margin: 0 auto;
    overflow: hidden;
}

.grid-cell {
    background-color: lightgrey;
    float: left;
    @for $x from 1 through $gridSize {
        &.grid-size-#{$x} {
            position: relative;
            width: (1 / $x) * 100%;
            padding-bottom: (1 / $x) * 100%;
            border: 1px solid black;
            display: inline-block;
            vertical-align: top;
        }
    }
}

.grid-cell-circle {
    background-color: lightgray;
    float: left;
    @for $x from 1 through $gridSize {
        &.grid-size-#{$x} {
            position: relative;
            border-radius: 50%;
            width: (1 / $x) * 100%;
            padding-bottom: (1 / $x) * 100%;
            border: 1px solid black;
            display: inline-block;
            vertical-align: top;
        }
    }
}

.grid-square-content {
    position:absolute;
    height:100%;
    width:100%;
    text-align: center;
}

.grid-text-small {
    font-size: 11px;
}

.grid-table {
    display: table;
    height: 100%;
    width: 100%;
}

.grid-table-cell {
    display: table-cell;
    vertical-align: middle;
    height: 100%;
    width: 100%;
}

.hover {
    border: 1px dotted black;
}

.dragged {
    opacity: 0.25;
    -webkit-transform: scale(0.8);
    -moz-transform: scale(0.8);
    -ms-transform: scale(0.8);
    -o-transform: scale(0.8);
}

.grid-drop-text-border {
    color: black;
    text-shadow: -0.5px 0 white, 0 0.5px white, 0.5px 0 white, 0 -0.5px white;
}

.top-padding {
    margin-top: 10px;
}
              
            
!

JS

              
                angular.module('gridDropApp', ['ui.router'])
.config(function($stateProvider, $urlRouterProvider) {
    
    $stateProvider
      .state('home', {
        url: '/',
        views: {
          'content': {
            templateUrl: 'templates/main.html',
            controller: 'MainController'
          }
        }
      });
  
    $urlRouterProvider.otherwise('/');
  })
.controller('MainController', function($scope, RandomContent) {
    $scope.initial = RandomContent.getRandomContent();
    $scope.totalScore = 0;
    $scope.gameOver = false;

    $scope.contents = [];

    $scope.shapes = [
      {
        displayName: 'Square',
        displayClass: 'grid-cell'
      },
      {
        displayName: 'Circle',
        displayClass: 'grid-cell-circle'
      }
    ];
    $scope.currentShape = $scope.shapes[0];
  
    $scope.resetGame = function() {
      $scope.contents = [];
      for(var i = 0; i < 3; ++i) {
        var contentRow = [];
        for(var j = 0; j < 3; ++j) {
          contentRow.push({ score: 0, color: 'lightgrey', displayClass: $scope.shapes[0].displayClass });
        }
        $scope.contents.push(contentRow);
      }
      $scope.totalScore = 0;
      $scope.gameOver = false;
    };
  
    $scope.resetGame();
  
    $scope.updateCells = function() {
      angular.forEach($scope.contents, function(row) {
        angular.forEach(row, function(content) {
          content.displayClass = $scope.currentShape.displayClass;
        })
      });
      $scope.initial.displayClass = $scope.currentShape.displayClass;
    };

    $scope.$watch('initial', function(drag) {
      drag.displayClass = $scope.currentShape.displayClass;
    });


    $scope.$on('grid-drop-change', function(event, position) {      
      $scope.clearMatches($scope.contents, position.dropPositionX, position.dropPositionY);
      if($scope.isGameOver()) {
        $scope.gameOver = true;
      }
    });

    $scope.isGameOver = function() {
      var gameOver = true;
      angular.forEach($scope.contents, function(rows) {
        angular.forEach(rows, function(el) {
          if(el.color === 'lightgrey') {
            gameOver = false;
          }
        })
      });
      return gameOver;
    };

    $scope.gameOver = $scope.isGameOver();

    $scope.clearMatches = function(grid, x, y) {
      var initialScore = $scope.totalScore;
      
      $scope.clearAdjacentMatches(grid, x, y);
      
      if($scope.scoreChanged(initialScore)) {
        $scope.reset(grid[x][y]);
      }
    };
  
    $scope.clearAdjacentMatches = function(grid, x, y) {
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x-1, y-1)); // top left
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x-1, y)); // top
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x-1, y+1)); // top right
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x, y-1)); // mid left
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x, y+1)); // mid right
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x+1, y-1)); // bottom left
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x+1, y)); // bottom
      $scope.clearCellIfPossible(grid[x][y], $scope.getCellFromCoordinates(grid, x+1, y+1)); // bottom right
    };

    $scope.clearCellIfPossible = function(original, adjacent) {
      if($scope.isMatch(original, adjacent)) {
        $scope.reset(adjacent);
      }
    };
  
    $scope.isMatch = function(original, gridElement) {
      return original.color === gridElement.color;
    };

    $scope.reset = function(gridElement) {
      gridElement.color = 'lightgrey';
      $scope.totalScore += gridElement.score;
      gridElement.score = 0;
    };

    $scope.getCellFromCoordinates = function(grid, x, y) {
      if($scope.outOfBounds(x, y, grid.length)) {
        return {}
      }
      return grid[x][y];
    };
  
    $scope.outOfBounds = function(x, y, gridSize) {
      return x < 0 || y < 0 || x >= gridSize || y >= gridSize;
    };

    $scope.scoreChanged = function(initialScore) {
      return initialScore !== $scope.totalScore;
    }
  })
.factory('DragAndDropHelper', function() {
        var content;

        return {
            setContent: function(content) {
                this.content = content;
            },

            getContent: function() {
                return this.content;
            }
        }
    })
.factory('RandomContent', function() {

        var colors = [
            'red',
            'blue',
            'green',
            'orange',
            'black',
            'yellow',
            'white',
            'pink'
        ];

        var currentShape = 'grid-cell';

        return {
            getRandomContent: function () {
                return {
                    score: Math.floor((Math.random() * 100) + 1),
                    color: colors[Math.floor(Math.random() * colors.length)],
                    displayClass: currentShape
                }
            },

            randomColor: function () {
                var letters = '0123456789ABCDEF'.split('');
                var color = '#';
                for (var i = 0; i < 6; i++) {
                    color += letters[Math.floor(Math.random() * 16)];
                }
                return color;
            }
        }
    })
.directive('gridDropSquare', function() {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                size: '=',
                content: '=',
                isPalette: '=',
                gridDropX: '=',
                gridDropY: '='
            },
            controller: ['$scope', function($scope) {
                this.getGridDropX = function() {
                    return $scope.gridDropX;
                };

                this.getGridDropY = function() {
                    return $scope.gridDropY;
                };

                this.getContent = function() {
                    return $scope.content;
                };

                this.setContent = function(content) {
                    $scope.content = content;
                };

                this.isPalette = function() {
                    return $scope.isPalette;
                };

                $scope.$watch('content.displayClass', function(displayClass) {
                    $scope.chosenClass = 'grid-size-' + $scope.size + ' ' + displayClass;
                })
            }],
            link: function(scope, el, attrs, ctrl) {},
            templateUrl: 'templates/grid-drop-square.html'
        }
    })
.directive('dragTarget', ['DragAndDropHelper', 'RandomContent', function(DragAndDropHelper, RandomContent) {
        return {
            restrict: 'A',
            replace: true,
            require: 'gridDropSquare',
            link: function(scope, el, attrs, ctrl) {
                angular.element(el).attr("draggable", attrs['dragTarget']);


                el.bind('dragstart', function(e) {
                    var transferObject = e.originalEvent ? e.originalEvent.dataTransfer : e.dataTransfer;

                    transferObject.effectAllowed = attrs['dragTarget'] === 'true' ? 'move' : 'none';


                    // We don't use the data transfer to move data, instead we communicate
                    // through required controllers. However, firefox requires data to be set
                    transferObject.setData('text/plain', 'stop');


                    DragAndDropHelper.setContent(ctrl.getContent());
                    angular.element(e.target).addClass('dragged');
                });

                el.bind('dragend', function(e) {
                    if(ctrl.isPalette()) {
                        ctrl.setContent(RandomContent.getRandomContent())
                    }
                    angular.element(e.target).removeClass('dragged');
                    scope.$apply();
                })
            }
        }
    }])
.directive('dropTarget', ['DragAndDropHelper', function(DragAndDropHelper) {
        return {
            restrict: 'A',
            require: 'gridDropSquare',
            link: function(scope, el, attrs, ctrl) {
                el.bind('drop', function(e) {
                    if(e.preventDefault) {
                        e.preventDefault();
                    }
                    if(e.stopPropagation) {
                        e.stopPropagation();
                    }
                    if(ctrl.getContent().color === 'lightgrey') {
                        ctrl.setContent(DragAndDropHelper.getContent());
                    }
                    scope.$apply();
                    angular.element(e.currentTarget).removeClass('hover');
                    scope.$emit('grid-drop-change', {
                        dropPositionX: ctrl.getGridDropX(),
                        dropPositionY: ctrl.getGridDropY()
                    });
                });

                el.bind('dragover', function(e) {
                    if(e.preventDefault) {
                        e.preventDefault();
                    }

                    return false;
                });

                el.bind('dragenter', function(e) {
                    angular.element(e.currentTarget).addClass('hover');
                });

                el.bind('dragleave', function(e) {
                    angular.element(e.currentTarget).removeClass('hover');
                });
            }
        }
    }])
              
            
!
999px

Console