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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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

              
                <script>
    let maps = [`
xxxxxxxxxxxxxxxxxxxxxxxxxx           
xxxxxxxxxxxxxxxxxxxxxxxxex        
xxxxxxxxxxxxxxxxxxxxxxxx.x          
xxxxxxxxxxxxxxxxxxxxxxxx.x          
xxxxxxxxxxxxxxxxxxxxxxxx.x          
xxxxxxxxxxxxxxxxxxxxxxxx.x          
xxxxxxxxxxxxxxxxxxxxx....x
xxxxxxxxxxxxxxxxxxxxx. xxx          
xxxxxxxxxxxxxxxxxxxxx. xx         
xxxxxxxxxxxxxxxxxxxxx...x         
xxxxxxxxxxxxxxxxxxxxxxx.x         
xxxxxxxxxxxxxxxxxxxxxxx.x           
xxxxxxxxxxxxxxxxxxxxxxx.x           
xxxxxxxxxxxxxxxxxxxxxxx.x           
xxxxxxxxxxxxxxxxxxxxxxx.xxx           
xxxxxxxxxxxxxxxxxxxx......x        
xxxxxxxxxxxxxxxxxxxx.  .x.x
xxxxxxxxxxxxxxxxxxxx.  .x.x       
xxxxxxxxxxxxxxxxxxxx....x.x
xxxxxxxxxxxxxxxxxxxxxxxxx.x 
xxxxxxxxxxxxxx......xxxxx.x
xxxxxxxxxxxxxx.xxxx.xxxxx.x
xxxxxxxxxxxxxx.xxxx.xxxxx.x
xxxxxxxxxxxxxx.xxxx.xxxxx.x
xxxxxxxxxxxxxx.xxxx.xxxxx.x
xxxxxxxxxxxxxx.xxxx.......x
xxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxx
xxxxxxxxxx...........xxxxxxxxxxxx
xxxxxxxxxx.   .xxxxx.xx.........x
xxxxxxxxxx.   .xxxxx....xxxxx  .x
xxxxxxxxxx.....xxxxxxxxxxxxxx  .x
xxxxxxxxxxxxxxxxxxxxxxxxxx     .x
xxxxxxxxxxxxxxxxxxxxxxxxxx     .x
xxxxxxxxxxxxxxxxxxxxxxxxxx     .x
xxxxxxxxxxxxxxxxxxxxxxxxxx  p  .x
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
`,`
    xxxxxxxxxxxxxxxxxxxxxx
    x.........x..........x
    x.       .x.        .x  
    x.       .x.        .x  
    x.x  xx  .x.        .x  
    x.   sx  .x.        .x  
    xx........R..........x
    xs  x    .x.        xx
    xr       .x.        ex  
    x        .x.        .x  
    x        .x.        .x  
    x        .x.        .x  
    x p.......x..........x 
    xxxssssssssssssssssxxx
`,`
    xxxxxxxxxxxxxxxxxxxxxx
    x.........x..........x
    x.       .x.        .x  
    x.       .x.        .x  
    x.       .x.        .x  
    x.       .s.        .x  
    x....................x
    xx       .s.        xx
    x        .x.        px  
    x        .x.        .x  
    x        .x.        .x  
    x        .x.        .x  
    xe........x..........x 
    xxxxxxxxxxxxxxxxxxxxxx
`,`
    xxxxxxxxxxxsxxxxxxxxxxx
    s.....................x
    x.       s.x.        .x 
    x.        .x.        .x
    x.        .x.        .x 
    x.        .x.        .x  
    x.........xx.        .x
    xs        ex.        .x
    x         .x.        .x 
    x         .x.        .x 
    x         .x.        .x 
    x         .x.        .x  
    x..........x.        .x 
    xxxxxxsxxxxx.        .x
    x..........x.        .x
    x.        .x.        .x
    x.        .x.        .x  
    x.        .x.        .x  
    x.        .x.        .x  
    x.        .x.        .x 
    x..........x.        xx
    x s       sx.        .x
    x         .x.        .x  
    x         .x.        .x  
    x         .x.        .x  
    x         .x.        .x  
    x p..........        .s 
    xxxxxxsxxxxxxxxxxxxxxxx
`];
    
    class TouchControls {
    constructor(game) {
        document.addEventListener('touchstart', handleTouchStart, false);
        document.addEventListener('touchmove', handleTouchMove, false);

        var xDown = null;
        var yDown = null;

        function handleTouchStart(evt) {
            game.move();
            xDown = evt.touches[0].clientX;
            yDown = evt.touches[0].clientY;
        }

        function handleTouchMove(evt) {
            if ( ! xDown || ! yDown )
                return;
            var xUp = evt.touches[0].clientX;
            var yUp = evt.touches[0].clientY;
            var xDiff = xDown - xUp;
            var yDiff = yDown - yUp;
            if ( Math.abs( xDiff ) > Math.abs( yDiff ) )
                game.move(0,-Math.sign(xDiff));
            else
                game.move(-Math.sign(yDiff), 0);
            xDown = null;
            yDown = null;
            evt.preventDefault()
        }
    }
}

