defiance/js/script.js
2025-09-02 19:51:56 +02:00

762 lines
No EOL
32 KiB
JavaScript

document.addEventListener('DOMContentLoaded', () => {
const Biome = {
WATER_DEEP: { acceptStructure:false, movements:['swim'], affinities:[('water',0.8),('dark',0.2)], name: 'Eau Profonde', winterColor: '#3D5A80', fallColor: '#3D5A80', summerColor: '#3D5A80', autumnColor: '#3D5A80',maxElevation:0,minElevation:0 },
WATER_SHALLOW: { acceptStructure:false,movements:['swim','ride','navigate','fly'], affinities:[('water',0.8),('life',0.2)],name: 'Eau Peu Profonde', winterColor: '#97aabdff', fallColor: '#5A8AB8', summerColor: '#5A8AB8', autumnColor: '#5A8AB8',maxElevation:1,minElevation:1 },
BEACH: { acceptStructure:true, movements:['walk','ride','fly'],affinities:[('sand',0.8),('water',0.2)],name: 'Sable', winterColor: '#E9D9A1', fallColor: '#E9D9A1', summerColor: '#E9D9A1', autumnColor: '#E9D9A1',maxElevation:2 ,minElevation:2 },
GRASSLAND: { sprite:{frame:4,animationSpeed:200 }, acceptStructure:true, movements:['walk','ride','fly'],affinities:[('life',0.6),('earth',0.2)],name: 'Plaine', winterColor: '#ecf1e3ff', fallColor: '#98C159', summerColor: '#a5a450ff', autumnColor: '#455e21ff',maxElevation:3,minElevation:2 },
FOREST: { acceptStructure:true,movements:['walk','ride','fly'],affinities:[('wood',0.6),('earth',0.4)], name: 'Forêt', winterColor: '#92ac83ff', fallColor: '#21a32cff', summerColor: '#6A994E', autumnColor: '#b88a28ff',maxElevation:3,minElevation:2 },
ENCHANTED_FOREST: { acceptStructure:true,movements:['walk','ride','fly'],affinities:[('wood',0.8),('dark',0.2),('life',0.2)], name: 'Forêt Enchantée', winterColor: '#7B6094', fallColor: '#7B6094', summerColor: '#7B6094', autumnColor: '#7B6094',maxElevation:3,minElevation:2 },
MOUNTAIN: { acceptStructure:false, movements:['climb','fly'],affinities:[('rock',0.6),('wind',0.4)],name: 'Montagne', winterColor: '#F7F7F7', fallColor: '#A9A9A9', summerColor: '#A9A9A9', autumnColor: '#A9A9A9',maxElevation:5,minElevation:3 },
SNOWLAND: { acceptStructure:true,movements:['walk','ride','fly'], affinities:[('ice',0.8),('earth',0.2)],name: 'Toundra', winterColor: '#F7F7F7', fallColor: '#F7F7F7', summerColor: '#F7F7F7', autumnColor: '#F7F7F7',maxElevation:2,minElevation:2 },
SNOWMOUNTAIN: { acceptStructure:false, movements:['climb','fly'],affinities:[('ice',0.4),('rock',0.4),('wind',0.2)],name: 'Mont enneigé', winterColor: '#F7F7F7', fallColor: '#F7F7F7', summerColor: '#F7F7F7', autumnColor: '#F7F7F7',maxElevation:8,minElevation:4 },
DESERT: { acceptStructure:true,movements:['walk','ride','fly'],affinities:[('sand',0.8),('life',0.1),('fire',0.1)], name: 'Désert', winterColor: '#D4A373', fallColor: '#D4A373', summerColor: '#D4A373', autumnColor: '#D4A373',maxElevation:2,minElevation:2 },
RIVER: { acceptStructure:false,movements:['navigate','swim','fly'],affinities:[('water',0.6),('earth',0.2),('life',0.2)],name: 'Rivière', winterColor: '#97aabdff', fallColor: '#5A8AB8', summerColor: '#5A8AB8', autumnColor: '#5A8AB8',maxElevation:2,minElevation:2 },
SWAMP: { acceptStructure:false, movements:['fly'],affinities:[('water',0.6),('earth',0.2),('dark',0.2)],name: 'Marais', winterColor: '#15521eff', fallColor: '#15521eff', summerColor: '#15521eff', autumnColor: '#15521eff',maxElevation:1,minElevation:1 }
}
let grasslandSheet;
let grasslandFrame = 0;
let lastGrassFrameTime = 0;
const NAME_PREFIXES = ["Chêne", "Sombre", "Pierre", "Haut", "Val", "Mur", "Guet", "Clair"];
const NAME_SUFFIXES = ["bourg", "fort", "ville", "mont", "port", "bois", "rivage", "gard"];
const Affinities = ['water','fire','sand','rock','dark','life','ice','wood','wind','metal','time','space','lava','light','spirit'];
const RACE = {
HUMAN: {strength:1,vitality:1,dexterity:1,intelligence:1,wisdom:1,luck:1}
};
const Slot = ['head','body','leg','foot','right-hand','left-hand','two-hands','finger1','finger2','neck','purse','backpack','belt1','belt2'];
const ItemType = {
lightWeapon:{slot:['right-hand','left-hand','backpack'],soul:true,enchant:true},
heavyWeapon:{slot:('two-hands','backpack'),soul:true,enchant:true},
heavyArmor:{slot:('body','backpack'),soul:true,enchant:true},
lightArmor:{slot:('body','backpack'),soul:true,enchant:true},
shield:{slot:('right-hand','left-hand','backpack'),soul:true,enchant:true},
shoes:{slot:('foot','backpack'),soul:true,enchant:true},
pant:{slot:('leg','backpack'),soul:true,enchant:true},
helmet:{slot:('leg','backpack'),soul:true,enchant:true},
potion:{slot:('heal','backpack'),soul:false,enchant:false},
throwable:{slot:('belt','backpack'),soul:true,enchant:true},
craftMaterial:{slot:('backpack'),soul:false,enchant:false},
ring:{slot:('finger1','finger2','backpack'),soul:true,enchant:true},
amulet:{slot:('neck','backpack'),soul:true,enchant:true},
currency:{slot:('purse'),soul:true,enchant:true},
enchantMaterial:{slot:('backpack'),soul:false,enchant:false},
mercantMaterial:{slot:('backpack'),soul:false,enchant:false}
}
const Items = {
'Épée en Bois': { name: 'Épée en Bois', itemType: 'lightWeapon', stats: { strength: 2 }, icon: '🗡️' ,enchantments:[] },
'Armure de Cuir': { name: 'Armure de Cuir', itemType: 'lightArmor', stats: { vitality: 2 }, icon: '🧥',enchantments:[] },
'Claymore': { name: 'Claymore', itemType: 'lightArmor', stats: { vitality: 2 }, icon: '🧥',enchantments:['primal'] },
'Bois': { name: 'Bois', itemType: 'craftMaterial', icon: '🌲',biome:['FOREST'],occurence:0.9},
'stone': { name: 'Pierre', itemType: 'craftMaterial', icon: '🗿',biome:['MOUNTAIN'],occurence:0.4},
'Herbes': { name: 'Herbes', itemType: 'craftMaterial', icon: '🌿',biome:['GRASSLAND'],occurence:0.4},
'Cristaux Magiques': { name: ' enchantMaterial',icon: '💎',biome:['MOUNTAIN','ENCHANTED_FOREST'],occurence:0.005},
'Fer': { name: 'Fer', itemType: 'craftMaterial', icon: '🔩',biome:['MOUNTAIN'],occurence:0.001},
'Mushroom': { name: 'Champignons', itemType: 'craftMaterial', icon: '🍄',biome:['FOREST'],occurence:0.01},
'gold': { name: 'Champignons', itemType: 'mercantMaterial', icon: '💰',biome:['MOUNTAIN','RIVER'],occurence:0.001}
};
const StructureType = {
TOWN: { name: 'Ville', population:15, icon: '🗡️', occurence:0.001,design: `<svg width="0" height="0" style="position:absolute; display: none;"> <defs> <g id="city-svg" viewBox="0 0 100 100"> <defs> <linearGradient id="stoneGradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:#A9A9A9;" /> <stop offset="100%" style="stop-color:#696969;" /> </linearGradient> <linearGradient id="stoneShadowGradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:#808080;" /> <stop offset="100%" style="stop-color:#4A5568;" /> </linearGradient> </defs> <!-- Muraille --> <path d="M 10 95 L 15 70 L 85 70 L 90 95 Z" fill="url(#stoneShadowGradient)" stroke="#1A202C" stroke-width="2" /> <!-- Crénaux muraille --> <path d="M 15 70 L 15 65 L 25 65 L 25 70 L 35 70 L 35 65 L 45 65 L 45 70 L 55 70 L 55 65 L 65 65 L 65 70 L 75 70 L 75 65 L 85 65 L 85 70 Z" fill="url(#stoneShadowGradient)" stroke="#1A202C" stroke-width="1.5"/> <!-- Tour gauche --> <rect x="20" y="30" width="20" height="40" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="2"/> <rect x="18" y="25" width="24" height="5" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="2"/> <!-- Tour droite --> <rect x="60" y="30" width="20" height="40" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="2"/> <rect x="58" y="25" width="24" height="5" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="2"/> <!-- Donjon central --> <rect x="40" y="15" width="20" height="55" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="2"/> <path d="M 38 15 L 38 10 L 43 10 L 43 15 L 48 15 L 48 10 L 53 10 L 53 15 L 58 15 L 58 10 L 63 10 L 63 15 Z" fill="url(#stoneGradient)" stroke="#1A202C" stroke-width="1.5"/> </g> </defs> </svg>`},
VILLAGE: { name: 'Village', population:5, icon: '🗡️',occurence:0.005, design: `<svg width="0" height="0" style="position:absolute; display: none;"> <defs> <!-- Définition du Village --> <g id="village-svg" viewBox="0 0 100 100"> <defs> <linearGradient id="woodGradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:#A0522D;" /> <stop offset="100%" style="stop-color:#8B4513;" /> </linearGradient> <linearGradient id="thatchGradient" x1="0%" y1="0%" x2="0%" y2="100%"> <stop offset="0%" style="stop-color:#D4A373;" /> <stop offset="100%" style="stop-color:#A0522D;" /> </linearGradient> </defs> <!-- Maison principale --> <rect x="20" y="50" width="60" height="45" fill="url(#woodGradient)" stroke="#1A202C" stroke-width="2"/> <polygon points="15,50 85,50 50,20" fill="url(#thatchGradient)" stroke="#1A202C" stroke-width="2"/> <!-- Petite maison derrière --> <rect x="65" y="60" width="25" height="35" fill="#8B4513" stroke="#1A202C" stroke-width="1.5"/> <polygon points="62,60 93,60 77.5,40" fill="#A0522D" stroke="#1A202C" stroke-width="1.5"/> <!-- Fenêtre --> <rect x="45" y="65" width="10" height="10" fill="#2D3748"/> </g> </defs> </svg>`},
FARM: { name: 'Ferme', population:5, icon: '🗡️',occurence:0.010 },
CAMP:{ name: 'Campement', population:2, icon: '⛺',occurence:0.002 },
};
const MONSTER_TYPES = {
GOBLIN: { name: 'Gobelin', icon: '👺', hp: 30, strength: 3, xp: 25, loot: { 'Or': 5 } },
ORC: { name: 'Orc', icon: '👹', hp: 60, strength: 6, xp: 50, loot: { 'Or': 15, 'Fer': 1 } },
};
const ANIMAL_TYPES = {
WOLF: { name: 'Loup', svgAsset: () => wolfsSVG, hp: 20, strength: 4, xp: 15, loot: { 'Cuir': 1, 'Os': 1 }, biomes: [Biome.FOREST, Biome.MOUNTAIN, Biome.SNOWLAND], spawnChance: 0.01 },
BOAR: { name: 'Sanglier', svgAsset: () => boarSVG, hp: 25, strength: 5, xp: 20, loot: { 'Cuir': 2 }, biomes: [Biome.FOREST, Biome.GRASSLAND], spawnChance: 0.02 },
};
class Position{
constructor(x,y,h=0) {
this.x = x;
this.y = y;
this.h = h;
}
setPosition(x, y, h=0) {
this.x = x;
this.y = y;
this.h = h;
}
getPosition() {
return { x: this.x, y: this.y, h: this.h };
}
cartToIso() {
return {
x: (this.x - this.y) * 32,
y: (this.x + this.y) * 16
}
}
// Méthode de l'objet
}
class Tile {
constructor(x, y) {
this.position = new Position(x, y);
this.biome = null;
this.structure = null;
this.setBiome();
this.setElevation();
this.setStructure();
//this.setDesign(ctx);
//this.forestSvg=null;
//this.setSvg();
}
// Méthode de l'objet
setBiome() {
let scale = 0.05;
let eRaw = (simplex.noise2D(this.position.x * scale, this.position.y * scale) + 1) / 2;
let tRaw = (simplex.noise2D(this.position.x * scale * 0.8, this.position.y * scale * 0.8) + 1) / 2;
let mRaw = (simplex.noise2D(this.position.x * scale * 1.5, this.position.y * scale * 1.5) + 1) / 2;
if (eRaw < 0.25) this.biome = Biome.WATER_DEEP;
else if (eRaw < 0.3) this.biome = Biome.WATER_SHALLOW;
else if (eRaw < 0.32) this.biome = Biome.SWAMP;
else if (eRaw < 0.35) this.biome = Biome.BEACH;
else if (eRaw > 0.85) this.biome = Biome.SNOWMOUNTAIN;
else if (eRaw > 0.75) this.biome = Biome.MOUNTAIN;
else {
if (tRaw < 0.3) this.biome = Biome.DESERT;
else if (tRaw > 0.6) this.biome = (mRaw > 0.7) ? Biome.ENCHANTED_FOREST : Biome.FOREST;
else this.biome = Biome.GRASSLAND;
}
}
setDesign(ctx,currentTime){
if (!this.biome) return;
const screenPos = this.position.cartToIso();
const elevationHeight = this.position.h * 8;
let baseColor=null;
ctx.save();
ctx.translate(screenPos.x, screenPos.y - elevationHeight);
if (currentTime.season == 'winter') { baseColor = this.biome.winterColor;}
if (currentTime.season == 'summer') { baseColor = this.biome.summerColor;}
if (currentTime.season == 'fall') { baseColor = this.biome.fallColor;}
if (currentTime.season == 'autumn') { baseColor = this.biome.autumnColor;}
const shadowColor = shadeColor(baseColor, -30);
// Right Face
ctx.fillStyle = shadowColor;
ctx.beginPath();
ctx.moveTo(0, 32); ctx.lineTo(32, 16); ctx.lineTo(32, 16 + elevationHeight); ctx.lineTo(0, 32 + elevationHeight);
ctx.closePath();
ctx.fill();
// Left Face
ctx.fillStyle = shadeColor(shadowColor, -10);
ctx.beginPath();
ctx.moveTo(0, 32); ctx.lineTo(-32, 16); ctx.lineTo(-32, 16 + elevationHeight); ctx.lineTo(0, 32 + elevationHeight);
ctx.closePath();
ctx.fill();
// Top Face
ctx.fillStyle = baseColor;
ctx.beginPath();
ctx.moveTo(0, 0); ctx.lineTo(32, 16); ctx.lineTo(0, 32); ctx.lineTo(-32, 16);
ctx.closePath();
ctx.fill();
if (this.biome === Biome.FOREST && forestSVG) {
ctx.drawImage(forestSVG, -25, -25, 50, 50);
} else if (this.biome === Biome.ENCHANTED_FOREST && mforestSVG) {
ctx.drawImage(mforestSVG, -25, -25, 50, 50);
} else if (this.biome === Biome.SWAMP && swampSVG) {
ctx.drawImage(swampSVG, -25, -5, 50, 30);
}
if (this.structure) {
if (this.structure.type === 'village' && villageSVG) {
ctx.drawImage(villageSVG, -20, -16, 40, 40);
} else if (this.structure.type === 'city' && citySVG) {
ctx.drawImage(citySVG, -24, -28, 48, 48);
}
}
ctx.restore();
}
setExplored(explored) {
this.explored=explored;
}
setElevation(){
if (!this.biome) {
console.error("Impossible de définir l'élévation car le biome n'est pas défini pour la tuile", this.position);
return;
}
this.position.h = Math.floor(Math.random() * (this.biome.maxElevation - this.biome.minElevation+ 1) + this.biome.minElevation);
}
setStructure(){
if (!this.biome) {
console.error("Impossible de définir une structure car le biome n'est pas défini pour la tuile", this.position);
return;
}
var rand = seededRandom(this.position.x * 13 + this.position.y * 59);
var structureChance = rand();
if (structureChance < 0.005 && this.biome.acceptStructure) {
this.structure = { type: 'city', name: NAME_PREFIXES[Math.floor(rand() * NAME_PREFIXES.length)] + NAME_SUFFIXES[Math.floor(rand() * NAME_SUFFIXES.length)], population: StructureType.TOWN.population + Math.floor(rand() * 150), buildings: ['Remparts', 'Place Forte (Château)', 'Grand Marché', 'Forge', 'Alchimiste', 'Enchanteur', 'Écurie', 'Ferme', 'Ferme', 'Ferme', 'Ferme', 'Ferme', 'Lieu de Culte', 'Nombreuses Maisons'] };
} else if (structureChance < 0.02 && this.biome.acceptStructure) {
this.structure = { type: 'village', name: NAME_PREFIXES[Math.floor(rand() * NAME_PREFIXES.length)] + NAME_SUFFIXES[Math.floor(rand() * NAME_SUFFIXES.length)], population: StructureType.VILLAGE.population + Math.floor(rand() * 20), buildings: ['Maison du Chef', 'Marchand', 'Lieu de Culte', 'Ferme', 'Ferme', 'Plusieurs Maisons'] };
}
if ( this.biome.acceptStructure && Math.random() < 0.2) {
this.structure={type:'farm', name: 'farm', population: 2, buildings: []}
// npcs.push({ x: nx, y: ny, homeX: loc.x, homeY: loc.y, workX: nx, workY: ny, type: 'farmer', icon: '🧑‍🌾' });
}
}
}
class Map {
constructor(size) {
this.size = size;
this.tiles = null
this.initializeMap();
}
initializeMap(){
console.time('Map Generation');
this.tiles = Array(this.size).fill(null).map((_, y) => Array(this.size).fill(null).map((_, x) => new Tile(x, y)));
console.timeEnd('Map Generation');
}
}
class Time {
constructor() {
this.year = 812;
this.month = 1;
this.day = 13;
this.season = 'winter';
this.hour = 12;
this.daylight = true;
this.minute=2
}
tick(){
this.minute=(this.minute+1) % 60
if (this.minute==1) this.hour=(this.hour+1) % 24
if (this.hour==1) this.day=(this.day+1) % 30
if (this.day==1) {this.month=(this.month+1) % 12;}
if (this.month==1) {this.year=(this.year+1); }
if (this.month==6 && this.day==21) {this.season='summer'; }
if (this.month==9 && this.day==21) {this.season='autumn'; }
if (this.month==12 && this.day==21) {this.season='winter'; }
if (this.month==3 && this.day==21) {this.season='fall'; }
}
wait(nbrHour){
for (let i = 0; i < nbrHour; i++) {
this.tick();
}
}
setDesign(){
let overlayColor = 'rgba(0,0,0,0)';
let opacity = 0;
if (this.hour > 20 || this.hour < 6) { // Nuit (20h -> 6h)
overlayColor = '#000033';
opacity = 0.5;
} else if (this.hour > 18) { // Soir (18h -> 20h)
overlayColor = '#FF8C00';
opacity = 0.3 * ( ((this.hour/24) - 0.75) / 0.08 );
} else if (this.hour < 8) { // Matin (6h -> 8h)
overlayColor = '#FFD700';
opacity = 0.3 * ( (0.33 - (this.hour/24) ) / 0.08 );
}
ctx.fillStyle = overlayColor;
ctx.globalAlpha = opacity;
document.getElementById('time-display').textContent = `Jour ${this.day}, ${this.hour}:${this.minute}`;
document.getElementById('season-display').textContent = this.season;
}
// Méthode de l'objet
}
class Attributes {
constructor(race) {
this.strength = race.strength;
this.vitality = race.vitality;
this.dexterity = race.dexterity;
this.intelligence = race.intelligence;
this.wisdom = race.wisdom;
this.luck = race.luck;
}
// Méthode de l'objet
}
class Animal {
constructor(type, tile) {
this.type = type;
this.tile = tile; // The tile the animal is currently on
this.lastMoveTime = 0;
this.moveCooldown = 2000 + Math.random() * 3000; // Move every 2-5 seconds
}
update(currentTime, gameMap) {
if (currentTime - this.lastMoveTime > this.moveCooldown) {
this.move(gameMap);
this.lastMoveTime = currentTime;
this.moveCooldown = 2000 + Math.random() * 3000;
}
}
move(gameMap) {
const possibleMoves = [
{ dx: 0, dy: -1 }, { dx: 0, dy: 1 }, { dx: -1, dy: 0 }, { dx: 1, dy: 0 },
];
const move = possibleMoves[Math.floor(Math.random() * possibleMoves.length)];
const newX = this.tile.position.x + move.dx;
const newY = this.tile.position.y + move.dy;
if (newX >= 0 && newX < gameMap.size && newY >= 0 && newY < gameMap.size) {
const targetTile = gameMap.tiles[newY][newX];
if (targetTile.biome && (targetTile.biome.movements.includes('walk') || targetTile.biome.movements.includes('climb')) && this.type.biomes.includes(targetTile.biome)) {
this.tile = targetTile;
}
}
}
setDesign(ctx) {
const svgImage = this.type.svgAsset();
if (!this.tile || !svgImage) return;
const screenPos = this.tile.position.cartToIso();
const elevationHeight = this.tile.position.h * 8;
const size = this.type.size || { w: 40, h: 40 };
const offset = this.type.offset || { x: -20, y: -35 };
ctx.save();
ctx.translate(screenPos.x, screenPos.y - elevationHeight);
ctx.drawImage(svgImage, offset.x, offset.y, size.w, size.h);
ctx.restore();
}
}
class Creature {
constructor(name,attributes,level,affinities,alignments,tile,species,race,hp,items) {
this.name = name;
this.attributes = attributes;
this.level = level;
this.affinities = affinities;
this.name = name;
this.alignments = alignments;
this.species = species;
this.race = race;
this.tile=tile;
this.items=items;
this.hp=hp;
}
fight(){
}
// Méthode de l'objet
}
class Npc {
constructor(name, creature, settlement, equipments) {
this.creature = creature;
this.settlement = settlement;
this.equipments = equipments;
}
talk() {
}
steal() {
}
trade() {
}
// Méthode de l'objet
}
class Player {
constructor(creature,equipments,playerImage) {
this.creature=creature;
this.equipments=equipments;
this.color = '#E53E3E';
//this.playerImage = playerImage ;
//this.setSvg();
}
get position() {
return this.creature.tile.position;
}
setDesign(ctx) {
const tile = this.creature.tile
if(!tile) return;
const screenPos = tile.position.cartToIso();
const elevationHeight = tile.position.h * 8;
ctx.save();
ctx.translate(screenPos.x, screenPos.y - elevationHeight);
if (playerSVG && playerSVG.complete) {
ctx.drawImage(playerSVG, -25, -50, 50, 60);
} else { // Fallback to circle
ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(0, TILE_HEIGHT / 2 - 6, 8, 0, Math.PI * 2); ctx.fill();
}
ctx.restore();
}
move(dx, dy, gameMap) {
const newX = this.position.x + dx;
const newY = this.position.y + dy;
if (newX >= 0 && newX < gameMap.size && newY >= 0 && newY < gameMap.size) {
const targetTile = gameMap.tiles[newY][newX];
if (targetTile.biome && targetTile.biome.movements.includes('walk')) {
this.creature.tile = targetTile;
}
}
}
rename(name) {
this.name = name;
}
equipItem(item,slot) {
equipment.equip(item,slot);
updateAttribute();
}
}
class Settlement {
constructor(level, affinities, name, alignments, position, structures) {
this.level = level;
this.affinities = affinities;
this.name = name;
this.alignments = alignments;
this.structures = structures;
}
// Méthode de l'objet
}
class Resource {
constructor(resourceType, position) {
this.resourceType = resourceType;
this.position = position;
}
collect(tile){
}
collect(creature){
// check if creature can collect
// transfer resulting items creature.items[]=this.resourceType.item
//end object
}
// Méthode de l'objet
}
class Equipment {
constructor(item,slot) {
this.item = item;
this.slot = slot;
}
// Méthode de l'objet
equip(slot) {
//replace current equipment
//check if compatible
//check if equipable
this.slot = slot;
}
unequip() {
this.slot = null;
}
}
class Soul {
constructor(name,description) {
this.name = name;
this.description = description;
}
// Méthode de l'objet
invoke() {
//
}
}
class Item {
constructor(name,duration,itemType) {
this.name = name;
if (!Object.values(ItemType).includes(itemType)) {
throw new Error('Item type invalide !');
}
this.itemType = itemType;
if (duration){
this.duration = itemType.duration
} else {
this.duration = duration
}
}
// Méthode de l'objet
throw() {
// delete after x Tick
}
destroy() {
}
use(){
if (this.duration >1) {
this.duration = this.duration-1
}
else {
this.destroy();
}
}
}
class World {
constructor(name) {
this.name = name;
this.map = new Map(200)
this.currentTime=new Time();
this.animals = [];
this.setAnimals();
}
// Méthode de l'objet
save() {
}
setAnimals() {
console.time('Animal Spawning');
for (let y = 0; y < this.map.size; y++) {
for (let x = 0; x < this.map.size; x++) {
const tile = this.map.tiles[y][x];
if (tile.biome && tile.biome.movements.includes('walk')) {
for (const key in ANIMAL_TYPES) {
const animalType = ANIMAL_TYPES[key];
if (animalType.biomes.includes(tile.biome) && Math.random() < animalType.spawnChance) {
this.animals.push(new Animal(animalType, tile));
}
}
}
}
}
console.log(`Spawned ${this.animals.length} animals.`);
console.timeEnd('Animal Spawning');
}
}
class Camera {
constructor(x=0,y=0,canvas) {
this.x=x;
this.y=y;
this.canvas = canvas;
}
// Méthode de l'objet
setCamera(position) {
var target = position.cartToIso();
var perspective = position.h * ELEVATION_STEP;
this.x = this.canvas.width / 2 - target.x;
this.y = this.canvas.height / 2 - (target.y - perspective);
}
}
class Session {
constructor() {
this.world = new World('Defiance');
this.camera = new Camera(0,0, canvas);
this.setControls();
this.loop = this.loop.bind(this);
this.player=null;
this.setInitial();
}
// Méthode de l'objet
loop(currentTime) {
this.updateAnimals(currentTime);
this.handleMovement(currentTime);
this.camera.setCamera(this.player.position);
this.setDesign();
requestAnimationFrame(this.loop);
}
updateAnimals(currentTime) {
this.world.animals.forEach(animal => {
animal.update(currentTime, this.world.map);
});
}
setInitial(){
let spawnX, spawnY;
do {
spawnX = Math.floor(Math.random() * this.world.map.size);
spawnY = Math.floor(Math.random() * this.world.map.size);
} while (!this.world.map.tiles[spawnY][spawnX].biome || !this.world.map.tiles[spawnY][spawnX].biome.movements.includes('walk') );
this.player = new Player(new Creature('player',new Attributes(RACE.HUMAN),1,null,null,this.world.map.tiles[spawnY][spawnX],'human',RACE.HUMAN,10,null),);
}
setControls() {
document.addEventListener('keydown', e => {
const key = e.key.toLowerCase();
if (key.startsWith('arrow')) { controls[key.replace('arrow', '')] = true; }
else if (['w', 'z'].includes(key)) { controls.up = true; }
else if (['s'].includes(key)) { controls.down = true; }
else if (['a', 'q'].includes(key)) { controls.left = true; }
else if (['d'].includes(key)) { controls.right = true; }
});
document.addEventListener('keyup', e => {
const key = e.key.toLowerCase();
if (key.startsWith('arrow')) { controls[key.replace('arrow', '')] = false; }
else if (['w', 'z'].includes(key)) { controls.up = false; }
else if (['s'].includes(key)) { controls.down = false; }
else if (['a', 'q'].includes(key)) { controls.left = false; }
else if (['d'].includes(key)) { controls.right = false; }
});
const controlMap = { 'btn-up': 'up', 'btn-down': 'down', 'btn-left': 'left', 'btn-right': 'right' };
for (const [id, dir] of Object.entries(controlMap)) {
const btn = document.getElementById(id);
btn.addEventListener('touchstart', e => { e.preventDefault(); controls[dir] = true; }, { passive: false });
btn.addEventListener('touchend', e => { e.preventDefault(); controls[dir] = false; });
}
}
setDesign(){
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(this.camera.x, this.camera.y);
for (let y = 0; y < this.world.map.size; y++) for (let x = 0; x < this.world.map.size; x++) this.world.map.tiles[y][x].setDesign(ctx,this.world.currentTime);
this.world.animals.forEach(animal => animal.setDesign(ctx));
this.player.setDesign(ctx);
this.world.currentTime.setDesign(ctx);
ctx.fillRect(this.camera.x * -1, this.camera.y * -1, canvas.width, canvas.height);
ctx.globalAlpha = 1.0;
//drawFloatingTexts();
ctx.restore();
this.world.currentTime.tick();
}
handleMovement(currentTime) {
if (currentTime - lastMoveTime < 150) return;
let moved = false;
if (controls.up) { this.player.move(0, -1,this.world.map); moved = true; }
if (controls.down) { this.player.move(0, 1,this.world.map); moved = true; }
if (controls.left) { this.player.move(-1, 0,this.world.map); moved = true; }
if (controls.right) { this.player.move(1, 0,this.world.map); moved = true; }
if(moved) lastMoveTime = currentTime;
}
}
const controls = { up: false, down: false, left: false, right: false };
const simplex = new SimplexNoise();
let lastMoveTime = 0;
let isGameReady = false;
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const loadingScreen = document.getElementById('loading');
const TILE_WIDTH = 64;
const TILE_HEIGHT = 32;
const ELEVATION_STEP = TILE_HEIGHT / 4;
let forestSVG, villageSVG, citySVG, boarSVG,wolfsSVG,swampSVG, playerSVG,mforestSVG;
function seededRandom(seed) {
let s = seed;
return () => { s = (s * 9301 + 49297) % 233280; return s / 233280.0; };
}
function loadSvgAsImage(gElement) {
return new Promise((resolve, reject) => {
if (!gElement) {
return reject(new Error("SVG <g> element not found."));
}
const viewBox = gElement.getAttribute('viewBox') || '0 0 100 100';
// Create a new, standalone <svg> element in memory
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
svg.setAttribute('viewBox', viewBox);
// Clone the content of the <g> element into the new <svg>
svg.innerHTML = gElement.innerHTML;
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svg);
const svgBlob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(svgBlob);
const img = new Image();
img.onload = () => {
URL.revokeObjectURL(url);
resolve(img);
};
img.onerror = (err) => {
URL.revokeObjectURL(url);
reject(new Error('Failed to load SVG as image: ' + err.type));
};
img.src = url;
});
}
function shadeColor(c, p) {
let R=parseInt(c.substring(1,3),16),G=parseInt(c.substring(3,5),16),B=parseInt(c.substring(5,7),16);R=parseInt(R*(100+p)/100);G=parseInt(G*(100+p)/100);B=parseInt(B*(100+p)/100);R=(R<255)?R:255;G=(G<255)?G:255;B=(B<255)?B:255;
return "#"+("0"+R.toString(16)).slice(-2)+("0"+G.toString(16)).slice(-2)+("0"+B.toString(16)).slice(-2);
}
async function initializeGame() {
canvas.width = canvas.parentElement.clientWidth;
canvas.height = canvas.parentElement.clientHeight;
try {
// Load SVG assets from HTML and convert them to Image objects
const forestElement = document.getElementById('forest-svg');
const villageElement = document.getElementById('village-svg');
const cityElement = document.getElementById('city-svg');
const playerElement = document.getElementById('player-svg');
const boarElement = document.getElementById('boar-svg');
const wolfsElement = document.getElementById('wolf-pack-svg');
const swampElement = document.getElementById('swamp-svg');
const manaForestElement = document.getElementById('enchanted-forest-svg');
//const cityElement = document.getElementById('swamp-svg');
[forestSVG, villageSVG, citySVG, boarSVG,wolfsSVG,swampSVG, playerSVG,mforestSVG] = await Promise.all([
loadSvgAsImage(forestElement),
loadSvgAsImage(villageElement),
loadSvgAsImage(cityElement),
loadSvgAsImage(boarElement),
loadSvgAsImage(wolfsElement),
loadSvgAsImage(swampElement),
loadSvgAsImage(playerElement),
loadSvgAsImage(manaForestElement)
]);
console.log("All SVG assets loaded as images.");
let session = new Session();
loadingScreen.style.display = 'none';
session.loop();
} catch (error) {
console.error("Failed to load SVG assets:", error);
loadingScreen.innerHTML = "Error loading assets. Please refresh.";
}
}
initializeGame();
})