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 includes JSX processing.

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

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

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

              
                <div class="container">
    <div class="heading">
        <h1 class="title">Rotation</h1>
        <a id="reset-button" class="reset-button">
            Reset
        </a>
    </div>

    <canvas id="grid-canvas" class="game-content" width="380px" height="380px">
    </canvas>

    <div class="footer">
        <hr>
        <p><b>HOW TO PLAY: </b>Click on the <b><span style="color:#00ffff;">cyan buttons</span></b> to rotate the numbers around.<p>
        <p>Arrange the numbers in order as fast as possible.<br/>
        1,2,3<br/>
        4,5,6<br/>
        7,8,9<br/>
          <strong>May your rotations be productive!</strong>
        </p>
        <hr>
        <p>Created by <a href="http://codemyroad.wordpress.com" target="#">Lee Yiyuan</a>, codepen'd by <a href="http://dave.thehorners.com" target="_blank">Dave Horner</a>.</p>
    </div>
</div>
              
            
!

CSS

              
                html, body
{
    margin:0;
    padding:0;
}

body{
    margin:10px;
}

a
{
    color: #000000;
    font-weight: bold;
    text-decoration: underline;
    cursor: pointer;
}

.container
{
    width:380px;
    margin:0 auto;
    background-color: #FCFCFC;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select:none;
    user-select:none;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

.heading{
    margin-bottom: 15px;
}

.heading:after {
    content: "";
    display: block;
    clear: both;
}

.title
{
    font-size: 40px;
    font-weight: bold;
    margin: 0;
    padding:0;
    display: block;
    float:left;

    color:#000000;
    text-align:center;
    font-family: Verdana;
}

.game-content
{
    width:380px;
    height:380px;
    box-shadow: 0 0 10px 2px #EEEEEE;
    border:1px solid #CCCCCC;
    position:relative;
}

.footer
{
    font-family: Verdana;
    color:#000000;
    font-size: 12px;
}

.reset-button
{
    border-radius: 50%;
    border:2px solid #CCCCCC;
    color:#000000;
    margin: 0;
    display: block;
    float:right;
    height:45px;
    width:45px;
    text-align: center;
    font-size:12px;
    line-height: 45px;
    font-family: Verdana;
    clear:right;
    font-weight: bolder;
    cursor: pointer;
}

@media screen and (max-width: 400px){
    html, body
    {
        margin:0;
        padding:0;
    }

    body
    {
        margin:10px;
    }

    .container
    {
        width:300px;
        margin:0 auto;
        background-color: #FCFCFC;
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select:none;
        user-select:none;
        -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
    }

    .heading{
        margin-bottom: 15px;
    }

    .heading:after {
        content: "";
        display: block;
        clear: both;
    }

    .title
    {
        font-size: 40px;
        font-weight: bold;
        margin: 0;
        padding:0;
        display: block;
        float:left;

        color:#000000;
        text-align:center;
        font-family: Verdana;
    }

    .game-content
    {
        width:300px;
        height:300px;
        box-shadow: 0 0 10px 2px #EEEEEE;
        border:1px solid #CCCCCC;
        position:relative;
    }

    .footer
    {
        font-family: Verdana;
        color:#000000;
        font-size: 12px;
    }

    .reset-button
    {
        border-radius: 50%;
        border:2px solid #CCCCCC;
        color:#000000;
        margin: 0;
        display: block;
        float:right;
        height:45px;
        width:45px;
        text-align: center;
        font-size:12px;
        line-height: 45px;
        font-family: Verdana;
        clear:right;
        font-weight: bolder;
        cursor: pointer;
    }
}
              
            
!

JS

              
                window.requestAnimFrame = function(){ // Polyfill
    return (
        window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
        function(callback){
            window.setTimeout(callback, 1000 / 60); // 60 FPS
        }
        );
}();

window.requestAnimFrame(function(){
    new GameManager();
});

function GameManager(){
    this.grid = new Grid();
    this.ui = new UI();
    this.isRotating = false;
    this.startTiming = null;

    this.ui.onOverlayPressed = this.start.bind(this);
    this.ui.onRotatePressed = this.move.bind(this);
    this.ui.onResetClicked = function(){
        this.reset();
        this.ui.renderOverlay();
    }.bind(this);

    this.reset();
    this.ui.renderOverlay();
};

GameManager.prototype.reset = function(){
    this.grid = new Grid();
    this.ui.render(this.grid);
};

GameManager.prototype.start = function(){
    this.ui.overlayVisible = false;
    this.grid.randomize();
    this.ui.render(this.grid);
    this.startTiming = Date.now();
};

GameManager.prototype.move = function(position){
    if (this.isRotating){
        return;
    }

    var animation = new GridRotationAnimation(this.ui, this.grid, position);
    animation.onCompleted = (function(){
        this.isRotating = false;
        if (this.grid.isComplete()){
            var timing = Date.now() - this.startTiming;
            this.ui.renderWinOverlay(timing / 1000);
        }
    }).bind(this);
    this.isRotating = true;
    animation.start();
    this.grid.move(position);
};

function Grid(){
    this.tiles = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]
    ];
};