class KeyboardControls {
    constructor(game) {
        addEventListener('click', e => game.move());
        addEventListener('keydown', e => {
            game.move();
            e.keyCode === 65 && game.move(0, -1);
            e.keyCode === 68 && game.move(0, 1);
            e.keyCode === 87 && game.move(-1, 0);
            e.keyCode === 83 && game.move(1, 0);
        });
    }
}
</script>
              
            
!

CSS

              
                
              
            
!

JS

              
                class Cell {
    constructor(x, y, type, game, color, size) {
        this.x = x;
        this.y = y;
        this.color = color||"#369";
        this.renderSize = size;
       
        this.neighbors = [];
        this.neighborsX = [];
        this.game = game;
        this.danger = {};
    }

    setDanger(x, y, delay, active, color, t){
        let key = 'danger_from_' + x + '_' + y;
        if (this.danger[key])
            return;
        this.danger[key] = {
            delay, active, x, y, color, activatedAt: t|| Date.now()
        }
    }
    
    tick() {
        let t = Date.now();

        Object.entries(this.danger)
              .forEach(entry => {

            let d = entry[1];
            let dt = t-d.activatedAt;
            if (d.delay && dt > d.delay) 
                d.delay = 0;
            if (!d.delay && dt > d.active) 
              delete this.danger[entry[0]]

        })
    }

    activate(t) {

        this.neighbors.forEach(c => 
           c.activateByNeighbor(this, t));

        Object.values(this.danger)
              .forEach(d => {

            if (d.active && !d.delay && !this.game.player.death) 
              this.game.player.death = t;

        })
    }

    activateByNeighbor(){}

    renderCell(renderer, context) {
        
       if(this.renderSize)
        renderer.drawRect(this.x, this.y,
          this.renderSize, this.color, context);
        
        Object.values(this.danger).forEach(d => {
            if (d.delay) {  
                renderer.drawRect(this.x-d.x*0.5, this.y-d.y*0.5, 0.2, 'red', context);
            } else if (d.active)
                renderer.drawRect(this.x-d.x*0.5, this.y-d.y*0.5, 0.7, d.color, context);
        })
    }
}

class Coin extends Cell {
    constructor(x, y, type, game) {
        super(x, y, type, game, '#ffe15a', 0.3);
        this.active = true;
    }

    activate(t) {
        super.activate(t);
        if (!this.active) 
           return;
        this.activatedAt = t||Date.now();
        this.active = false;
        this.game.coins++;
    }

