xxxxxxxxxx
133
let cats = [];
let dogs = [];
let territory = [];
const numCats = 10;
const numDogs = 10;
const territorySize = 100;
const fightThreshold = 5;
function setup() {
createCanvas(400, 400);
// Create cats
for (let i = 0; i < numCats; i++) {
let cat = new Animal(random(width), random(height), "cat");
cats.push(cat);
}
// Create dogs
for (let i = 0; i < numDogs; i++) {
let dog = new Animal(random(width), random(height), "dog");
dogs.push(dog);
}
}
function draw() {
background(220);
// Explore and mark territory
for (let i = 0; i < cats.length; i++) {
cats[i].explore();
cats[i].markTerritory();
}
for (let i = 0; i < dogs.length; i++) {
dogs[i].explore();
dogs[i].markTerritory();
}
// Handle fights for territory
for (let i = 0; i < territory.length; i++) {
let territoryPos = territory[i].pos;
// Check for cats and dogs within the same territory
let catsInTerritory = cats.filter(cat => dist(cat.pos.x, cat.pos.y, territoryPos.x, territoryPos.y) < fightThreshold);
let dogsInTerritory = dogs.filter(dog => dist(dog.pos.x, dog.pos.y, territoryPos.x, territoryPos.y) < fightThreshold);
// If there are both cats and dogs in the same territory, a fight occurs
if (catsInTerritory.length > 0 && dogsInTerritory.length > 0) {
let randomCat = random(catsInTerritory);
let randomDog = random(dogsInTerritory);
// Cats scratch faster
if (random(1) < 0.5) {
randomDog.health -= 1;
} else {
randomCat.health -= 1;
}
}
}
// Remove animals with zero or negative health
cats = cats.filter(cat => cat.health > 0);
dogs = dogs.filter(dog => dog.health > 0);
// Display animals and territories
for (let i = 0; i < cats.length; i++) {
cats[i].display();
}
for (let i = 0; i < dogs.length; i++) {
dogs[i].display();
}
for (let i = 0; i < territory.length; i++) {
territory[i].display();
}
}
class Animal {
constructor(x, y, type) {
this.pos = createVector(x, y);
this.health = 10;
this.type = type;
this.speed = (type === "cat") ? 2 : 1; // Cats are faster
}
explore() {
this.pos.x += random(-this.speed, this.speed);
this.pos.y += random(-this.speed, this.speed);
this.pos.x = constrain(this.pos.x, 0, width);
this.pos.y = constrain(this.pos.y, 0, height);
}
markTerritory() {
let newTerritory = true;
// Check if the territory is already marked
for (let i = 0; i < territory.length; i++) {
let distToTerritory = dist(this.pos.x, this.pos.y, territory[i].pos.x, territory[i].pos.y);
if (distToTerritory < territorySize) {
newTerritory = false;
break;
}
}
// If not, mark the territory
if (newTerritory) {
territory.push(new Territory(this.pos.x, this.pos.y));
}
}
display() {
if (this.type === "cat") {
fill(255, 0, 0);
} else {
fill(0, 0, 255);
}
ellipse(this.pos.x, this.pos.y, 10, 10);
}
}
class Territory {
constructor(x, y) {
this.pos = createVector(x, y);
}
display() {
noFill();
stroke(0);
ellipse(this.pos.x, this.pos.y, territorySize, territorySize);
}
}