JSFiddle - React, Tailwind, and code Playground
HTML
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Wolf and Sheep</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="game" width="800" height="600"></canvas>
</body>
JavaScript
//Note: This started as a GTP4 created code before I butchered it
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
let sheepLeft = 2;
let time = 0.00;
const epsilon = 0.001;
class Entity {
constructor(x, y, dx, dy, speed, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.speed = speed;
this.color = color;
}
move() {
const d = pointDistance(this.dx, this.dy);
this.x += this.dx*this.speed/d;
this.y += this.dy*this.speed/d;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, 5, 0, 2 * Math.PI);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
const wolf = new Entity(200, 300, 0, 1, 1, 'red');
const sheep1 = new Entity(300, 300, 0, -2, 0.5, 'blue');
const sheep2 = new Entity(300, 300, 0, 2, 0.5, 'blue');
function distance(entity1, entity2) {
const dx = entity1.x - entity2.x;
const dy = entity1.y - entity2.y;
return Math.sqrt(dx * dx + dy * dy);
}
function pointDistance(x, y) {
return Math.sqrt(x*x + y*y);
}
function chase(wolf, sheep) {
wolf.dx = (sheep.x - wolf.x);
wolf.dy = (sheep.y - wolf.y);
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
time += 0.01;
ctx.font = "30px Arial";
ctx.fillText("Time: " + Math.round(time*1000)/1000, 10, 50);
const dist1 = distance(wolf, sheep1);
const dist2 = distance(wolf, sheep2);
var closestSheep;
var farthestSheep;
var closestDist;
var farthestDist;
if(dist1 < dist2){
closestSheep = sheep1;
farthestSheep = sheep2;
closestDist = dist1;
farthestDist =...