    tick(t) {
        super.tick(t);
        if (!this.activatedAt) 
            return;
        let dt = t - this.activatedAt;
        this.renderSize = 0.3-0.3*(dt )/500;
       

        if (dt > 0 && !this.soundPlayed) {
            this.soundPlayed = true;
            this.game.audio.coin()
        }
        if (dt>500) {
           this.activatedAt = 0;
           this.renderSize = 0;
           
         }
    }
}

class Key extends Cell {
      constructor(x, y, type, game, color) {
        super(x, y, type, game, 'red', 0.4);
        this.active = true;
    }
    
    activate(t){
        super.activate(t)
        if (!this.active)
            return
        this.active = false;
        this.game.player.keys[this.color] = (this.game.player.keys[this.color]||0)+1;
        this.renderSize = 0;
    }
}

class Door extends Cell {
      constructor(x, y, type, game, color) {
        super(x, y, type, game, 'red', 1);
        this.isWall = true;  
    }
}

class Exit extends Cell {
    constructor(x, y, type, game) {
        super(x, y, type, game, 0, 0.6);
        this.tick();
        this.r = 0;
        this.i = 0;
    }

    tick(t) {
        this.r += 0.01;
        this.color = 'hsl(' + this.i++ + ',55%,55%)'
        this.renderSize = 0.6 + Math.sin(this.i/77)*0.1;
        
        if (t - this.activatedAt >0) {
            this.game.nextLevel();
            this.game.gameInProgress = false
        }
       
    }
    
    renderCell(renderer, context) {
         context.save()
        context.translate(this.x*renderer.size+renderer.size/2, this.y*renderer.size+renderer.size/2)
        context.rotate(this.r)
        context.translate(-renderer.size/2,-renderer.size/2)
        renderer.drawRect(0, 0,
          this.renderSize, this.color, context);
        context.restore()       
     }
    
    activate(t) {
        this.activatedAt = t || Date.now();
    }
}
        
class Wall extends Cell {
    constructor(x, y, type, game) {
        super(x, y, type, game, '#876040', 1.1);
        this.isWall = true;
        this.isStatic = true;
    }

    renderCell(renderer, context) {
        if (!this.subcells){
        this.subcells = [[0,0,0],[0,0,0],[0,0,0]]
        this.neighbors.forEach(n => {
            if (n.isWall && !(n instanceof Door)) 
                return;
            if (this.y>n.y || this.x>n.x) this.subcells[0][0] = 1;
            if (this.y>n.y || this.x<n.x) this.subcells[0][2] = 1;
            if (this.y<n.y || this.x>n.x) this.subcells[2][0] = 1;   
            if (this.y<n.y || this.x<n.x) this.subcells[2][2] = 1;
            this.subcells[n.y+1-this.y][n.x+1-this.x] = 1;
        });
        this.neighborsX.forEach(n => {
            if (n.isWall) return;
            this.subcells[n.y+1-this.y][n.x+1-this.x] = 1;
        });
        }
        this.renderSubcells(renderer,context)
    }
    
    
    renderSubcells(renderer, context) {
  context.fillStyle = this.color;
        let s = renderer.size;
        let cs = s/3; 
        
        this.subcells.forEach((row, y) => {
            row.forEach((c, x) => {
                 c && context.fillRect(
                    this.x*s + cs*x,
                    this.y*s + cs*y
                ,cs,cs) 
            })
        })
    }
}

class Spike extends Wall {
    constructor(x, y, type, game) {
        super(x, y, type, game);
        this.color = '#61c0ff'
    }

    activateByNeighbor(cell, t) {
        cell.setDanger(cell.x-this.x, cell.y-this.y, 1000, 2000, this.color, t)
    }
}

class CanvasRenderer {
    constructor() {
        this.createRendererComponent();
        document.body.append(this.canvas);
        document.body.style.margin=0;
        document.body.style.background = "#000";
        document.body.style.overflow = "hidden";
        this.resizeRenderer();
        this.cx = 0;
        this.cy = 0;
    }
    
