简体   繁体   中英

How do I add random sized black blocks that move horizontally across the canvas when you click the button?

How do I add random sized black blocks that move horizontally across the canvas when you click the button?

Here is how the game works: The game that you will implement is called "Block Avoider". It's a game where the user moves a virtuous blue block around and tries to avoid as many of the black blocks that are in a hurry to get from the far right side of the screen to the left. The user uses the arrow keys to move the blue block around. If there is every a collision between the user and the black block, then the black block with which the user collided is erased from the screen and a collision is detected. Game statistics are displayed - the number of blocks avoided, the number of collisions avoided and the number of steps elapsed since the beginning of the game (the number of steps is the number of times the canvas is re-drawn).

Here is my code:

JavaScript code

 const WIDTH = 640; const HEIGHT = 480; const PLAYER_SIZE = 20; const REPAINT_DELAY = 50; const EASY_DELAY = 1750 const MODERATE_DELAY = 1000; const HARD_DELAY = 750; const MAX_BLOCKS = 100; // You might want to add more constants... var playerX = WIDTH / 2 - PLAYER_SIZE / 2, playerY = HEIGHT / 2 - PLAYER_SIZE / 2; // You will definitely NEED to add more variables... document.onkeydown = function(e) { if (e.keyCode == 37) left(); else if (e.keyCode == 38) up(); else if (e.keyCode == 39) right(); else if (e.keyCode == 40) down(); }; function up() { playerY -= 10; repaint(); } function left() { playerX -= 10; repaint(); } function right() { playerX += 10; repaint(); } function down() { playerY += 10; repaint(); } window.onload = repaint; function startGame() { if (repaintTimer == null) repaintTimer = setInterval(repaint, 50); var rand = Math.floor(Math.random() * 2); if (rand >= 80) { var ulX = Math.floor(Math.random() * WIDTH), ulY = Math.floor(Math.random() * HEIGHT), width = Math.floor(Math.random() * 100), height = Math.floor(Math.random() * 100); context.fillStyle = "#000000"; context.fillRect(ulX, ulY, width, height); } else { return false; } } function repaint() { var canvas = document.getElementById("myCanvas"), context = canvas.getContext("2d"); context.fillStyle = "#0000FF"; context.clearRect(0, 0, canvas.width, canvas.height); context.fillRect(playerX, playerY, PLAYER_SIZE, PLAYER_SIZE); } 

HTML Code

 <!doctype html> <html lang="en"> <head> <title>Block-Avoider</title> <meta charset="utf-8"> <script type="text/javascript" src="project.js"></script> </head> <body> <div style="text-align: center;"> <h1>Block Avoider</h1> <canvas id="myCanvas" width="640" height="480" style=" background-color: #fff8dc;vertical-align:bottom; border:solid 5px#000000;"> </canvas> <p> <input type="button" value="Start" id="startGame ();"> </p> <p> <input type="radio" name="difficulty" checked="true"> Easy &nbsp; <input type="radio" name="difficulty"> Moderate &nbsp; <input type="radio" name="difficulty"> Hard </p> <p> Collisions = <span id="collisions">0</span> &nbsp; Avoisions = <span id="escaped">0</span> &nbsp; Steps elapsed = <span id="steps">0</span> &nbsp; </p> <h1 id="gameover"></h1> <p id="pct"></p> </div> </body> </html> 

I think you got "how animation works in canvas" wrong. It's not some css animation. In canvas you need to build all the frames that are necessary to make an animation yourself, you might find some libraries to make that simpler.

So, you need to repaint the black block continuously with decreasing x value to get it moving. So your logic of number of steps = number of repaint might be wrong.

Anyway the moving of black block part you can achieve it with this code.

const WIDTH = 640;
const HEIGHT = 480;

/* Moving Block */
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var SPEED = 10;

function Block() {
    this.width = Math.floor(Math.random() * 100);
    this.height = Math.floor(Math.random() * 100);

    // Make sure the block doesn't go out of view
    this.y = Math.floor(Math.random() * (HEIGHT - this.height));

    // Randomize the direction from which to calculate ulY
    if (Math.random() > 0.5) {
        this.y = HEIGHT - this.y - this.height;
    }

    // Make sure the block doesn't go out of view
    this.x = WIDTH - this.width;

    this.distanceToCross = WIDTH - this.width;
    this.timeToCross = (this.distanceToCross / SPEED) * 100;
    requestAnimationFrame(this.animate.bind(this));
}

Block.prototype.draw = function () {
    context.clearRect(0, 0, WIDTH, HEIGHT);
    context.fillStyle = "#000000";
    context.fillRect(this.x, this.y, this.width, this.height);
};

Block.prototype.animate = function (timestamp) {
    if (!this.start) {
        this.start = timestamp;
    }

    this.x = this.distanceToCross * (1 - ((timestamp - this.start) / this.timeToCross));
    this.draw();

    if (this.x <= 0 - this.width) {
        console.log(new Block());
    } else {
       requestAnimationFrame(this.animate.bind(this));
    }
};

console.log(new Block());

https://codepen.io/anon/pen/ZoXdPB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM