Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!doctype html>
- <html>
- <head>
- <title>Monsters</title>
- <style>
- #main {background-color: black;}
- </style>
- </head>
- <body onload="run();">
- <canvas id="main" width="640" height="480"></canvas>
- <script src="keyHandling.js"></script>
- <script>
- /*
- You are a box on the screen, moving with the arrow keys.
- There are other boxes around you in random places.
- There are a random amount of monsters on the screen per
- page refresh, all in random positions.
- */
- var canvas = document.getElementById("main");
- var context = canvas.getContext("2d");
- // generic entity object
- var entity = {
- x: 0,
- y: 0,
- width: 50,
- height: 50,
- color: "rgb(0, 0, 0)"
- };
- var player = Object.create(entity);
- var floorTile = Object.create(entity);
- var initMonsterSwarm = function(numMonsters) {
- var swarm = [];
- for(var m = 0; m < numMonsters; m++) {
- var monster = Object.create(entity);
- monster.color = "rgb(255, 0, 0)";
- swarm.push(monster);
- }
- return swarm;
- };
- var initMonsterPosition = function(swarm) {
- if(swarm !== []) {
- for(var i = 0, j = swarm.length; i < j; i++) {
- swarm[i].x = Math.random()*canvas.width;
- swarm[i].y = Math.random()*canvas.height;
- }
- }
- };
- var spawnMonsterSwarm = function(swarm) {
- if(swarm !== []) {
- for(var s = 0, t = swarm.length; s < t; s++) {
- context.fillStyle = swarm[s].color;
- context.fillRect(swarm[s].x,
- swarm[s].y,
- swarm[s].width,
- swarm[s].height);
- }
- }
- };
- var initFloor = function() {
- floorTile.color = "rgb(0, 0, 100)";
- };
- var drawFloor = function() {
- context.fillStyle = floorTile.color;
- context.fillRect(0, 0, canvas.width, canvas.height);
- };
- var initPlayer = function() {
- player.color = "rgb(255, 255, 255)"
- context.fillStyle = player.color;
- };
- var drawPlayer = function() {
- context.fillStyle = player.color;
- context.fillRect(player.x, player.y, player.width, player.height);
- };
- var update = function() {
- var s = 3;
- if(key.left) {player.x -= s;}
- if(key.up) {player.y -= s;}
- if(key.right) {player.x += s;}
- if(key.down) {player.y += s;}
- };
- var numMonsters = Math.random()*10;
- var initGame = function() {
- swarm = initMonsterSwarm(numMonsters);
- initMonsterPosition(swarm);
- initFloor();
- initPlayer();
- };
- var main = function() {
- drawFloor();
- drawPlayer();
- spawnMonsterSwarm(swarm);
- update();
- };
- var run = function() {
- var FPS = 1000 / 60;
- initGame();
- setInterval(main, FPS);
- };
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement