сделай террарию на html и p5js
- User
сделай террарию на html и p5js
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
сделай террарию на html и p5js
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Вот пример простой террарии на HTML и p5.js с базовыми механиками:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<style>
body { margin: 0; overflow: hidden; }
</style>
</head>
<body>
<script>
// Константы
const TILE_SIZE = 32;
const GRAVITY = 0.5;
const JUMP_FORCE = -12;
const MOVE_SPEED = 5;
// Игровые объекты
let player;
let blocks = [];
let inventory = [];
let selectedBlock = 0;
// Типы блоков
const BLOCK_TYPES = {
DIRT: { color: '#8B4513', solid: true },
GRASS: { color: '#90EE90', solid: true },
STONE: { color: '#808080', solid: true },
WOOD: { color: '#DEB887', solid: true },
AIR: { color: '#87CEEB', solid: false }
};
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.width = 30;
this.height = 50;
this.velocityX = 0;
this.velocityY = 0;
this.onGround = false;
}
update() {
// Гравитация
this.velocityY += GRAVITY;
// Движение
if (keyIsDown(65)) { // A - влево
this.velocityX = -MOVE_SPEED;
} else if (keyIsDown(68)) { // D - вправо
this.velocityX = MOVE_SPEED;
} else {
this.velocityX *= 0.8; // Трение
}
// Прыжок
if (keyIsDown(32) && this.onGround) { // Пробел
this.velocityY = JUMP_FORCE;
this.onGround = false;
}
// Применяем физику
this.x += this.velocityX;
this.y += this.velocityY;
// Коллизия с блоками
this.checkCollisions();
}
checkCollisions() {
this.onGround = false;
for (let block of blocks) {
if (!block.type.solid) continue;
let blockLeft = block.x * TILE_SIZE;
let blockRight = blockLeft + TILE_SIZE;
let blockTop = block.y * TILE_SIZE;
let blockBottom = blockTop + TILE_SIZE;
if (this.x + this.width > blockLeft &&
this.x < blockRight &&
this.y + this.height > blockTop &&
this.y < blockBottom) {
// Вертикальная коллизия
if (this.velocityY > 0) {
this.y = blockTop - this.height;
this.velocityY = 0;
this.onGround = true;
} else if (this.velocityY < 0) {
this.y = blockBottom;
this.velocityY = 0;
}
// Горизонтальная коллизия
if (this.velocityX > 0) {
this.x = blockLeft - this.width;
} else if (this.velocityX < 0) {
this.x = blockRight;
}
}
}
}
draw() {
fill(255, 0, 0);
rect(this.x, this.y, this.width, this.height);
}
}
class Block {
constructor(x, y, type) {
this.x = x;
this.y = y;
this.type = type;
}
draw() {
fill(this.type.color);
rect(this.x * TILE_SIZE, this.y * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
}
function setup() {
createCanvas(windowWidth, windowHeight);
player = new Player(width/2, height/2);
// Генерация мира
generateWorld();
// Заполняем инвентарь
for (let type in BLOCK_TYPES) {
if (BLOCK_TYPES[type].solid) {
inventory.push(BLOCK_TYPES[type]);
}
}
}
function generateWorld() {
// Генерация земли
let groundHeight = height / TILE_SIZE - 10;
for (let x = 0; x < width/TILE_SIZE; x++) {
// Поверхность
blocks.push(new Block(x, groundHeight, BLOCK_TYPES.GRASS));
// Подземелье
for (let y = groundHeight + 1; y < height/TILE_SIZE; y++) {
if (random() < 0.8) {
blocks.push(new Block(x, y, BLOCK_TYPES.DIRT));
} else {
blocks.push(new Block(x, y, BLOCK_TYPES.STONE));
}
}
}
// Генерация деревьев
for (let x = 2; x < width/TILE_SIZE - 2; x += 5) {
if (random() < 0.3) {
for (let y = 0; y < 4; y++) {
blocks.push(new Block(x, groundHeight - 1 - y, BLOCK_TYPES.WOOD));
}
}
}
}
function draw() {
background(135, 206, 235); // Небо
// Отрисовка блоков
for (let block of blocks) {
block.draw();
}
// Обновление и отрисовка игрока
player.update();
player.draw();
// Отрисовка инвентаря
drawInventory();
// Подсветка выбранного блока
highlightSelectedBlock();
}
function drawInventory() {
let startX = 10;
let startY = 10;
for (let i = 0; i < inventory.length; i++) {
fill(inventory[i].color);
stroke(i === selectedBlock ? '#ff0' : '#000');
strokeWeight(2);
rect(startX + i * 40, startY, 35, 35);
}
}
function highlightSelectedBlock() {
let mouseBlockX = floor(mouseX / TILE_SIZE);
let mouseBlockY = floor(mouseY / TILE_SIZE);
noFill();
stroke(255);
rect(mouseBlockX * TILE_SIZE, mouseBlockY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
}
function mousePressed() {
let mouseBlockX = floor(mouseX / TILE_SIZE);
let mouseBlockY = floor(mouseY / TILE_SIZE);
if (mouseButton === LEFT) {
// Размещение блока
let canPlace = true;
// Проверяем, не накладывается ли блок на игрока
let playerBlockX = floor(player.x / TILE_SIZE);
let playerBlockY = floor(player.y / TILE_SIZE);
if (mouseBlockX === playerBlockX && mouseBlockY === playerBlockY) {
canPlace = false;
}
if (canPlace) {
blocks.push(new Block(mouseBlockX, mouseBlockY, inventory[selectedBlock]));
}
} else if (mouseButton === RIGHT) {
// Удаление блока
blocks = blocks.filter(block =>
!(block.x === mouseBlockX && block.y === mouseBlockY)
);
}
}
function keyPressed() {
// Выбор блока цифровыми клавишами
if (key >= '1' && key <= '9') {
let index = parseInt(key) - 1;
if (index < inventory.length) {
selectedBlock = index;
}
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
</script>
</body>
</html>
Этот код создает простую 2D террарию со следующими функциями:
Управление персонажем:
Блоки:
Инвентарь:
Генерация мира:
Чтобы расширить игру, можно добавить:
function generateWorld() {
// Использование шума Перлина для более естественного ландшафта
let noiseScale = 0.1;
for (let x = 0; x < width/TILE_SIZE; x++) {
let groundHeight = height/2 + noise(x * noiseScale) * 100;
// ... остальная логика генерации
}
}
class Player {
constructor() {
this.health = 100;
this.maxHealth = 100;
}
drawHealthBar() {
fill(255, 0, 0);
rect(10, 50, this.health * 2, 20);
}
}
class Inventory {
constructor() {
this.items = {};
}
addItem(type, amount = 1) {
if (!this.items[type]) this.items[type] = 0;
this.items[type] += amount;
}
}
const RECIPES = {
WOODEN_PICKAXE: {
requires: { WOOD: 3 },
result: 'WOODEN_PICKAXE'
}
};
function craft(recipe) {
if (hasResources(recipe.requires)) {
removeResources(recipe.requires);
addItem(recipe.result);
}
}
class Enemy {
constructor(x, y) {
this.x = x;
this.y = y;
this.health = 50;
this.speed = 2;
}
update() {
// ИИ для преследования игрока
let dx = player.x - this.x;
this.x += Math.sign(dx) * this.speed;
}
}
function saveGame() {
let gameState = {
player: {
x: player.x,
y: player.y,
inventory: inventory
},
blocks: blocks
};
localStorage.setItem('terraria-save', JSON.stringify(gameState));
}
function loadSprites() {
playerSprite = loadImage('player.png');
blockSprites = {
DIRT: loadImage('dirt.png'),
GRASS: loadImage('grass.png')
// ...
};
}
let sounds = {};
function preload() {
sounds.jump = loadSound('jump.mp3');
sounds.break = loadSound('break.mp3');
sounds.place = loadSound('place.mp3');
}
Это базовая версия, которую можно расширять и улучшать в зависимости от ваших потребностей.