Grid.prototype.clone = function(){
    var grid = new Grid();
    for(var r = 0; r < 3; r++){
        for(var c = 0; c < 3; c++){
            grid.tiles[r][c] = this.tiles[r][c];
        }
    }
    return grid;
};

Grid.prototype.move = function (position){
    var r = position >> 1;
    var c = position & 1;

    var temp = this.tiles[r][c];
    this.tiles[r][c] = this.tiles[r + 1][c];
    this.tiles[r + 1][c] = this.tiles[r + 1][c + 1];
    this.tiles[r + 1][c + 1] = this.tiles[r][c + 1];
    this.tiles[r][c + 1] = temp;
};

Grid.prototype.isEasyGrid = function(){
    for(var r = 0; r < 3; r++){
        var count = 0;
        for(var c = 0; c < 3; c++){
            if (this.tiles[r][c] >= 3 * r && this.tiles[r][c] < 3 * (r + 1)){
                count++;
                if (count > 1){
                    return true;
                }
            }
        }
    }
    return false;
};

Grid.prototype.randomize = function(){
    while(this.isEasyGrid()){
        for(var i = 0; i < 100; i++) {
            this.move(Math.floor((Math.random() * 4)));
        }
    }
};

Grid.prototype.isComplete = function(){
    for(var r = 0; r < 3; r++){
        for(var c = 0; c < 3; c++){
            if (this.tiles[r][c] != r * 3 + c){
                return false;
            }
        }
    }
    return true;
};

function UI(){
    this.canvas = document.getElementById('grid-canvas');
    this.resetButton = document.getElementById('reset-button');
    this.tileRadius = 30;
    this.tileSpacing = 60;
    this.tileRotationRadius = Math.sqrt(Math.pow(this.tileSpacing + 2 * this.tileRadius, 2) / 2); // Pythagoras theorem
    this.overlayVisible = false;


    this.onRotatePressed = null;
    this.onOverlayPressed = null;
    this.onResetClicked = null;

    this.canvas.addEventListener('mousedown', this.onCanvasClick.bind(this), false);
    this.resetButton.addEventListener('click', function(){
        if (this.onResetClicked != null){
            this.onResetClicked();
        }
    }.bind(this), false);
};

UI.prototype.renderOverlay = function(){
    this.overlayVisible = true;
    var context = this.canvas.getContext('2d');
    context.fillStyle = "rgba(255, 255, 255, 0.9)";
    context.fillRect(0, 0, this.canvas.width, this.canvas.height);

    var text = "Click to start!";

    context.font="30px Verdana";
    context.fillStyle = "#000000";
    var width = context.measureText(text).width;

    context.fillText(text, (this.canvas.width - width) / 2, (this.canvas.height + 28) / 2-50);
    context.fillText("(solution displayed)", (this.canvas.width - width) / 2-40, (this.canvas.height + 28) / 2+50);
};

UI.prototype.renderWinOverlay = function(timing){
    this.overlayVisible = true;
    var context = this.canvas.getContext('2d');
    context.fillStyle = "rgba(255, 255, 255, 0.9)";
    context.fillRect(0, 0, this.canvas.width, this.canvas.height);


    context.font="40px Verdana";
    context.fillStyle = "#000000";
    var text1 = "You win!";
    var width1 = context.measureText(text1).width;
    context.fillText(text1, (this.canvas.width - width1) / 2, 130);

    var text2 = (Math.round( timing * 10 ) / 10).toFixed(1) + " s";
    var width2 = context.measureText(text2).width;
    context.fillText(text2, (this.canvas.width - width2) / 2, 200);

    context.font="20px Verdana";
    var text3 = "Click to play again"
    var width3 = context.measureText(text3).width;
    context.fillText(text3, (this.canvas.width - width3) / 2, 260);
};

