|
| 1 | +export {generateRandomWorld, drawWorld, updateWorld}; |
| 2 | + |
| 3 | +import { |
| 4 | + randomPositiveInt, |
| 5 | + randomInt, |
| 6 | + randomFloat |
| 7 | +} from "../node_modules/utilsac/random.js"; |
| 8 | +import { |
| 9 | + fillArrayWithFunctionResult |
| 10 | +} from "../node_modules/utilsac/utility.js"; |
| 11 | + |
| 12 | + |
| 13 | +/* |
| 14 | +*/ |
| 15 | +const drawWorld = function (context, world) { |
| 16 | + world.creatures.forEach(function (creature) { |
| 17 | + const {x, y, width, height} = creature; |
| 18 | + context.strokeRect(x, y, width, height) |
| 19 | + }); |
| 20 | +}; |
| 21 | + |
| 22 | +/* |
| 23 | +A world is a rectangle |
| 24 | +Inside a world there are living creatures with |
| 25 | +speed, direction, etc |
| 26 | +*/ |
| 27 | +const generateRandomWorld = function (width = 300, height = 300) { |
| 28 | + const populationSize = 25; |
| 29 | + const world = { |
| 30 | + width, |
| 31 | + height, |
| 32 | + creatures : undefined |
| 33 | + }; |
| 34 | + world.creatures = fillArrayWithFunctionResult( |
| 35 | + function () { |
| 36 | + return generateRandomCreature(world.width, world.height); |
| 37 | + }, |
| 38 | + populationSize); |
| 39 | + return world; |
| 40 | +}; |
| 41 | + |
| 42 | +const generateRandomCreature = function (maxX, maxY) { |
| 43 | + const maxSize = 5; |
| 44 | + const maxSpeed2d = 1 |
| 45 | + const creature = { |
| 46 | + width: randomPositiveInt(maxSize), |
| 47 | + height: randomPositiveInt(maxSize), |
| 48 | + speedX: randomFloat(-maxSpeed2d, maxSpeed2d), |
| 49 | + speedY: randomFloat(-maxSpeed2d, maxSpeed2d), |
| 50 | + x: 0, |
| 51 | + y: 0 |
| 52 | + }; |
| 53 | + creature.x = randomFloat(0, maxX - creature.width); |
| 54 | + creature.y = randomFloat(0, maxY - creature.height); |
| 55 | + return creature; |
| 56 | +}; |
| 57 | + |
| 58 | +const updateWorld = function (world) { |
| 59 | + world.creatures.forEach(function (creature) { |
| 60 | + creature.x = Math.min(world.width - creature.width, Math.max(0, creature.x + creature.speedX)); |
| 61 | + creature.y = Math.min(world.height - creature.height, Math.max(0, creature.y + creature.speedY)); |
| 62 | + }); |
| 63 | +}; |
0 commit comments