    renderGui(coins, keys) {
        this.ctx.font = 'bold 28px Arial';
        this.ctx.fillStyle = 'gold';
        this.ctx.textAlign = 'left'
        this.ctx.fillText(coins, 35, 20)
        this.ctx.fillRect(15, 5, 10, 10)
        Object.entries(keys).forEach((entry, i) => {
            if (!entry[1]) return;
            this.ctx.fillStyle = entry[0];
            this.ctx.fillRect(100+i*70, 5, 10, 10)
            this.ctx.fillText(entry[1], 125+i*70, 20)
        })
    }

    createRendererComponent() {
        this.canvas = document.createElement('canvas');
        this.ctx = this.canvas.getContext('2d');
    }

    resizeRenderer() {
        this.canvas.width = innerWidth;
        this.canvas.height = innerHeight;
        this.size = Math.round(Math.min(innerWidth, innerHeight)/20);
    }

    updateStaticImage(level) {
        level.staticImage.width = level.width*this.size;
        level.staticImage.height = level.height*this.size;
        let ctx = level.staticImage.getContext("2d");
        level.iterateCells(c => c.isStatic && c.renderCell(this, ctx));
    }

    drawRect(x, y, s, color, context) {
        context = context || this.ctx;
        s = s * this.size;
        let shift = (this.size-s)/2;
        x = x*this.size + shift;
        y = y*this.size + shift;

        context.fillStyle = color;
        context.fillRect(x, y, s, s);
    }

    drawFrame(player, level) {
        this.ctx.clearRect(-1e9,-1e9,2e9,2e9);
        this.ctx.save();
        this.scroll(player)
     
        this.ctx.drawImage(level.staticImage, 0, 0);
        level.iterateCells(c => !c.isStatic && c.renderCell(this, this.ctx));
        player.renderCell(this, this.ctx);
        this.ctx.restore();
    }
    
    scroll(player){
        let cx = player.renderPosition[0]*this.size;
        let cy = player.renderPosition[1]*this.size;
        let maxStep = this.size*0.7
        if (Math.abs(cx-this.cx) > maxStep)
            this.cx += Math.sign(cx-this.cx)*maxStep;
         else
            this.cx = cx;
        
        if (Math.abs(cy-this.cy) > this.size)
            this.cy += Math.sign(cy-this.cy)*maxStep;
         else
            this.cy = cy;
        
        this.ctx.translate(innerWidth/2 - this.cx, innerHeight/2 - this.cy);
    }
    
    elastic(t){
        let k = 0.25;
        return Math.pow(2,-10*t) * 
                   Math.sin((t-k/4)*(2*Math.PI)/k) + 1
    }
    
    renderLevelGui(levelIndex){
        let t = Date.now();
        if (!this.menuDrawStartTimestamp){
            this.menuDrawStartTimestamp = t;
            return;
        }
        t = (Math.min(1, (t-this.menuDrawStartTimestamp)/1000))
        t = this.elastic(t);
        let h = 200 * t;
        let w = innerWidth*(1 - t) + 200*t
        this.ctx.fillStyle = '#000f';
        this.ctx.fillRect(0,0,innerWidth,innerHeight);
        
        this.ctx.fillStyle = 'wheat';
        this.ctx.fillRect((innerWidth-w)/2,(innerHeight-h)/2,w,h);
        this.ctx.fillStyle = 'black'
        this.ctx.textAlign = 'center'
        this.ctx.font = '90px Arial'
        this.ctx.fillText(levelIndex+1, innerWidth/2, innerHeight/2+20);
        this.ctx.font = '15px Arial'
        this.ctx.fillText('START: any key or tap', innerWidth/2, innerHeight/2+60);
        this.ctx.fillText('MOVE: swipe or WSAD', innerWidth/2, innerHeight/2+80);
    }
}