UI.prototype.render = function(grid, xOffsets, yOffsets){
    var xOffset = (this.canvas.width - 2 * this.tileSpacing - 3 * 2 * this.tileRadius) / 2;
    var yOffset = (this.canvas.height - 2 * this.tileSpacing - 3 * 2 * this.tileRadius) / 2;
    var context = this.canvas.getContext('2d');
    context.fillStyle = "#FFFFFF";
    context.fillRect(0, 0, this.canvas.width, this.canvas.height); // Because clearRect is buggy on Android

    // Rotate buttons
    for(var r = 0; r < 2; r++){
        for(var c = 0; c < 2; c++){
            context.beginPath();
            context.lineWidth = 3;
            context.strokeStyle = '#00FFFF';
            context.arc(xOffset + 2 * this.tileRadius + this.tileSpacing / 2 + c * (this.tileSpacing + 2 * this.tileRadius),
                    yOffset + 2 * this.tileRadius + this.tileSpacing / 2 + r * (this.tileSpacing + 2 * this.tileRadius),
                this.tileRadius,
                0,
                    2 * Math.PI);
            context.stroke();
        }
    }

    // Tiles
    for(var r = 0; r < 3; r++){
        for(var c = 0; c < 3; c++){
            var value = grid.tiles[r][c];
            var text = (grid.tiles[r][c] + 1).toString();

            // Clear background
            context.beginPath();
            context.fillStyle = "#FFFFFF";
            context.beginPath();
            context.arc(xOffset + this.tileRadius + c * (this.tileSpacing + 2 * this.tileRadius) + (xOffsets == null ? 0 : xOffsets[r][c]),
                    yOffset + this.tileRadius + r * (this.tileSpacing + 2 * this.tileRadius) - (yOffsets == null ? 0 : yOffsets[r][c]),
                this.tileRadius,
                0,
                    2 * Math.PI);
            context.fill();

            // Draw text
            context.font="40px Verdana";
            context.fillStyle = value < 3 ? "#FF0000" : value < 6 ? "#00FF00" : "#0000FF";
            context.fillText(
                    text,
                    xOffset + this.tileRadius + c * (this.tileSpacing + 2 * this.tileRadius) + (xOffsets == null ? 0 : xOffsets[r][c]) - context.measureText(text).width / 2,
                    yOffset + this.tileRadius + r * (this.tileSpacing + 2 * this.tileRadius) - (yOffsets == null ? 0 : yOffsets[r][c]) + 28 / 2);

            // Draw outline circle
            context.lineWidth=1;
            context.strokeStyle = '#000000';
            context.beginPath();
            context.arc(xOffset + this.tileRadius + c * (this.tileSpacing + 2 * this.tileRadius) + (xOffsets == null ? 0 : xOffsets[r][c]),
                    yOffset + this.tileRadius + r * (this.tileSpacing + 2 * this.tileRadius) - (yOffsets == null ? 0 : yOffsets[r][c]),
                this.tileRadius,
                0,
                    2 * Math.PI);

            context.stroke();
        }
    }
};

UI.prototype.onCanvasClick = function(e){
    if (this.overlayVisible){
        if (this.onOverlayPressed != null){
            this.onOverlayPressed();
            return;
        }
    }

    var x = 0;
    var y = 0;
    if (!e) var e = window.event;
    if (e.pageX || e.pageY) 	{
        x = e.pageX;
        y = e.pageY;
    }
    else if (e.clientX || e.clientY) 	{
        x = e.clientX + document.body.scrollLeft
            + document.documentElement.scrollLeft;
        y = e.clientY + document.body.scrollTop
            + document.documentElement.scrollTop;
    }

    x -= this.canvas.offsetLeft;
    y -= this.canvas.offsetTop;

    x *= this.canvas.width / this.canvas.clientWidth;
    y *= this.canvas.height / this.canvas.clientHeight;

    var centers = [
        {x: 130, y:130},
        {x: 250, y: 130},
        {x: 130, y: 250},
        {x: 250, y: 250}
    ];

    var position = -1;

    for(var i = 0; i < 4; i++){
        if (Math.pow(centers[i].x - x, 2) + Math.pow(centers[i].y - y, 2) <= Math.pow(30, 2)){
            position = i;
            break;
        }
    }

    if (position > -1){
        this.onRotatePressed(position);
    }

    event.preventDefault();
    return false;
};

