JSFiddle - React, Tailwind, and code Playground
by lastuniverse
HTML
<!DOCTYPE html>
<html>
<head>
<title>Game</title>
</head>
<body>
<canvas id="canvas" widht="500" height="200"></canvas>
<div id="text"></div>
</body>
</html>
CSS
#canvas{
border:1px solid black;
}
JavaScript
var canvas = document.getElementById("canvas");
var text = document.getElementById("text");
var ctx = canvas.getContext("2d");
var width = canvas.width = 500;
var height = canvas.height = 200;
var stop = false;
var tasks = [
{
message: "Затолкайте красный шар за верхнюю грань",
isPerformed: (x,y)=>(y<0)
},
{
message: "Затолкайте красный шар за нижнюю грань",
isPerformed: (x,y)=>(y>height)
},
{
message: "Затолкайте красный шар за левую грань",
isPerformed: (x,y)=>(x<0)
},
{
message: "Затолкайте красный шар за правую грань",
isPerformed: (x,y)=>(x>width)
},
];
var task = tasks[Math.floor(Math.random()*tasks.length)];
text.innerText = task.message;
// класс объекта ЕДА
class Food {
constructor(ctx){
this.ctx = ctx;
this.randomWarp();
this.display = false;
this.warpTime = Math.floor(10+Math.random()*10);
this.count=0;
this.type="food";
}
loop(){
this.count++;
if(this.count>=this.warpTime){
this.count=0;
this.randomWarp();
}
}
// метод телепортирует еду в новые случайные координаты
randomWarp(){
this.x = 20+Math.floor(Math.random()*(width-40));
this.y = 20+Math.floor(Math.random()*(height-40));
}
// метод рисует еду
draw(){
if(!this.display) return;
// this.ctx.fillRect(food.x-5,food.y-5,10,10);
this.ctx.fillStyle = "red";
this.ctx.beginPath();
this.ctx.arc( this.x, this.y, 2, 0, Math.PI * 2);
this.ctx.fill();
}
}
// класс объекта ЕДА
class Mouse {
constructor(ctx, canvas){
this.ctx = ctx;
this.display = false;
this.type="mouse";
let listener = (e)=>{
this.x = e.pageX - e.target.offsetLeft;
this.y = e.pageY - e.target.offsetTop;
}
canvas.addEventListener('mousemove', listener);
canvas.addEventListener('touchmove', listener);
}
loop(){}
// метод рисует еду
draw(){
if(!this.display) return;
// this.ctx.fillRect(food.x-5,food.y-5,10,10);
this.ctx.fillStyle =...