<!DOCTYPE html>
<html lang=
"zh_CN"
>
<head>
<meta charset=
"UTF-8"
>
<title>弹球</title>
<script src=
"https://code.jquery.com/jquery-3.3.1.js"
></script>
</head>
<body>
<canvas id=
"canvas"
width=
"400"
height=
"400"
></canvas>
<script>
let canvas = document.getElementById(
"canvas"
);
let context = canvas.getContext(
"2d"
);
class
Ball{
x = 100;
y = 40;
xSpeed = -2;
ySpeed = -2;
constructor(){};
getX(){
return
this.x;
}
getY(){
return
this.y;
}
setX(x){
this.x = x;
}
setY(y){
this.y = y;
}
getXSpeed(){
return
this.xSpeed;
}
setXSpeed(xSpeed){
this.xSpeed = xSpeed;
}
getYSpeed(){
return
this.ySpeed;
}
setYSpeed(ySpeed){
this.ySpeed = ySpeed;
}
draw = () => {
context.beginPath();
context.arc(this.x, this.y, 10, 0, Math.PI * 2, false);
context.strokeRect(0, 0, 400, 400);
context.fill();
};
move = () => {
this.x = this.x + this.xSpeed;
this.y = this.y + this.ySpeed;
};
checkCanvas = (panel) => {
if
(this.x < 5 || this.x > 400 - 5){
this.xSpeed = -this.xSpeed;
}
if
(this.y < 0){
this.ySpeed = -this.ySpeed;
}
if
(this.y > 390 - 10){
if
(this.x > panel.x && this.x < panel.xSize + panel.x){
this.ySpeed = -this.ySpeed;
}
else
{
alert(
"游戏结束"
);
this.x = 100;
this.y = 10;
}
}
}
}
class
Panel{
constructor(){};
x = 200;
y = 390;
xSize = 50;
ySize = 5;
draw(){
context.fillRect(this.x, this.y, this.xSize, this.ySize);
}
}
let ball =
new
Ball();
let panel =
new
Panel();
window.setInterval(() => {
context.clearRect(0, 0, 400, 400);
ball.draw();
panel.draw();
ball.move();
ball.checkCanvas(panel);
},10);
$(
"body"
).keydown((event) => {
if
(event.keyCode == 37){
panel.x = panel.x - 5;
if
(panel.x < 0){
panel.x = 0;
}
}
if
(event.keyCode == 39){
panel.x = panel.x + 5;
if
(panel.x + panel.xSize > 400){
panel.x = 400 - panel.xSize;
}
}
})
</script>
</body>
</html>