Welcome to another Mini Code Adventure, an attempt to highlight fun programming projects that you can get started in minutes.
This week, we’re looking at generating mazes with amaze, a simple nodejs package that lets us focus on the fun.
Now, lets make a maze!
- Video: https://www.youtube.com/watch?v=PkSsLdzVncI
- Live Demo: https://codingblocks.github.io/mini-code-adventures-maze-generator/dist/
- Code on Github: https://github.com/codingblocks/mini-code-adventures-maze-generator
Amaze is a simple, non-nonsense library. The only programming we’ll be doing will be drawing it to screen using HTML5’s canvas tag.
If you’re not familiar with canvas then: Good News Everybody: Now’s your chance to do something fun AND learn something new!
Step 1: Setup the project with Yeoman
1 2 3 4 5 6 7 8 9 |
mkdir maze-generator cd maze-generator yo browserify npm install --save amazejs npm install --save priorityjs npm install gulp browserify gulp serve # Now go add some code to index.html and app.js! |
Step 2: Setup the user interface
We’re going to keep things really simple, so just add a canvas element to the web page and add a little bit of glue, and…well, that’s it. (Full code is available on github)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var canvas = document.getElementById('maze'); var pen = canvas.getContext('2d'); pen.fillStyle = '#DDDDDD'; var size = 1; var maze = require('amazejs'); var m = new maze.Backtracker(canvas.width / size, canvas.height / size); m.generate(); for(var row = 0; row < m.height; row++) { for(var col = 0; col < m.width; col++) { if(m.get(row, col)) { pen.fillRect(col * size, row * size, size, size); } } } |
Step 3: Do cool stuff!
Now you’ve got all the pieces and it’s time to start messing around! You could write some code to solve the maze, or maybe turn it into a simple browser game. The world is your oyster!
So, that’s it for this session. Go forth, explore, make cool stuff!