<!DOCTYPE html>
<html>
<body onkeydown="key_handler()" onload="myfunc1()">
<canvas id="myCanvas" width="300" height="600" style="border:1px solid #d3d3d3;">
</canvas>
<script>
var module_speed = 0;
var speedK = [1, 1];
var max_x = 300;
var max_y = 600;
var obj_height = 10;
var ball_height = 10;
var x = 150;
var y = 290;
var direction = 0;
var xObj_1 = 0;
var yObj_1 = 0;
var xObj_2 = 0;
var yObj_2 = max_y - obj_height;
function myfunc1(){
let playGame = setInterval(function () {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.clearRect(0, 0, max_x, max_y);
ctx.fillStyle = "black";
ctx.fillRect(x, y, 10, 10);
let direction_matrix = [[1, -1], [1, 1], [-1, 1], [-1, -1]];
x += direction_matrix[direction][0] * speedK[0];
y += direction_matrix[direction][1] * speedK[1];
if (direction == 0) {
if (x > max_x-ball_height) {
// edge
direction = 3;
} else if (collision()) {
// platform
onPlatform();
if (y == obj_height) {
direction = 1;
} else {
direction = 3;
}
} else if (y < 0) {
// goal
direction = 1;
onGoal();
}
} else if (direction == 3) {
if (x < 0) {
// edge
direction = 0;
} else if (collision()) {
// platform
onPlatform();
if (y == obj_height) {
direction = 2;
} else {
direction = 1;
}
} else if (y < 0) {
// goal
direction = 2;
onGoal();
}
} else if (direction == 1) {
if (x > max_x - ball_height) {
// edge
direction = 2;
} else if (collision()) {
// platform
onPlatform();
if (y == max_y - obj_height - ball_height) {
direction = 0;
} else {
direction = 2;
}
} else if (y > max_y - ball_height) {
// goal
direction = 0;
onGoal();
}
} else if (direction == 2) {
if (x < 0) {
// edge
direction = 1;
} else if (collision()) {
// platform
onPlatform();
if (y == max_y - obj_height - ball_height) {
direction = 3;
} else {
direction = 1;
}
} else if (y > max_y - ball_height) {
// goal
direction = 3;
onGoal();
}
}
ctx.fillStyle = "red";
ctx.fillRect(xObj_1, yObj_1,100, 10);
ctx.fillRect(xObj_2, yObj_2,100,10);
},10);
}
function collision() {
if (xObj_1 + 100 > x &&
xObj_1 < x+10 &&
yObj_1+10 >= y &&
yObj_1 <= y+10) {
return true;
}
if (xObj_2 + 100 > x &&
xObj_2 < x+10 &&
yObj_2+10 >= y-ball_height &&
yObj_2 <= y+10) {
return true;
}
return false;
}
function onPlatform() {
speedK[module_speed%2]++;
module_speed++;
}
function onGoal() {
speedK = [1, 1];
}
function key_handler(){
if (event.code == 'KeyQ' && xObj_1 > 0) {
xObj_1 -= 5;
}
if (event.code == 'KeyW' && xObj_1 < 200) {
xObj_1 += 5;
}
if (event.code == 'KeyO' && xObj_2 > 0) {
xObj_2 -= 5;
}
if (event.code == 'KeyP' && xObj_2 < 200) {
xObj_2 += 5;
}
}
</script>
</body>
</html>
|