function GridRotationAnimation(ui, grid, position){
    this.ui = ui;
    this.grid = grid.clone();
    this.r = position >> 1;
    this.c = position & 1;
    this.onCompleted = null;

    this.animation = new Animation(150);
    this.animation.onUpdate = this.animationUpdate.bind(this);
    var self = this;
    this.animation.onCompleted = function(){
        if (self.onCompleted != null){
            self.onCompleted();
        }
    };
};

GridRotationAnimation.prototype.animationUpdate = function(progress){
    var angle = progress * Math.PI / 2;

    var xOffsets = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ];

    var yOffsets = [
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]
    ];

    var rotationXOffsets = Rotation.rotationXOffsets(angle);
    var rotationYOffsets = Rotation.rotationYOffsets(angle);

    for(var r = 0; r < 2; r++){
        for(var c = 0; c < 2; c++){
            xOffsets[r + this.r][c + this.c] = this.ui.tileRotationRadius * rotationXOffsets[r][c];
            yOffsets[r + this.r][c + this.c] = this.ui.tileRotationRadius * rotationYOffsets[r][c];
        }
    }

    this.ui.render(this.grid, xOffsets, yOffsets);
};

GridRotationAnimation.prototype.start = function(){
  this.animation.start();
};

function Animation(duration){
    this.animationProgress = 0;
    this.lastUpdate = null;
    this.animationDuration = duration;

    this.onUpdate = null;
    this.onCompleted = null;
};

Animation.prototype.update = function(timestamp){
    if (this.lastUpdate == null){
        this.lastUpdate = timestamp;
    }

    var self = this;
    var delta = timestamp - this.lastUpdate;
    this.lastUpdate = timestamp;

    this.animationProgress += delta / this.animationDuration;
    if (this.animationProgress >= 1){
        this.animationProgress = 1;
        if (this.onUpdate != null){
            this.onUpdate(this.animationProgress);
        }
        if (this.onCompleted != null){
            this.onCompleted();
        }
    }else{
        if (this.onUpdate != null){
            this.onUpdate(this.animationProgress);
        }
        window.requestAnimFrame(function(){
            self.update(Date.now());
        });
    }
};

Animation.prototype.start = function(){
    var self = this;

    window.requestAnimFrame(function(){
        self.update(Date.now());
    });
};

function Rotation(){};

Rotation.rotationXOffsets = function(angle){
    var offsets = [
        [0, 0],
        [0, 0]
    ];

    offsets[0][0] = Math.cos(3 * Math.PI / 4 - angle) - Math.cos(3 * Math.PI / 4);
    offsets[0][1] = Math.cos(Math.PI / 4 - angle) - Math.cos(Math.PI / 4);
    offsets[1][1] = Math.cos(-Math.PI / 4 - angle) - Math.cos(-Math.PI / 4);
    offsets[1][0] = Math.cos(-3 * Math.PI / 4 - angle) - Math.cos(- 3 * Math.PI / 4);

    return offsets;
};

Rotation.rotationYOffsets = function(angle){
    var offsets = [
        [0, 0],
        [0, 0]
    ];

    offsets[0][0] = Math.sin(3 * Math.PI / 4 - angle) - Math.sin(3 * Math.PI / 4);
    offsets[0][1] = Math.sin(Math.PI / 4 - angle) - Math.sin(Math.PI / 4);
    offsets[1][1] = Math.sin(-Math.PI / 4 - angle) - Math.sin(-Math.PI / 4);
    offsets[1][0] = Math.sin(-3 * Math.PI / 4 - angle) - Math.sin(- 3 * Math.PI / 4);

    return offsets;
};

              
            
!
999px

Console