console
let canvas = document.getElementById('canvas');
let cxt = canvas.getContext('2d');
let main = {
map: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
mapArr: [],
state: 0
};
let player = {
x: (canvas.width / 2) - 50,
y: 600 - 10,
w: 100,
h: 10,
hs: 4,
leftMove: false,
rightMove: false,
color: 'purple',
draw: function() {
cxt.fillStyle = this.color;
cxt.fillRect(this.x, this.y, this.w, this.h);
}
};
let ball = {
x: canvas.width / 2,
y: 600 - 18,
r: 8,
color: 'white',
hs: 0,
vs: 0,
draw: function() {
cxt.fillStyle = this.color;
cxt.beginPath();
cxt.arc(this.x, this.y, this.r, 0, Math.PI * 2);
}
};
function BallRender() {
if (ball.x < ball.r || ball.x + ball.r > canvas.width) {
ball.hs = -ball.hs;
}
if (ball.y < ball.r) {
ball.vs = -ball.vs;
}
ball.x += ball.hs;
ball.y += ball.vs;
ball.draw();
}
function MapRender() {
main['mapArr'].forEach((item1, index1) => {
item1.forEach((item2, index2) => {
if (item2.state == 0) {
if (ball.x + ball.r > item2.x && ball.x - ball.r < item2.x + item2.w && ball.y + ball.r > item2.y && ball.y -
ball.r < item2.y + item2.h) {
if (ball.y + ball.r + ball.vs > item2.y + item2.h && ball.x + ball.r > item2.x && ball.x - ball.r < item2.x +
item2.w) {
ball.vs = -ball.vs;
}
item2.state = 1;
}
item2.draw();
}
})
});
cxt.stroke();
}
function PlayerRender() {
if (ball.y + ball.r + ball.vs > player.y && ball.y + ball.r + ball.vs < player.y + player.h && ball.x > player.x &&
ball.x < player.x + player.w) {
ball.vs = -ball.vs;
ball.hs = Math.floor(Math.random()*5+5);
if (ball.hs > 0 && ball.x > player.x && ball.x < player.x + player.w / 2) {
ball.hs = -ball.hs;
}
if (ball.hs < 0 && ball.x < player.x + player.w && ball.x > player.x + player.w / 2) {
ball.hs = -ball.hs;
}
}
player.draw();
}
function render() {
cxt.clearRect(0, 0, canvas.width, canvas.height);
PlayerRender();
BallRender();
MapRender();
cxt.fill();
requestAnimationFrame(render)
}
function Enemy(x, y, w, h, color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.color = color;
this.state = 0;
}
Enemy.prototype.draw = function() {
cxt.fillStyle = this.color;
cxt.strokeStlye = '#ccc';
cxt.strokeRect(this.x, this.y, this.w, this.h);
cxt.fillRect(this.x, this.y, this.w, this.h);
}
function init() {
main['map'].forEach((item1, index1) => {
main['mapArr'].push([]);
item1.forEach((item2, index2) => {
main['mapArr'][index1][index2] = new Enemy(index2 * 50, index1 * 20, 50, 20, '#8af');
})
});
canvas.onmousedown = function() {
canvas.onmousemove = function(e) {
player.x = e.pageX - player.w / 2;
if (main.state == 0) {
ball.x = player.x + player.w / 2;
}
}
canvas.onmouseup = function() {
canvas.onmousemove = null;
}
}
document.onkeydown = function(e) {
if (e.keyCode == 32 && main.state == 0) {
main.state = 1;
ball.hs = 5;
ball.vs = -6;
}
}
render();
}
init();
<canvas id="canvas" width="500" height="700" style="border:1px solid;"></canvas>