class Level {
    constructor(src, game) {
        this.cells = {
            'x': Wall,
            's': Spike,
            '.': Coin,
            'e': Exit,
            'r': Key,
            'R': Door 
        };
      
        this.map = src.trim()
            .split('\n')
            .map((row, y) =>
                 row.trim()
                 .split('')
                 .map((type, x) => 
            this.createCell(type,x,y, game)));
     
        this.findNeighbors([[-1,0],[1,0],[0,-1],[0,1]]);
        this.findNeighbors([[-1,-1],[1,1],[1,-1],[-1,1]], true);
        
        this.height = this.map.length;
        this.width = Math.max(...this.map.map(r => r.length));
        this.staticImage = document.createElement("canvas");

    }
    
    findNeighbors(neighbors, isDiagonal){
       
        this.iterateCells(c => {
            neighbors.forEach(xy => {
                try {
                   
                    let cell = this.map[c.y + xy[1]][c.x + xy[0]];
                    if(isDiagonal)
                       cell.neighborsX.push(c);
                     else
                       cell.neighbors.push(c);
                    
                } catch (e) {}
            })
        });
    }

    iterateCells(f) {
        this.map.forEach(r => r.forEach(c => c && f(c)));
    }

    createCell(type, x, y, game) {
        if (type === 'p') this.playerEnter = [x, y];
        return new (this.cells[type] || Cell)(x, y, type, game);
    }
}

class Player {
    constructor() {
        this.logicPosition = null;
        this.keys = {};
    }

    lerp(a, b, t) {
        return a + t*(b-a);
    }

    renderCell(renderer){
        let s = this.renderSize, rs = renderer.size;
        s = this.entering? 1-this.entering/30: s;
        let w = s, h = s;
        let t = Date.now()
        if (this.death && this.death < t){
            t = (t - this.death)/1000;
            t = renderer.elastic(t);
            w = t*4
            h = (1 - t)*0.7
        }
        w *= rs;
        h *= rs 
        renderer.ctx.fillStyle = 'wheat'
        renderer.ctx.fillRect(
            this.renderPosition[0]*rs + rs/2 - w/2, 
            this.renderPosition[1]*rs + rs/2 - h/2,w,h);
        
        
        
        if (this.moveToPosition){
           let x0 = this.renderPosition[0]
           let x1 = this.logicPosition[0]
           let y0 = this.renderPosition[1]
           let y1 = this.logicPosition[1]
           let d = rs/7;
            
           renderer.ctx.fillRect(
               Math.min(x0,x1)*rs+1*d,
               Math.min(y0,y1)*rs+1*d,
               Math.abs(x0-x1)*rs||d*0.7,
               Math.abs(y0-y1)*rs||d*0.7)

            renderer.ctx.fillRect(
               Math.min(x0,x1)*rs+3*d,
               Math.min(y0,y1)*rs+3*d,
               Math.abs(x0-x1)*rs||d*0.7,
               Math.abs(y0-y1)*rs||d*0.7)

             renderer.ctx.fillRect(
               Math.min(x0,x1)*rs+5*d,
               Math.min(y0,y1)*rs+5*d,
               Math.abs(x0-x1)*rs||d*0.7,
               Math.abs(y0-y1)*rs||d*0.7)
        }
    }

    calcPlayerPosition(t) {
        if(this.entering){
           this.entering-=1;
            if (this.entering <= 0)
              this.entering= null
        }
        this.renderPosition = [...this.logicPosition];
        this.renderSize = 0.9;

        if (!this.moveToPosition)
            return;

        if (!this.moveStartTime) {
            this.moveStartTime = t;
            this.moveDuration = Math.abs(
                this.logicPosition[0] + this.logicPosition[1] -
                this.moveToPosition[0] - this.moveToPosition[1]
            )*15;
        }

        let dt = (t - this.moveStartTime)/this.moveDuration;
  
        if (dt > 1) {
            this.logicPosition = [...this.moveToPosition];
            this.renderPosition = [...this.moveToPosition];
            this.moveToPosition = null;
            this.moveDuration = this.moveStartTime = 0;
        } else if (dt) {
         
            this.renderPosition[0] = this.lerp(
                this.logicPosition[0], this.moveToPosition[0], dt);
            this.renderPosition[1] = this.lerp(
                this.logicPosition[1], this.moveToPosition[1], dt);
            this.renderSize = 0.7;
        }
    }

    move(dirx, diry){
        if (this.moveToPosition || this.death)
            return;
        let mt = this.moveToPosition = [...this.logicPosition];
        let t = Date.now();
        for (let i=0; i<99; i++) {
            let next = this.levelMap[mt[1]+dirx][mt[0]+diry];
            if (next.isWall) {
                if (next instanceof Door){
                    if (this.keys[next.color]){
                        this.keys[next.color]--;
                        next.isWall = false;
                        next.renderSize = 0;
                    } else break
                    
                } else {
                    break;
                }
            }

            next.activate(t+i*15)

            mt[1] += dirx;   
            mt[0] += diry;

            if (this.death)
              break;

        }
    }

    enterToLevel(level) {
        this.moveToPosition = this.logicPosition = level.playerEnter;
        this.levelMap = level.map;
        this.entering = 30;
        this.death = 0;
        level.iterateCells(c => c.danger = [])
    }
}

class Audio {
    constructor(){
         var AudioContext = window.AudioContext || window.webkitAudioContext;    
        this.context = new AudioContext();
        this.context.resume();

    }
    
    coin() {
        let oscillator = this.context.createOscillator()
        let gain = this.context.createGain()
        oscillator.type="sine"
        oscillator.connect(this.context.destination)
        oscillator.frequency.value=830
        oscillator.start()
        oscillator.stop(this.context.currentTime + 0.01);
        
    }
}

class CollectTheDotsGame {
    constructor() {
        this.coins = 0;
        this.levelIndex = 0;
        this.renderer = new CanvasRenderer();
        this.player = new Player();

        new KeyboardControls(this);
        new TouchControls(this);

        this.startLevel();
//this.gameInProgress = true
        addEventListener('resize', e => {
            this.renderer.resizeRenderer();
            this.renderer.updateStaticImage(this.level);
        });

        setInterval(this.gameLogic.bind(this),30);
        this.gameLogic();
        this.drawFrame();
    }

    gameLogic() {
        let t = Date.now();
        this.level.iterateCells(c => c.tick(t));
        let cx = this.player.logicPosition[0];

        let cy = this.player.logicPosition[1];

        this.level
            .map[cy][cx]
            .activate(t);

       if(this.player.death){
         let dt = t - this.player.death;
         
         if(dt>300)
           this.player
               .enterToLevel(this.level); 
        }
    }

    drawFrame() {
        requestAnimationFrame(this.drawFrame.bind(this));
        if (!this.gameInProgress){
            return this.renderer.renderLevelGui(this.levelIndex);
        }
        this.renderer.menuDrawStartTimestamp = null;
        this.player.calcPlayerPosition(Date.now())
        this.renderer.drawFrame(this.player, this.level);
        this.renderer.renderGui(this.coins, this.player.keys)
    }

    startLevel(){
        this.level = new Level(maps[this.levelIndex], this);
        this.renderer.updateStaticImage(this.level);
        this.player.enterToLevel(this.level);        
    }
    
    nextLevel() {
        this.levelIndex++;
        if (this.levelIndex === maps.length)
            this.levelIndex = 0;
        this.startLevel();
    } 
    
    move(x, y) {
        if (this.gameInProgress){
            if (isFinite(x+y))
                this.player.move(x, y);
        } else {
            this.gameInProgress = true;
            if (!this.audio) {
                this.audio = new Audio();
                
            }
            
        }
    }
}

new CollectTheDotsGame();


              
            
!
999px

Console