Вот пример симуляции червей в земле на JavaScript. Черви двигаются, едят еду и размножаются. Используется HTML5 Canvas для визуализации.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Симуляция червей в земле</title>
<style>
body {
background-color: #222;
color: #fff;
font-family: Arial, sans-serif;
display: flex;
flex-direction: column;
align-items: center;
margin: 0;
padding: 20px;
}
canvas {
border: 2px solid #555;
background-color: #111;
}
#info {
margin-top: 15px;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Симуляция червей в земле</h1>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<div id="info">Червей: 0 | Еды: 0 | Средний размер: 0</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const infoDiv = document.getElementById('info');
const WIDTH = canvas.width;
const HEIGHT = canvas.height;
const WORM_COUNT = 10;
const FOOD_COUNT = 50;
const WORM_SPEED = 1;
const WORM_GROWTH = 2;
const MAX_WORM_SIZE = 50;
const FOOD_SPAWN_RATE = 0.05;
class Worm {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 10;
this.color = `hsl(${Math.random() * 360}, 100%, 50%)`;
this.speed = WORM_SPEED;
this.direction = Math.random() * Math.PI * 2;
}
update() {
// Движение
this.x += Math.cos(this.direction) * this.speed;
this.y += Math.sin(this.direction) * this.speed;
// Ограничение по краям
if (this.x < 0) this.x = WIDTH;
if (this.x > WIDTH) this.x = 0;
if (this.y < 0) this.y = HEIGHT;
if (this.y > HEIGHT) this.y = 0;
// Случайное изменение направления
if (Math.random() < 0.02) {
this.direction += (Math.random() - 0.5) * Math.PI * 2;
}
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
eat(food) {
const dx = this.x - food.x;
const dy = this.y - food.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.size + food.size) {
this.size += WORM_GROWTH;
return true;
}
return false;
}
checkCollision(worms) {
for (let other of worms) {
if (other !== this) {
const dx = this.x - other.x;
const dy = this.y - other.y;
const distance = Math.sqrt(dx * dx + dy * dy);
if (distance < this.size + other.size) {
return true;
}
}
}
return false;
}
}
class Food {
constructor() {
this.x = Math.random() * WIDTH;
this.y = Math.random() * HEIGHT;
this.size = 5;
this.color = '#0f0';
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
}
}
let worms = [];
let foods = [];
let foodTimer = 0;
function init() {
for (let i = 0; i < WORM_COUNT; i++) {
worms.push(new Worm(Math.random() * WIDTH, Math.random() * HEIGHT));
}
for (let i = 0; i < FOOD_COUNT; i++) {
foods.push(new Food());
}
}
function update() {
// Добавление новой еды
foodTimer += 1;
if (foodTimer > 100 / FOOD_SPAWN_RATE) {
foods.push(new Food());
foodTimer = 0;
}
// Обновление червей
for (let worm of worms) {
worm.update();
// Проверка столкновений
if (worm.checkCollision(worms)) {
worm.size -= 1;
}
// Проверка еды
for (let i = foods.length - 1; i >= 0; i--) {
if (worm.eat(foods[i])) {
foods.splice(i, 1);
}
}
// Размножение
if (worm.size > MAX_WORM_SIZE) {
worms.push(new Worm(worm.x, worm.y));
worm.size = MAX_WORM_SIZE / 2;
}
}
// Удаление маленьких червей
for (let i = worms.length - 1; i >= 0; i--) {
if (worms[i].size < 5) {
worms.splice(i, 1);
}
}
}
function draw() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
// Рисование еды
for (let food of foods) {
food.draw();
}
// Рисование червей
for (let worm of worms) {
worm.draw();
}
// Обновление информации
const totalSize = worms.reduce((sum, worm) => sum + worm.size, 0);
const avgSize = worms.length > 0 ? totalSize / worms.length : 0;
infoDiv.textContent = `Червей: ${worms.length} | Еды: ${foods.length} | Средний размер: ${avgSize.toFixed(1)}`;
}
function gameLoop() {
update();
draw();
requestAnimationFrame(gameLoop);
}
init();
gameLoop();
</script>
</body>
</html>
Этот код создает симуляцию с червями, которые:
- Двигаются по полю
- Едят еду (зеленые точки)
- Растут при поедании еды
- Размножаются, когда достигают определенного размера
- Столкновения с другими червями уменьшают их размер
- Маленькие черви удаляются из симуляции
Каждый червь имеет случайный цвет и двигается в случайном направлении. Еда появляется случайным образом, а скорость появления можно настроить через параметр FOOD_SPAWN_RATE.
Вы можете открыть этот код в браузере, и он начнет симулировать поведение червей в земле.