JSFiddle - React, Tailwind, and code Playground
by mucaho
HTML
<script src="https://github.com/craftyjs/Crafty/releases/download/0.7.1/crafty.js"></script>
<!DOCTYPE html>
<html>
<head>
<style type="text/css" media="screen">
body { background: black; }
</style>
</head>
<body>
</body>
</html>
JavaScript
Game = {
// This defines our grid's size and the size of each of its tiles
map_grid: {
width: 24,
height: 16,
tile: {
width: 16,
height: 16
}
},
// The total width of the game screen. Since our grid takes up the entire screen
// this is just the width of a tile times the width of the grid
width: function() {
return this.map_grid.width * this.map_grid.tile.width;
},
// The total height of the game screen. Since our grid takes up the entire screen
// this is just the height of a tile times the height of the grid
height: function() {
return this.map_grid.height * this.map_grid.tile.height;
},
// Initialize and start our game
start: function() {
// Start crafty and set a background color so that we can see it's working
Crafty.init(Game.width(), Game.height());
Crafty.background('rgb(87, 109, 20)');
// Simply start the "Loading" scene to get things going
Crafty.scene('Loading');
}
}
// The Grid component allows an element to be located
// on a grid of tiles
Crafty.c('Grid', {
init: function() {
this.attr({
w: Game.map_grid.tile.width,
h: Game.map_grid.tile.height
})
},
// Locate this entity at the given position on the grid
at: function(x, y) {
if (x === undefined && y === undefined) {
return { x: this.x/Game.map_grid.tile.width, y: this.y/Game.map_grid.tile.height }
} else {
this.attr({ x: x * Game.map_grid.tile.width, y: y * Game.map_grid.tile.height });
return this;
}
}
});
// An "Actor" is an entity that is drawn in 2D on canvas
// via our logical coordinate grid
Crafty.c('Actor', {
init: function() {
this.requires('2D, Canvas, Grid');
},
});
// A Tree is just an Actor with a certain color
Crafty.c('Tree', {
init: function() {
this.requires('Actor, Solid, spr_tree');
},
});
// A Bush is just an Actor with a certain color
Crafty.c('Bush', {
init: function() {
this.requires('Actor, Solid, spr_bush');
},
});
// This is the player-controlled...