Code edit (3 edits merged)
Please save this source code
User prompt
Please fix the bug: 'ReferenceError: imageBackGround is not defined' in or related to this line: 'var backGround = imageBackGround;' Line Number: 484
Code edit (2 edits merged)
Please save this source code
User prompt
Please fix the bug: 'TypeError: this.children[e].setStageReference is not a function' in or related to this line: 'game.update = function () {' Line Number: 1100
Code edit (8 edits merged)
Please save this source code
User prompt
Please fix the bug: 'TypeError: object.addChild is not a function' in or related to this line: 'object.addChild(nameGrid);' Line Number: 620
Code edit (1 edits merged)
Please save this source code
User prompt
Please fix the bug: 'TypeError: object.addChild is not a function' in or related to this line: 'object.addChild(nameGrid);' Line Number: 618
Code edit (8 edits merged)
Please save this source code
User prompt
Please fix the bug: 'TypeError: t is undefined' in or related to this line: 'backGroundImage = LK.getAsset(image, {' Line Number: 539
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (2 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'length')' in or related to this line: 'var nbWords = mainListsList[i].length;' Line Number: 468
Code edit (19 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught TypeError: Cannot read properties of undefined (reading 'length')' in or related to this line: 'var nbWords = mainListsList[i].length;' Line Number: 468
Code edit (1 edits merged)
Please save this source code
Code edit (1 edits merged)
Please save this source code
Code edit (6 edits merged)
Please save this source code
User prompt
Please fix the bug: 'TypeError: Cannot read properties of null (reading 'resetGrid')' in or related to this line: 'mainGrid.resetGrid();' Line Number: 592
Code edit (12 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Uncaught ReferenceError: setHelpButtons is not defined' in or related to this line: 'setHelpButtons('ButtonHelp');' Line Number: 471
Code edit (1 edits merged)
Please save this source code
Code edit (8 edits merged)
Please save this source code
/**** 
* Classes
****/ 
var Button = Container.expand(function (text, options) {
	var self = Container.call(this);
	var buttonGraphics = self.attachAsset(options.assetName || 'button', {
		anchorX: options.anchorX || 0.5,
		anchorY: options.anchorY || 0.5
	});
	self.width = options.width || 200;
	self.height = options.height || 100;
	self.fill = options.fill || 0x00FF00;
	self.text = new Text2(text, {
		size: options.text && options.text.size || 50,
		fill: options.text && options.text.fill || "#000000"
	});
	self.text.anchor.set(0.5, 0.5);
	self.addChild(self.text);
	self.x = options.x || 0;
	self.y = options.y || 0;
	self.on('down', function () {
		if (options.onClick) {
			options.onClick();
		}
	});
});
// Assets will be automatically created and loaded by the LK engine based on usage in the game code.
// GridCell class for individual letters in the grid
var GridCell = Container.expand(function (letter, assetName) {
	var self = Container.call(this);
	var cellGraphics = self.attachAsset(assetName, {
		anchorX: 0.5,
		anchorY: 0.5
	});
	self.width = cellGraphics.width;
	self.height = cellGraphics.height;
	self.clickable = true; //Indique si la cellule est cliquable
	self.wordFrom = ''; //Mot d'origine de la lettre
	self.letter = letter;
	self.policeSize = policeSize;
	var text = new Text2(letter.toUpperCase(), {
		size: self.policeSize,
		fill: "#000000"
	});
	self.texte = text;
	self.texte.anchor.set(0.5, 0.5);
	self.addChild(self.texte);
	self.column = 0; //From 0 to gridColumns - 1
	self.line = 0; //From 0 to gridLines - 1
	self.columnFrom = 0; //Used in case of moving back to the main grid of a letter
	self.lineFrom = 0;
	self.setLetter = function (newLetter) {
		self.letter = newLetter;
		//self.texte.setText(newLetter.toUpperCase());
		self.texte.setText(newLetter);
		self.texte.x = -10;
		self.texte.y = -10;
	};
	self.setColorToLetter = function (color) {
		self.texte.setStyle({
			fill: color
		});
	};
	self.onClickCell = function () {
		//Fonction appelée lors du click sur la cellule
		if (!self.clickable || self.letter == '') {
			return;
		}
		self.isClicked = true;
	};
	self.isClicked = false; //Indique si la cellule a été cliquée
});
// LettersGrid class for managing the grid of letters, same as WordGrid but with control of number of columns and lines
var LettersGrid = Container.expand(function (columns, lines, assetName) {
	var self = Container.call(this);
	self.gridColumns = columns;
	self.gridLines = lines;
	var oneCell = new GridCell('', assetName); //Taille de reference
	self.oneCell = oneCell;
	self.width = oneCell.width * self.gridColumns;
	self.height = oneCell.height + oneCell.height * (self.gridLines - 1);
	self.clickable = true; //Indique si la grille est cliquable
	self.cells = [];
	self.emptyCells = []; //Liste des cellules vides
	self.words = []; //Liste des mots actuellement dans la grille
	self.initializeGrid = function () {
		for (var i = 0; i < self.gridLines; i++) {
			self.cells[i] = [];
			for (var j = 0; j < self.gridColumns; j++) {
				var cell = new GridCell('', assetName);
				cell.x = j * cell.width;
				cell.y = i * cell.height + cell.height / 2;
				self.addChild(cell);
				self.cells[i][j] = cell;
				cell.column = j;
				cell.line = i;
				cell.on('down', function () {
					//Fonction appelée lors du click sur la cellule
					this.onClickCell();
				});
				cell.clickable = self.clickable;
				self.emptyCells.push(cell);
			}
		}
	}; //Fin de la fonction initializeGrid
	self.resetGrid = function () {
		//Réinitialise la grille : remove all cells and repositionnement de la grille
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				self.removeChild(self.cells[i][j]);
			}
		}
		self.cells = [];
		self.emptyCells = [];
		self.gridColumns = 0;
		self.gridLines = 0;
	}; //Fin de la fonction resetGrid
	self.addCell = function (letter, assetName) {
		//Only when there is only one gridLine, add a cell to the grid with the given letter
		var cell = null;
		if (self.gridLines === 1) {
			cell = new GridCell(letter, assetName);
			cell.x = self.gridColumns * cell.width;
			cell.y = cell.height / 2;
			self.addChild(cell);
			self.cells[0][self.gridColumns] = cell;
			cell.column = self.gridColumns;
			cell.line = 0;
			cell.on('down', function () {
				//Fonction appelée lors du click sur la cellule
				this.onClickCell();
			});
			cell.clickable = self.clickable;
			if (letter === '') {
				self.emptyCells.push(cell);
			}
			self.gridColumns++;
			self.x -= cell.width / 2; //Repositionnement de la grille
		}
		return cell;
	}; //Fin de la fonction addCell
	self.removeCell = function (index) {
		//Only when there is only one gridLine, remove a cell from the grid at the given index
		if (self.gridLines === 1 && index >= 0 && index < self.gridColumns) {
			var cell = self.cells[0][index];
			self.removeChild(cell);
			self.cells[0].splice(index, 1);
			self.gridColumns--;
			//Decale les cellules suivantes vers la gauche de une cellule
			for (var i = index; i < self.gridColumns; i++) {
				self.cells[0][i].x -= self.cells[0][i].width;
				self.cells[0][i].column = i;
			}
			self.x += cell.width / 2; //Repositionnement de la grille
		}
	}; //Fin de la fonction removeCell
	self.cellsPositions = function () {
		//Return the absolutes positions of the cells in the game
		var positions = [];
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				positions.push({
					x: self.cells[i][j].x + self.x,
					y: self.cells[i][j].y + self.y
				});
			}
		}
		return positions;
	}; //Fin de la fonction cellsPositions
	self.setLetter = function (column, line, letter) {
		// Set a letter in the grid at (column, line)
		if (column >= 0 && column < self.gridColumns && line >= 0 && line < self.gridLines) {
			self.cells[line][column].setLetter(letter);
			//Retrait de la cellule de la liste des cellules vides
			if (self.emptyCells.includes(self.cells[line][column]) && letter !== '') {
				self.emptyCells.splice(self.emptyCells.indexOf(self.cells[line][column]), 1);
			} else if (!self.emptyCells.includes(self.cells[line][column]) && letter === '') {
				self.emptyCells.push(self.cells[line][column]);
			}
		}
	}; //Fin de la fonction setLetter
	self.addRandomLetter = function (letter) {
		// Add a letter in a random empty cell using emptyCells list
		var added = false;
		if (self.emptyCells.length > 0) {
			var randomIndex = Math.floor(Math.random() * self.emptyCells.length);
			var cell = self.emptyCells[randomIndex];
			cell.setLetter(letter);
			added = true;
			//Retrait de la cellule de la liste des cellules vides
			if (self.emptyCells.includes(cell)) {
				self.emptyCells.splice(self.emptyCells.indexOf(cell), 1);
			}
		}
		return added;
	}; //Fin de la fonction addRandomLetter
	self.removeLetter = function (column, line) {
		// Remove a letter from the grid at (column, line)
		if (column >= 0 && column < self.gridColumns && line >= 0 && line < self.gridLines) {
			self.cells[line][column].setLetter('');
			//Ajout de la cellule à la liste des cellules vides
			if (!self.emptyCells.includes(self.cells[line][column])) {
				self.emptyCells.push(self.cells[line][column]);
			}
		}
	}; //Fin de la fonction removeLetter
	self.findNclickCell = function (letter) {
		//Trouve et clique sur la première cellule contenant la lettre letter
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				if (self.cells[i][j].letter === letter) {
					self.cells[i][j].onClickCell();
					return;
				}
			}
		}
	}; //Fin de la fonction findNclickCell
	self.addWord = function (word) {
		// Add a word in the list of words
		self.words.push(word);
	}; //Fin de la fonction addWord
	self.removeWord = function (word) {
		// Remove a word from the list of words
		if (self.words.includes(word)) {
			self.words.splice(self.words.indexOf(word), 1);
		}
	}; //Fin de la fonction removeWord
	self.firstWord = function () {
		// Return the first word in the list of words
		var word = '';
		for (var i = 0; i < self.gridColumns; i++) {
			word += self.cells[0][i].letter;
		}
		return word;
	}; //Fin de la fonction firstWord
	self.isFull = function () {
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				if (self.cells[i][j].letter === '') {
					return false;
				}
			}
		}
		return true;
	}; //Fin de la fonction isFull
	self.isEmpty = function () {
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				if (self.cells[i][j].letter !== '') {
					return false;
				}
			}
		}
		return true;
	}; //Fin de la fonction isEmpty
	self.colorWordCells = function (word, color) {
		//Colorie les cellules du mot word en couleur color
		for (var j = 0; j < self.gridLines; j++) {
			for (var k = 0; k < self.gridColumns; k++) {
				if (word.includes(self.cells[j][k].letter)) {
					self.cells[j][k].setColorToLetter(color);
					word = word.replace(self.cells[j][k].letter, '');
				}
			}
		}
	}; //Fin de la fonction colorWordCells
	self.colorAllCells = function (color) {
		for (var i = 0; i < self.gridLines; i++) {
			for (var j = 0; j < self.gridColumns; j++) {
				self.cells[i][j].setColorToLetter(color);
			}
		}
	}; //Fin de la fonction colorAllCells
});
/**** 
* Initialize Game
****/ 
//Fin de la classe LettersGrid
var game = new LK.Game({
	backgroundColor: 0x000000 // Init game with black background
});
/**** 
* Game Code
****/ 
/**** 
* GAME DESCRIPTION:
* Game Principle:
	* NAME: QUIZ COOL by Dalhem 2024
	* -There is a board filled with letters, where the player selects letters from a partially filled grid.
	* -With these letters, the player forms a word that appears below the grid, then validates their word.
	* -If the word is among the main list, it is valid, and the player earns points.
	* -The score obtained is proportional to the length of the word.
	* -These letters move randomly within the grid to empty spaces.
	* -If the word is not valid, the letters forming the word are returned to their original position in the grid.
	* -A new word is selected from the main list, shuffled and randomly dispatched in the empty cells.
	* -If there is no more space in the grid, the game is over.
* Game Areas:
	* The screen is divided into 5 main zones in the following descending order:
		1. Score area: displays the player's score.
		2. The grid: the letter grid (main grid).
		3. Word area: displays the word formed by the player (word grid).
		4. Validation area: button to validate the word or erase letters.
		5. Options area (or advertisement).
* Game Progression:
	* At the beginning of the game, the player choose a thema
	* Once the thema selected, the grid is almost empty, containing one  shuffled word.
	* The player can choose a letter in the grid by clicking on it.
	* The chosen letter is added to the word area.
	* The player can validate the word or erase a letter by clicking on the letter in the word, which then returns to its place in the grid.
	* When the player thinks he has formed a word, he can validate it with the validate button located below the word area.
	* If the word is valid, the player earns points, and the score is updated.
	* If the word is not valid, the letters forming the word are returned to their original position in the grid.
	* A new word appears randomly within the grid to empty spaces.
	* If there is no more space in the grid, the game is over.
****/ 
// Button class for creating buttons in the game
var namesList = ["PLANETES AND SATELLITES", "USA STATES", "EUROPEAN CAPITALES", "ANIMALS", "PERIODIC TABLE OF THE ELEMENTS", "VIDEO GAMES"]; //Liste des thèmes de jeu
var backGroundsList = ["BackGroundPlanetesNSatellites", "BackGroundUSAStates", "BackGroundEuropeanCapitales", "BackGroundAnimals", "BackGroundPeriodic", "BackGroundGames"]; //Liste des assets de fond
var usaStates = ["ALABAMA", "ALASKA", "ARIZONA", "ARKANSAS", "CALIFORNIA", "COLORADO", "CONNECTICUT", "DELAWARE", "FLORIDA", "GEORGIA", "HAWAII", "IDAHO", "ILLINOIS", "INDIANA", "IOWA", "KANSAS", "KENTUCKY", "LOUISIANA", "MAINE", "MARYLAND", "MASSACHUSETTS", "MICHIGAN", "MINNESOTA", "MISSISSIPPI", "MISSOURI", "MONTANA", "NEBRASKA", "NEVADA", "NEW-HAMPSHIRE", "NEW-JERSEY", "NEW-MEXICO", "NEW-YORK", "NORTH-CAROLINA", "NORTH-DAKOTA", "OHIO", "OKLAHOMA", "OREGON", "PENNSYLVANIA", "RHODE-ISLAND", "SOUTH-CAROLINA", "SOUTH-DAKOTA", "TENNESSEE", "TEXAS", "UTAH", "VERMONT", "VIRGINIA", "WASHINGTON", "WEST-VIRGINIA", "WISCONSIN", "WYOMING"];
//var europeanCapitales = ["AMSTERDAM", "ANDORRA-LA-VELLA", "ANKARA", "ATHENS", "BELGRADE", "BERLIN", "BERN", "BRATISLAVA", "BRUSSELS", "BUCHAREST", "BUDAPEST", "CHISINAU", "COPENHAGEN", "DUBLIN", "HELSINKI", "KIEV", "LISBON", "LJUBLJANA", "LONDON", "LUXEMBOURG", "MADRID", "MINSK", "MONACO", "MOSCOW", "NICOSIA", "OSLO", "PARIS", "PODGORICA", "PRAGUE", "REYKJAVIK", "RIGA", "ROME", "SAN-MARINO", "SARAJEVO", "SKOPJE", "SOFIA", "STOCKHOLM", "TALLINN", "TBILISI", "TIRANA", "VADUZ", "VALLETTA", "VIENNA", "VILNIUS", "WARSAW", "ZAGREB"];
var europeanCapitales = ["AMSTERDAM", "ANDORRA-LA-VELLA", "ANKARA", "ATHENS", "BELGRADE", "BERLIN", "BERN", "ANKA", "BERA", "ANRA"];
var planetesNsatellites = ["SUN", "MERCURY", "VENUS", "EARTH", "MOON", "MARS", "PHOBOS", "DEIMOS", "JUPITER", "IO", "EUROPA", "GANYMEDE", "CALLISTO", "SATURN", "TITAN", "MIMAS", "ENCELADUS", "TETHYS", "DIONE", "RHEA", "HYPERION", "LAPETUS", "PHOEBE", "URANUS", "PUCK", "MIRANDA", "ARIEL", "UMBRIEL", "TITANIA", "OBERON", "NEPTUNE", "TRITON", "PROTEUS", "NEREID", "PLUTO", "CHARON"];
var animals = ["AARDVARK", "ALBATROSS", "ALLIGATOR", "ALPACA", "ANT", "ANTEATER", "ANTELOPE", "APE", "ARMADILLO", "BABOON", "BADGER", "BAT", "BEAR", "BEAVER", "BEE", "BEETLE", "BISON", "BOAR", "BUFFALO", "BUTTERFLY", "CAMEL", "CANARY", "CAPYBARA", "CARIBOU", "CARP", "CAT", "CATERPILLAR", "CHEETAH", "CHICKEN", "CHIMPANZEE", "CHINCHILLA", "CHOUGH", "CLAM", "COBRA", "COCKROACH", "COD", "CORMORANT", "COYOTE", "CRAB", "CRANE", "CROCODILE", "CROW", "CURLEW", "DEER", "DINOSAUR", "DOG", "DOGFISH", "DOLPHIN", "DONKEY", "DOTTEREL", "DOVE", "DRAGONFLY", "DUCK", "DUGONG", "DUNLIN", "EAGLE", "ECHIDNA", "EEL", "ELAND", "ELEPHANT", "ELK", "EMU", "FALCON", "FERRET", "FINCH", "FISH", "FLAMINGO", "FLY", "FOX", "FROG", "GAUR", "GAZELLE", "GERBIL", "GIRAFFE", "GNAT", "GNU", "GOAT", "GOLDFINCH", "GOLDFISH", "GOOSE", "GORILLA", "GOSHAWK", "GRASSHOPPER", "GROUSE", "GUANACO", "GULL", "HAMSTER", "HARE", "HAWK", "HEDGEHOG", "HERON", "HERRING", "HIPPOPOTAMUS", "HORNET", "HORSE", "HUMMINGBIRD", "HYENA", "IBEX", "IBIS", "JACKAL", "JAGUAR", "JAY", "JELLYFISH", "KANGAROO", "KINGFISHER", "KOALA", "KOOKABURA", "KUDU", "LAPWING", "LARK", "LEMUR", "LEOPARD", "LION", "LLAMA", "LOBSTER", "LOCUST", "LORIS", "LOUSE", "LYREBIRD", "MAGPIE", "MALLARD", "MANATEE", "MANDRILL", "MANTIS", "MARTEN", "MEERKAT", "MINK", "MOLE", "MONKEY", "MOOSE", "MOSQUITO", "MOUSE", "MULE", "NARWHAL", "NEWT", "NIGHTINGALE", "OCTOPUS", "OKAPI", "OPOSSUM", "ORYX", "OSTRICH", "OTTER", "OWL", "OYSTER", "PANTHER", "PARROT", "PARTRIDGE", "PEAFOWL", "PELICAN", "PENGUIN", "PHEASANT", "PIG", "PIGEON", "PORCUPINE", "PORPOISE", "QUAIL", "QUELEA", "QUETZAL", "RABBIT", "RACCOON", "RAIL", "RAM", "RAT", "RAVEN", "REINDEER", "RHINOCEROS", "ROOK", "SALAMANDER", "SALMON", "SANDPIPER", "SARDINE", "SCORPION", "SEAHORSE", "SEAL", "SHARK", "SHEEP", "SHREW", "SKUNK", "SNAIL", "SNAKE", "SPARROW", "SPIDER", "SPOONBILL", "SQUID", "SQUIRREL", "STARLING", "STINGRAY", "STINKBUG", "STORK", "SWALLOW", "SWAN", "TAPIR", "TARSIER", "TERMITE", "TIGER", "TERN", "THRUSH", "TIGER", "TOAD", "TOUCAN", "TROUT", "TURKEY", "TURTLE", "VIPER", "VULTURE", "WALLABY", "WALRUS", "WASP", "WEASEL", "WHALE", "WILDCAT", "WOLF", "WOMBAT", "WOODCOCK", "WOODPECKER", "WORM", "WREN", "YAK", "ZEBRA"];
var periodic = ["HYDROGEN", "HELIUM", "LITHIUM", "BERYLLIUM", "BORON", "CARBON", "NITROGEN", "OXYGEN", "FLUORINE", "NEON", "SODIUM", "MAGNESIUM", "ALUMINIUM", "SILICON", "PHOSPHORUS", "SULFUR", "CHLORINE", "ARGON", "POTASSIUM", "CALCIUM", "SCANDIUM", "TITANIUM", "VANADIUM", "CHROMIUM", "MANGANESE", "IRON", "COBALT", "NICKEL", "COPPER", "ZINC", "GALLIUM", "GERMANIUM", "ARSENIC", "SELENIUM", "BROMINE", "KRYPTON", "RUBIDIUM", "STRONTIUM", "YTTRIUM", "ZIRCONIUM", "NIOBIUM", "MOLYBDENUM", "TECHNETIUM", "RUTHENIUM", "RHODIUM", "PALLADIUM", "SILVER", "CADMIUM", "INDIUM", "TIN", "ANTIMONY", "TELLURIUM", "IODINE", "XENON", "CESIUM", "BARIUM", "LANTHANUM", "CERIUM", "PRASEODYMIUM", "NEODYMIUM", "PROMETHIUM", "SAMARIUM", "EUROPIUM", "GADOLINIUM", "TERBIUM", "DYSPROSIUM", "HOLMIUM", "ERBIUM", "THULIUM", "YTTERBIUM", "LUTETIUM", "HAFNIUM", "TANTALUM", "TUNGSTEN", "RHENIUM", "OSMIUM", "IRIDIUM", "PLATINUM", "GOLD", "MERCURY", "THALLIUM", "LEAD", "BISMUTH", "POLONIUM", "ASTATINE", "RADON", "FRANCIUM", "RADIUM", "ACTINIUM", "THORIUM", "PROTACTINIUM", "URANIUM", "NEPTUNIUM", "PLUTONIUM", "AMERICIUM", "CURIUM", "BERKELIUM", "CALIFORNIUM", "EINSTEINIUM", "FERMIUM", "MENDELEVIUM", "NOBELIUM", "LAWRENCIUM", "RUTHERFORDIUM", "DUBNIUM", "SEABORGIUM", "BOHRIUM", "HASSIUM", "MEITNERIUM", "DARMSTADTIUM", "ROENTGENIUM", "COPERNICIUM", "NIHONIUM", "FLEROVIUM", "MOSCOVIUM", "LIVERMORIUM", "TENNESSINE", "OGANESSON"];
var videogames = ["FINAL-FANTASY", "THE-ELDER-SCROLLS", "WORLD-OF-WARCRAFT", "GUILD-WARS", "STAR-WARS", "BLACK-DESERT", "EVE", "RIFT", "TERA", "NEVERWINTER", "STAR-TREK", "LOTRO", "DC-UNIVERSE", "BLADE&SOUL", "ALBION", "RUNESCAPE", "SKYFORGE", "MAPLESTORY", "AION", "ARCHAGE", "VINDICTUS", "WARFRAME", "THE-SECRET-WORLD", "PLANETSIDE-2", "DUNGEONS&DRAGONS", "STARCRAFT", "DIABLO", "MINECRAFT"];
var mainListsList = [planetesNsatellites, usaStates, europeanCapitales, animals, periodic, videogames]; //Liste des listes de mots principales
var wordsMainList = []; // Initialize wordsMainList to an empty array
var miniBackGrounds = [];
var scoreTest = 0; // Define scoreTest variable
var isScoreUpdatable = false; // Autorise ou pas la mise à jour du score
var score = 100;
var clueWord = '';
var costForLetter = 10; //Coût pour l'indice de la première lettre
var costForWord = 5; //Coût pour l'indice du mot
var costForDrop = 10; //Coût pour l'indice drop letter
var rewardForLetter = 10;
var rewardForEmpty = 50;
/**** 
* Game zones and backgrounds
****/ 
var ScoreZone = {
	x: 0,
	y: 0,
	width: game.width,
	height: 200 * game.height / 2732
};
var MainZone = {
	x: 0,
	y: ScoreZone.height,
	width: game.width,
	height: game.height - 2 * ScoreZone.height
};
var OptionsZone = {
	x: 0,
	y: game.height - ScoreZone.height,
	width: game.width,
	height: 200 * game.height / 2732
};
var backGroundScoreZone = LK.getAsset('ScoreZoneBackGround', {
	x: ScoreZone.x,
	y: ScoreZone.y,
	width: ScoreZone.width,
	height: ScoreZone.height
});
game.addChild(backGroundScoreZone);
var backGroundOptionsZone = LK.getAsset('OptionsZoneBackGround', {
	x: OptionsZone.x,
	y: OptionsZone.y,
	width: OptionsZone.width,
	height: OptionsZone.height
});
game.addChild(backGroundOptionsZone);
/**** 
* Score
****/ 
var scoreTestText = new Text2('0', {
	size: 30,
	fill: "#000000",
	anchorX: 0.5,
	anchorY: 0
});
LK.gui.topLeft.addChild(scoreTestText);
var scoreText = new Text2(score, {
	size: 100,
	fill: "#554444",
	anchorX: 0.5,
	anchorY: 0
});
//LK.gui.top.addChild(scoreText);
/**** 
* Main zone foreground
****/ 
var policeSize = 128;
var mainGrid = null;
var wordGrid = null;
var wordGridWords = []; //Liste des mots deja formés
var isGameStarted = false; //Indique si le jeu a commencé dans un thème
var isThemaSelected = false; //Indique si un thème a été sélectionné
var isHelpOn = false; //Indique si l'aide est activée
var helpTextGrids = []; //Liste des grilles d'aide
var isMGRefillrequired = false; //Indique si le remplissage de la grille principale est nécessaire
var isWordValid = false; //Indique si le mot formé est valide
var isWordInMainList = false; //Indique si le mot formé est dans la liste principale
var isWordAlreadyFound = false; //Indique si le mot formé a déjà été trouvé
var homeButton = null;
var validateButton = null;
var clueButtonLetter = null;
var clueButtonWord = null;
var clueButtonDrop = null;
var animatingImageOn = false; //Drapeau indiquant qu'une image est a scrollscaller
var imagesToScrollRescale = []; //Liste des images a scrollscaller
setBackGroundImage('BackGroundImage', 0, 0, game.width, game.height);
displayminiBackGrounds();
/**** 
* Functions
****/ 
//Fonction displayminiBackGrounds : permet d'afficher les miniatures des fonds et d'y associer un événement de click
//Les assets de fond sont stockés dans la liste backGroundsList
function displayminiBackGrounds() {
	var nbBoutons = backGroundsList.length;
	for (var i = 0; i < backGroundsList.length; i++) {
		var name = namesList[i];
		miniBackGrounds[i] = new Button('', {
			//assetName: backGroundsList[i],
			assetName: 'BackGroundNoImage',
			mainList: mainListsList[i],
			x: game.width / 2,
			y: ScoreZone.height + this.height / 2 + i * (MainZone.height - this.height / 2) / nbBoutons,
			width: game.width,
			height: (MainZone.height - this.height / 2) / nbBoutons,
			fill: "#00FF00",
			text: {
				size: 100,
				fill: "#000000"
			},
			onClick: onClickMiniBackGround
		});
		var oneCell = new GridCell('', 'cell'); // Define oneCell variable
		var nbWords = mainListsList[i].length;
		displayText(name + "(" + nbWords + ")", 'cellWord', nbWords * oneCell.width + oneCell.width / 2, miniBackGrounds[i].height / 2 + 2.5 * oneCell.height);
		//var nameGrid = makeNameGrid(name + "(" + nbWords + ")", 'cellWord');
		//nameGrid.y = miniBackGrounds[i].height / 2 - 2.5 * nameGrid.height;
		//nameGrid.width = miniBackGrounds[i].width - 2 * oneCell.width;
		//nameGrid.height = 2 * miniBackGrounds[i].height;
		//nameGrid.x = -nameGrid.width / 2 + oneCell.width / 2;
		//miniBackGrounds[i].addChild(nameGrid);
		game.addChild(miniBackGrounds[i]);
		setHelpButton('ButtonHelp');
	}
} //Fin de la fonction displayminiBackGrounds
//Fonction onClickMiniBackGround : permet de sélectionner un thème de jeu
function onClickMiniBackGround() {
	var mainList = this.mainList || [];
	if (!isThemaSelected) {
		var mainList = this.mainList;
		var backGround = this.assetName;
		initGameThema(mainList, backGround);
		mainList = mainList || [];
		isThemaSelected = true;
		//On cache les miniatures des fonds
		for (var i = 0; i < miniBackGrounds.length; i++) {
			game.removeChild(miniBackGrounds[i]);
		}
		LK.gui.top.addChild(scoreText);
	}
} //Fin de la fonction onClickMiniBackGround
//Fonction initGameThema : permet d'initialiser le thème du jeu (liste des mots et image de fond)
function initGameThema(mainList, backGround) {
	isGameStarted = false;
	isMGRefillrequired = false;
	isWordValid = false;
	setMainWordsList(mainList);
	setBackGroundImage(backGround, MainZone.x, MainZone.y, MainZone.width, MainZone.height);
	mainGrid = new LettersGrid(6, 6, 'cell');
	mainGrid.initializeGrid();
	mainGrid.x = game.width / 2 - mainGrid.width / 2 + mainGrid.width / (mainGrid.gridColumns + 2);
	mainGrid.y = MainZone.height / 6;
	game.addChild(mainGrid);
	initWordGrid();
	setHomeButton('ButtonHome');
	setValidateButton('buttonValidate');
	setClueButtonFirstLetter('ButtonClueLetter');
	setClueButtonWord('ButtonClueWord');
	setClueButtonDrop('ButtonClueDrop');
} //Fin de la fonction initGameThema
function updateScoreTest(nouveauScore) {
	scoreTestText.setText(nouveauScore);
} //fin updateScoreTest
function updateScore(nouveauScore) {
	if (nouveauScore < 0) {
		nouveauScore = 0;
		score = 0;
	}
	scoreText.setText(nouveauScore);
} //fin updateScore
//Fonction setMainWordsList : permet de définir la liste principale des mots
function setMainWordsList(liste) {
	wordsMainList = liste;
} //Fin de la fonction setMainWordsList
//Fonction setBackGroundImage : permet de définir l'image de fond du jeu
function setBackGroundImage(image, x, y, width, height) {
	backGroundImage = LK.getAsset(image, {
		x: x,
		y: y,
		width: width,
		height: height
	});
	game.addChild(backGroundImage);
} //Fin de la fonction setBackGroundImage
//Fonction setHelpButton : permet de définir le bouton d'aide
//Le bouton d'aide est situé en haut à droite de l'écran dans la zone score a cote du bouton home
function setHelpButton(asset) {
	helpButton = new Button('', {
		assetName: asset,
		x: game.width - 300,
		y: 100,
		width: 200,
		height: 200,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickHelpButton
	});
	game.addChild(helpButton);
} //Fin de la fonction setHelpButton
//Fonction onClickHelpButton : permet d'afficher une aide
//Affiche le backGround de l'aide et le texte d'aide avec displayText
function onClickHelpButton() {
	//On cache les miniatures des fonds
	for (var i = 0; i < miniBackGrounds.length; i++) {
		game.removeChild(miniBackGrounds[i]);
	}
	//Si l'aide est déjà affichée, on la cache
	if (isHelpOn) {
		for (var i = 0; i < helpTextGrids.length; i++) {
			game.removeChild(helpTextGrids[i]);
		}
		helpTextGrids = [];
		isHelpOn = false;
		if (!isGameStarted) {
			//Si le jeu n'a pas commencé, on affiche les miniatures des fonds
			displayminiBackGrounds();
		}
		return;
	}
	//setBackGroundImage('BackGroundHelp', MainZone.x, MainZone.y, MainZone.width, MainZone.height);
	helpTextGrids = displayText(game, "-COOL QUIZZ-\nChoose a thema\nGuess the names\n\nBUTTONS:\nHelp: displays this\nHome: changes thema (keep score)\n\nCLUE BUTTONS (not free):\n-hightlights the first letter\n-hightlights a name\n-gives the letters\n\nHave fun !!", 'cellWord', 200, MainZone.y + MainZone.height / 4);
	game.removeChild(helpButton);
	isHelpOn = true;
	setHomeButton('ButtonHome');
} //Fin de la fonction onClickHelpButton
//Fonction makeNameGrid : permet de créer une grille de lettres pour afficher un mot
function makeNameGrid(word, assetName) {
	var grid = new LettersGrid(word.length, 1, assetName);
	grid.initializeGrid();
	for (var i = 0; i < word.length; i++) {
		grid.setLetter(i, 0, word[i]);
	}
	return grid;
} //Fin de la fonction makeNameGrid
//Fonction displayText : permet d'afficher un texte en utilisant des NameGrid
//Le texte est affiché dans la zone de jeu et une nouvelle NameGrid est créée pour chaque ligne
function displayText(object, text, assetName, x, y) {
	var textsGrid = []; //Liste des NameGrids affichant le texte
	var nameGridRef = new LettersGrid(1, 1, assetName);
	var cellWidth = nameGridRef.oneCell.width;
	var cellHeight = nameGridRef.oneCell.height;
	var lines = text.split('\n');
	var nbLines = lines.length;
	var maxCellsPerLine = Math.floor((MainZone.width - 4 * cellWidth) / cellWidth) * 2;
	for (var i = 0; i < nbLines; i++) {
		var nbCellsPerLine = Math.min(maxCellsPerLine, lines[i].length);
		var partialLines = [];
		for (var j = 0; j < lines[i].length; j += nbCellsPerLine) {
			partialLines.push(lines[i].substring(j, j + nbCellsPerLine));
		}
		for (var j = 0; j < partialLines.length; j++) {
			var nameGrid = null;
			nameGrid = makeNameGrid(partialLines[j], assetName);
			nameGrid.x = x;
			nameGrid.y = y + i / 4 * cellHeight * 2 + j / 2 * cellHeight;
			nameGrid.width /= 2;
			nameGrid.height /= 2;
			//if (object instanceof Container) {
			//scoreTest = "Container valide! ";
			if (object instanceof Container) {
				object.addChild(nameGrid);
			} else {
				game.addChild(nameGrid);
			}
			//} else {
			//scoreTest = "Container non valide! ";
			//game.addChild(nameGrid);
			textsGrid.push(nameGrid);
		}
	}
	return textsGrid;
} //Fin de la fonction displayText	
//Fonction onClickHomeButton : permet de retourner à l'accueil
//On réinitialise les variables et on affiche les miniatures des fonds
function onClickHomeButton() {
	isGameStarted = false;
	isThemaSelected = false;
	isMGRefillrequired = false;
	isWordValid = false;
	isWordInMainList = false;
	wordsMainList = [];
	if (mainGrid) {
		mainGrid.resetGrid();
	}
	game.removeChild(backGroundImage);
	game.removeChild(mainGrid);
	game.removeChild(wordGrid);
	game.removeChild(homeButton);
	game.removeChild(validateButton);
	game.removeChild(clueButtonLetter);
	game.removeChild(clueButtonWord);
	game.removeChild(clueButtonDrop);
	game.removeChild(scoreText);
	displayminiBackGrounds();
} //Fin de la fonction onClickHomeButton
//Fonction setHomeButton : permet de définir le bouton de retour à l'accueil
//Situé en haut à droite de l'écran dans la zone score
function setHomeButton(asset) {
	homeButton = new Button('', {
		assetName: asset,
		x: game.width - 100,
		y: 100,
		width: 200,
		height: 200,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickHomeButton
	});
	game.addChild(homeButton);
} //Fin de la fonction setHomeButton
//Fonction onClickValidateButton : permet de valider le mot formé par le joueur
function onClickValidateButton() {
	var isValide = validateWord(mainGrid.words);
	if (isValide) {
		//On vide la grille des lettres formant le mot final apres x secondes
		LK.setTimeout(function () {
			var tableauFrom = wordGrid.cellsPositions();
			for (var i = 0; i < tableauFrom.length; i++) {
				var ticks = Math.floor(Math.random() * 30) + 40;
				scrollCoins(1, 'RewardsCoin', tableauFrom[i].x, tableauFrom[i].y, 0, ticks, rewardForLetter, 'SoundRewardCoin', game.width / 2, MainZone.y - scoreText.height / 2);
			}
			if (isWordInMainList) {
				//Si le mot est dans la liste principale, on compense les lettres utilisées avec récompense
				for (var i = 0; i < wordGrid.gridColumns; i++) {
					mainGrid.setLetter(wordGrid.cells[0][i].columnFrom, wordGrid.cells[0][i].lineFrom, wordGrid.cells[0][i].letter);
					var cellWidth = mainGrid.oneCell.width;
					var cellHeight = mainGrid.oneCell.height;
					var xAbsCell = (wordGrid.cells[0][i].columnFrom + 1) * cellWidth + mainGrid.x - cellWidth;
					var yAbsCell = (wordGrid.cells[0][i].lineFrom + 1) * cellHeight + mainGrid.y - cellHeight / 2;
					scrollCoins(1, 'RewardsCoin', xAbsCell, yAbsCell, 60, 30, rewardForLetter, 'SoundRewardCoin', game.width / 2, MainZone.y - scoreText.height / 2);
				}
				isWordInMainList = false;
			}
			wordGrid.resetGrid();
			initWordGrid();
		}, 1000);
		if (mainGrid.isEmpty()) {
			scrollCoins(1, 'RewardsCoin', mainGrid.x + mainGrid.width / 2, mainGrid.y + mainGrid.height / 2, 0, 30, rewardForEmpty, 'SoundEmptyGrid', game.width / 2, MainZone.y - scoreText.height / 2);
			isMGRefillrequired = true;
		}
	} else {
		//Le mot n'est pas valide, on remet les lettres dans la grille principale
		LK.setTimeout(function () {
			for (var i = 0; i < wordGrid.gridColumns; i++) {
				mainGrid.setLetter(wordGrid.cells[0][i].columnFrom, wordGrid.cells[0][i].lineFrom, wordGrid.cells[0][i].letter);
			}
			if (isWordAlreadyFound) {
				//Si le mot a déjà été trouvé, on ne remet pas d'autres lettres dans la grille principale
				isWordAlreadyFound = false;
				isMGRefillrequired = false;
			} else {
				isMGRefillrequired = true;
			}
			wordGrid.resetGrid();
			initWordGrid();
		}, 1000);
	}
} //Fin de la fonction onClickValidateButton
//Fonction setValidateButton : permet de définir le bouton de validation
function setValidateButton(asset) {
	validateButton = new Button('', {
		assetName: asset,
		x: game.width / 2 + 50,
		y: wordGrid.y + wordGrid.height + 350,
		width: 300,
		height: 300,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickValidateButton
	});
	game.addChild(validateButton);
} //Fin de la fonction setValidateButton
//Fonction onClickClueButtonLetter : permet de donner un indice au joueur
function onClickClueButtonLetter() {
	if (!wordGrid.isEmpty()) {
		//Si le joueur a déjà commencé à former un mot, on ne donne pas d'indice
		return;
	}
	if (mainGrid.words.length >= 1) {
		var randomIndex = Math.floor(Math.random() * mainGrid.words.length);
		var word = mainGrid.words[randomIndex];
		var firstLetter = word[0];
		var line = -1;
		var col = -1;
		var isFound = false;
		for (var i = 0; i < mainGrid.gridLines && !isFound; i++) {
			//On colorie la première lettre du mot pendant 2 secondes
			for (var j = 0; j < mainGrid.gridColumns && !isFound; j++) {
				if (mainGrid.cells[i][j].letter == firstLetter) {
					mainGrid.cells[i][j].setColorToLetter("#FF5500");
					line = i;
					col = j;
					isFound = true;
				}
			}
		}
		LK.setTimeout(function () {
			if (mainGrid.cells[line] && mainGrid.cells[line][col]) {
				mainGrid.cells[line][col].setColorToLetter("#000000");
				if (score >= costForLetter) {
					scrollCostCoins(clueButtonLetter.x, clueButtonLetter.y, 1, costForLetter);
				} else {
					score -= costForLetter;
				}
			}
		}, 3000);
	}
} //Fin de la fonction onClickClueButtonLetter
//Fonction setClueButtonFirstLetter : permet de définir le bouton d'indice
function setClueButtonFirstLetter(asset) {
	clueButtonLetter = new Button('', {
		assetName: asset,
		x: game.width / 2 - 350,
		y: 150,
		// Set a default y position
		width: 200,
		height: 200,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickClueButtonLetter
	});
	clueButtonLetter.x = game.width - clueButtonLetter.width; // Adjust x position after initialization
	clueButtonLetter.y = mainGrid.y + clueButtonLetter.height; // Adjust y position after initialization
	game.addChild(clueButtonLetter);
} //Fin de la fonction setClueButtonFirstLetter
//Fonction onClickClueButtonWord : permet de donner un indice au joueur (change la couleur des lettres d'un des mots au hasard)
function onClickClueButtonWord() {
	if (!wordGrid.isEmpty()) {
		//Si le joueur a déjà commencé à former un mot, on ne donne pas d'indice
		return;
	}
	//On change la couleur des lettres d'un des mots au hasard de mainGrid.words
	if (mainGrid.words.length >= 1) {
		var randomIndex = Math.floor(Math.random() * mainGrid.words.length);
		var word = mainGrid.words[randomIndex];
		var randomColor = Math.floor(Math.random() * 16777215).toString(16); //On choisit une couleur au hasard parmi 16777215 couleurs
		mainGrid.colorWordCells(word, "#" + randomColor);
		LK.setTimeout(function () {
			mainGrid.colorWordCells(word, "#000000");
			scrollCostCoins(clueButtonWord.x, clueButtonWord.y, word.length, costForWord);
		}, 5000);
	}
} //Fin de la fonction onClickClueButtonWord
//Fonction setClueButtonWord : permet de définir le bouton d'indice focus word
function setClueButtonWord(asset) {
	clueButtonWord = new Button('', {
		assetName: asset,
		x: game.width / 2 - 350,
		y: mainGrid.y,
		// Set a default y position
		width: 200,
		height: 200,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickClueButtonWord
	});
	clueButtonWord.x = game.width - clueButtonWord.width; // Adjust x position after initialization
	clueButtonWord.y = mainGrid.y + 2 * clueButtonWord.height; // Adjust y position after initialization
	game.addChild(clueButtonWord);
} //Fin de la fonction setClueButtonWord
//Fonction onClickClueButtonDrop : permet de donner un indice au joueur (drop letter)
function onClickClueButtonDrop() {
	if (wordGrid.isEmpty() && clueWord == '') {
		//On prend un mot au hasard dans la liste principale et on clique sur les deux premières lettres
		if (mainGrid.words.length > 0) {
			var randomIndex = Math.floor(Math.random() * mainGrid.words.length);
			var word = mainGrid.words[randomIndex];
			clueWord = word; //On garde le mot pour le prochain indice
			var firstLetter = word[0];
			var secondLetter = word[1];
			mainGrid.findNclickCell(firstLetter);
			LK.setTimeout(function () {
				mainGrid.findNclickCell(secondLetter);
				scrollCostCoins(clueButtonDrop.x, clueButtonDrop.y, 2, costForDrop);
			}, 100);
		}
	} else if (!wordGrid.isEmpty() && clueWord != '') {
		//On reconstitue le mot contenu dans wordGrid
		var word = wordGrid.firstWord();
		var letterRank = wordGrid.gridColumns;
		if (word == clueWord.substring(0, letterRank)) {
			var letter = clueWord[letterRank];
			//On descend la suite du mot
			mainGrid.findNclickCell(letter);
			if (word != clueWord) {
				scrollCostCoins(clueButtonDrop.x, clueButtonDrop.y, 1, letterRank * costForDrop);
			} else if (word == clueWord && word != '') {
				clueWord = '';
			}
		} else {
			//On réinitialise les parametres de l'indice drop letter
			clueWord = '';
		}
	}
} //Fin de la fonction onClickClueButtonDrop
//Fonction setClueButtonDrop : permet de définir le bouton d'indice drop letter
function setClueButtonDrop(asset) {
	clueButtonDrop = new Button('', {
		assetName: asset,
		x: game.width / 2 - 350,
		y: mainGrid.y,
		// Set a default y position
		width: 200,
		height: 200,
		fill: "#00FF00",
		text: {
			size: 50,
			fill: "#000000"
		},
		onClick: onClickClueButtonDrop
	});
	clueButtonDrop.x = game.width - clueButtonDrop.width; // Adjust x position after initialization
	clueButtonDrop.y = mainGrid.y + 3 * clueButtonDrop.height; // Adjust y position after initialization
	game.addChild(clueButtonDrop);
} //Fin de la fonction setClueButtonDrop
//Fonction initWordGrid : permet d'initialiser la grille des lettres formant le mot
function initWordGrid() {
	//Initialise la grille des lettres formant le mot
	wordGrid = game.addChild(new LettersGrid(0, 1, 'cellWord'));
	wordGrid.initializeGrid();
	wordGrid.x = game.width / 2 + 100;
	wordGrid.y = ScoreZone.height + mainGrid.height + 300;
} //Fin de la fonction initWordGrid
//Fonction pickAndShakeSingleWord : permet de choisir un mot dans la liste des mots et de le mélanger
function pickAndShakeSingleWord() {
	if (wordsMainList.length == 0) {
		return {
			word: '',
			wordShuffled: ''
		};
	}
	var randomIndex = Math.floor(Math.random() * wordsMainList.length);
	var word = wordsMainList[randomIndex];
	if (!word) {
		return {
			word: '',
			wordShuffled: ''
		};
	}
	var wordShuffled = word.split('').sort(function () {
		return 0.5 - Math.random();
	}).join('');
	wordsMainList.splice(randomIndex, 1); //Retire le mot de la liste principale pour ne pas le reprendre
	return {
		word: word,
		wordShuffled: wordShuffled
	};
} //Fin de la fonction pickAndShakeSingleWord
//Fonction pickAndShakeWords : permet de choisir plusieurs mots dans la liste des mots et de les mélanger
function pickAndShakeWords(numberOfWords) {
	var words = [];
	var wordsShuffeled = [];
	for (var i = 0; i < numberOfWords; i++) {
		var wordSingle = pickAndShakeSingleWord();
		var word = wordSingle.word;
		var shuffledWord = wordSingle.wordShuffled;
		words.push(word);
		wordsShuffeled.push(shuffledWord);
	}
	return {
		words: words,
		wordsShuffeled: wordsShuffeled
	};
} //Fin de la fonction pickAndShakeWords
//Fonction putRandomShuffledWordInGrid : permet de mettre un mot mélangé dans la grille principale
function putRandomShuffledWordInGrid() {
	var word = pickAndShakeSingleWord().word;
	var isPossibleToAddletter = true; //Indique si le mot peut être ajouté dans la grille principale
	for (var i = 0; i < word.length && isPossibleToAddletter; i++) {
		isPossibleToAddletter = mainGrid.addRandomLetter(word[i]);
	}
	if (isPossibleToAddletter && word != '') {
		mainGrid.addWord(word);
	}
	return isPossibleToAddletter;
} //Fin de la fonction putRandomShuffledWordInGrid
//Fonction addCellLetterToWord : permet d'ajouter une cellule à la liste des lettres formant le mot situé sous la grille
function addCellLetterToWord(letter) {
	var cellLetter = wordGrid.addCell(letter, 'cellWord');
	return cellLetter;
} //Fin de la fonction addCellLetterToWord
//Fonction validateWord : permet de valider le mot formé par le joueur dans une liste de mots
function validateWord(liste) {
	var word = wordGrid.firstWord();
	var count = liste.filter(function (element) {
		return element === word;
	}).length;
	if (liste.includes(word)) {
		wordGridWords.push(word);
		mainGrid.removeWord(word); //Retire le mot de la grille principale
		isWordValid = true;
	} else if (wordsMainList.includes(word)) {
		isWordValid = true;
		isWordInMainList = true;
		wordGridWords.push(word);
		wordsMainList.splice(wordsMainList.indexOf(word), 1); //Retire le mot de la liste principale
	} else if (wordGridWords.includes(word)) {
		isWordAlreadyFound = true;
		isWordValid = false;
	} else {
		isWordValid = false;
	}
	wordGrid.colorAllCells(isWordValid ? "#00FF00" : "#FF0000");
	return isWordValid;
} //Fin de la fonction validateWord
// Fonction pour créer une image à faire défiler et redimensionner
function createImageToSrollRescale(asset, xFrom, yFrom) {
	var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
	// Création d'une nouvelle instance de l'image asset 
	var assetToScrollRescale = LK.getAsset(asset, {
		anchorX: 0.5,
		anchorY: 0.5,
		scaleX: 1.0,
		scaleY: 1.0,
		x: xFrom,
		y: yFrom
	});
	var imageToScrollRescale = {
		animate: options.animate !== undefined ? options.animate : false,
		image: options.image !== undefined ? options.image : assetToScrollRescale,
		xToReach: options.xToReach !== undefined ? options.xToReach : 0,
		yToReach: options.yToReach !== undefined ? options.yToReach : 0,
		scaleToReach: options.scaleToReach !== undefined ? options.scaleToReach : 1.0,
		nbTicksBeforeStart: options.nbTicksBeforeStart !== undefined ? options.nbTicksBeforeStart : 0,
		nbTicksLeft: options.nbTicksLeft !== undefined ? options.nbTicksLeft : 0,
		isDestroyedOnEnd: options.isDestroyedOnEnd !== undefined ? options.isDestroyedOnEnd : false,
		valueToAddToScore: options.valueToAddToScore !== undefined ? options.valueToAddToScore : 0,
		soundOnEnd: options.soundOnEnd !== undefined ? options.soundOnEnd : ''
	};
	game.addChild(assetToScrollRescale);
	return imageToScrollRescale;
} //fin createImageToSrollRescale
//Fonction createImages : permet de créer plusieurs images à scrollrescaler avec les même parametres
//Chaque image est crée à l'emplacement donnée dans le tableauFrom composé de (x, y)
function createImages(asset, tableauFrom, options) {
	for (var i = 0; i < tableauFrom.length; i++) {
		var image = createImageToSrollRescale(asset, tableauFrom[i].x, tableauFrom[i].y, options);
		imagesToScrollRescale.push(image);
	}
} //fin createImages
//Fonction scrollCostCoins : permet de faire défiler des pièces de monnaie
function scrollCostCoins(xTo, yTo, nbCoins, valueToTakeFromScore) {
	for (var i = 0; i < nbCoins; i++) {
		var image = createImageToSrollRescale('CostCoin', game.width / 2, MainZone.y - scoreText.height / 2, {
			xToReach: xTo,
			yToReach: yTo,
			nbTicksLeft: 30 + i * 2,
			valueToAddToScore: -valueToTakeFromScore,
			soundOnEnd: 'SoundCostCoin',
			isDestroyedOnEnd: true,
			animate: true
		});
		imagesToScrollRescale.push(image);
	}
} //fin scrollCostCoins
//Fonction scrollCoins : permet de faire défiler des pièces de monnaie
function scrollCoins(nbCoins, asset, xFrom, yFrom, nbTicksBeforeStart, ticksLeft, valueToAddToScore, soundOnEnd, xTo, yTo) {
	for (var i = 0; i < nbCoins; i++) {
		var image = createImageToSrollRescale(asset, xFrom, yFrom, {
			xToReach: xTo,
			yToReach: yTo,
			nbTicksBeforeStart: nbTicksBeforeStart,
			nbTicksLeft: ticksLeft,
			valueToAddToScore: valueToAddToScore,
			soundOnEnd: soundOnEnd,
			isDestroyedOnEnd: true,
			animate: true
		});
		imagesToScrollRescale.push(image);
	}
} //fin scrollCoins
//Fonction scrollRescaleImages permettant de faire défiler et redimensionner des images
function scrollRescaleImages() {
	for (var i = 0; i < imagesToScrollRescale.length; i++) {
		if (imagesToScrollRescale[i].animate) {
			if (imagesToScrollRescale[i].nbTicksBeforeStart > 0) {
				imagesToScrollRescale[i].nbTicksBeforeStart -= 1;
			} else if (imagesToScrollRescale[i].nbTicksLeft == 0) {
				//On joue un son si soundOnEnd est défini
				if (imagesToScrollRescale[i].soundOnEnd != '') {
					LK.getSound(imagesToScrollRescale[i].soundOnEnd).play();
				}
				//On ajoute la valeur à ajouter au score si valueToAddToScore est défini
				if (imagesToScrollRescale[i].valueToAddToScore != 0) {
					score += imagesToScrollRescale[i].valueToAddToScore;
					isScoreUpdatable = true;
				}
				//On détruit l'image si isDestroyedOnEnd est vrai
				var imageToDestroy = null;
				if (imagesToScrollRescale[i].isDestroyedOnEnd) {
					game.removeChild(imagesToScrollRescale[i].image);
					imageToDestroy = imagesToScrollRescale[i].image;
				}
				//On retire l'image du tableau si le nombre de ticks est nul				
				imagesToScrollRescale.splice(i, 1);
				if (imageToDestroy) {
					imageToDestroy.destroy();
				}
			} else {
				var x = imagesToScrollRescale[i].image.x;
				var y = imagesToScrollRescale[i].image.y;
				var scale = imagesToScrollRescale[i].image.scale.x;
				var xToReach = imagesToScrollRescale[i].xToReach;
				var yToReach = imagesToScrollRescale[i].yToReach;
				var scaleToReach = imagesToScrollRescale[i].scaleToReach;
				var nbTicksLeft = imagesToScrollRescale[i].nbTicksLeft;
				var dx = (xToReach - x) / nbTicksLeft;
				var dy = (yToReach - y) / nbTicksLeft;
				var dscale = (scaleToReach - scale) / nbTicksLeft;
				imagesToScrollRescale[i].image.x += dx;
				imagesToScrollRescale[i].image.y += dy;
				imagesToScrollRescale[i].image.scale.x += dscale;
				imagesToScrollRescale[i].image.scale.y += dscale;
				imagesToScrollRescale[i].nbTicksLeft -= 1;
			}
		}
	}
} //fin scrollRescaleImages
//Fonction longuestWord : permet de trouver le mot le plus long dans une liste de mots et de donner sa longueur
function longuestWord(liste) {
	var longuest = '';
	for (var i = 0; i < liste.length; i++) {
		if (liste[i].length > longuest.length) {
			longuest = liste[i];
		}
	}
	return longuest.length;
} //Fin de la fonction longuestWord
/**** 
* Main loop
****/ 
game.update = function () {
	//scoreTest = wordsMainList.length;
	updateScoreTest(scoreTest);
	//Choix du thème
	if (!isThemaSelected) {
		return;
	}
	//Mise à jour score
	if (isScoreUpdatable) {
		updateScore(score);
		isScoreUpdatable = false;
	}
	//Animation des images
	scrollRescaleImages();
	//Recherche de la lettre cliquée dans la mainGrid et ajout de la lettre à la liste des lettres formant le mot
	for (var i = 0; i < mainGrid.gridLines; i++) {
		for (var j = 0; j < mainGrid.gridColumns; j++) {
			if (mainGrid.cells[i][j].isClicked) {
				var newCell = addCellLetterToWord(mainGrid.cells[i][j].letter);
				if (newCell) {
					newCell.columnFrom = j;
					newCell.lineFrom = i;
				}
				mainGrid.cells[i][j].isClicked = false;
				mainGrid.cells[i][j].setLetter('');
				mainGrid.emptyCells.push(mainGrid.cells[i][j]);
			}
		}
	}
	//Recherche de la lettre cliquée dans la wordGrid et retour de la lettre à la mainGrid
	var indexCellToRemove = -1;
	for (var j = 0; j < wordGrid.gridColumns; j++) {
		if (wordGrid.cells[0][j].isClicked) {
			//Retour de la lettre à la grille principale
			var columnBack = wordGrid.cells[0][j].columnFrom;
			var lineBack = wordGrid.cells[0][j].lineFrom;
			mainGrid.setLetter(columnBack, lineBack, wordGrid.cells[0][j].letter);
			//Retrait de la lettre cliquée du mot
			wordGrid.cells[0][j].setLetter('');
			wordGrid.cells[0][j].isClicked = false;
			indexCellToRemove = j;
		}
	}
	if (indexCellToRemove >= 0) {
		wordGrid.removeCell(indexCellToRemove);
		indexCellToRemove = -1;
	}
	//Affichage ou pas du bouton de validation
	if (validateButton) {
		if (wordGrid.isEmpty()) {
			validateButton.visible = false;
		} else {
			validateButton.visible = true;
		}
	}
	//Affichage ou pas des boutons d'indices
	if (!wordGrid.isEmpty()) {
		clueButtonLetter.visible = false;
	} else {
		clueButtonLetter.visible = true;
	}
	var notEnoughtMoneyForWord = longuestWord(mainGrid.words) * costForWord > score;
	if (notEnoughtMoneyForWord || !wordGrid.isEmpty()) {
		clueButtonWord.visible = false;
	} else {
		clueButtonWord.visible = true;
	}
	var word = wordGrid.firstWord();
	var notEnoughtMoneyForDrop = longuestWord(mainGrid.words) * costForDrop > score;
	if (notEnoughtMoneyForDrop || clueWord == '' && !wordGrid.isEmpty() || word == clueWord && word != '') {
		clueButtonDrop.visible = false;
	} else {
		clueButtonDrop.visible = true;
	}
	if (wordGrid.isEmpty() && clueWord != '') {
		//On réinitialise les parametres de l'indice drop letter
		clueWord = '';
	}
	//Autres actions à effectuer sans urgence
	if (LK.ticks % 10 == 0) {
		//Chargement initiale de la grille principale si nécessaire (vide):
		//mot(s) est choisi au hasard dans la liste principale, 
		//il est mélangé et les lettres sont directement ajoutées à la grille principale avec la fonction addRandomLetter
		if (mainGrid.isEmpty() && !isGameStarted) {
			var wordsToBegin = pickAndShakeWords(1).words;
			for (var i = 0; i < wordsToBegin.length; i++) {
				var isPossibleToAddletter = true;
				for (var j = 0; j < wordsToBegin[i].length && isPossibleToAddletter; j++) {
					isPossibleToAddletter = mainGrid.addRandomLetter(wordsToBegin[i][j]);
				}
				if (isPossibleToAddletter) {
					mainGrid.addWord(wordsToBegin[i]);
				}
			}
			isGameStarted = true;
			isMGRefillrequired = false;
		}
		//Chargement d'un mot mélangé dans la grille principale si demandé (isMGRefillrequired = true) et fin de partie
		if (isMGRefillrequired) {
			if (!putRandomShuffledWordInGrid()) {
				LK.setTimeout(function () {
					LK.showGameOver();
				}, 1000);
			}
			isMGRefillrequired = false;
		}
	}
}; //Fin de la fonction update
//Liste des mots en majuscule
//var animaux = ["ORYCTEROPE", "ALBATROS", "ALLIGATOR", "ALPAGA", "FOURMI", "FOURMILIER", "ANTILOPE", "SINGE", "TATOU", "BABOUIN", "BLAIREAU", "OURS", "CASTOR", "ABEILLE", "SCARABEE", "BISON", "SANGLIER", "BUFFLE", "PAPILLON", "CHAMEAU", "CANARI", "CAPYBARA", "CARIBOU", "CARPE", "CHAT", "CHENILLE", "GUEPARD", "POULET", "CHIMPANZE", "CHINCHILLA", "CRAVE", "PALOURDE", "COBRA", "CAFARD", "MORUE", "CORMORAN", "COYOTE", "CRABE", "GRUE", "CROCODILE", "CORBEAU", "COURLIS", "CERF", "DINOSAURE", "CHIEN", "AIGLEFIN", "DAUPHIN", "ANE", "ECHANDE", "COLOMBE", "LIBELLULE", "CANARD", "DUGONG", "BECASSEAU", "AIGLE", "ECHIDNE", "ANGUILLE", "ELAND", "ELEPHANT", "ELAN", "EMEU", "FAUCON", "FUROT", "PINSON", "POISSON", "FLAMANT", "MOUCHE", "RENARD", "GRENOUILLE", "GAUR", "GAZELLE", "GERBILLE", "GIRAFE", "MOUSTIQUE", "GNU", "CHEVRE", "CHARDONNERET", "OIE", "GORILLE", "AUTOUR", "SAUTERELLE", "GELINOTTE", "GUANACO", "MOUETTE", "HAMSTER", "LIEVRE", "FAUCON", "HERISSON", "HERON", "HARENG", "HIPPOPOTAME", "FRELON", "CHEVAL", "COLIBRI", "HYENE", "BOUC", "IBIS", "CHACAL", "JAGUAR", "GEAI", "MEDUSE", "KANGOUROU", "KOALA", "KOOKABURRA", "KOUROU", "VANNEAU", "ALOUETTE", "LEMURIEN", "LEOPARD", "LION", "LAMA", "HOMARD", "CRIQUET", "LORIS", "POUX", "MENURE", "PIE", "COLVERT", "LAMANTIN", "MANDRILL", "MANTIS", "MARTRE", "SURICATE", "VISON", "TAUPE", "SINGE", "ORIGNAL", "MOUSTIQUE", "SOURIS", "MULET", "NARVAL", "TRITON", "ROSSIGNOL", "PIEUVRE", "OKAPI", "OPOSSUM", "ORYX", "AUTRUCHE", "LOUTRE", "HIBOU", "HUITRE", "PANTHERE", "PERROQUET", "PERDRIX", "PAON", "PELICAN", "PINGOUIN", "FAISAN", "COCHON", "PIGEON", "MARSOUIN", "CAILLE", "QUELEA", "QUETZAL", "LAPIN", "RALE", "BELIER", "RAT", "CORBEAU", "RENNE", "RHINOCEROS", "FREUX", "SALAMANDRE", "SAUMON", "BECASSE", "SARDINE", "SCORPION", "HIPPOCAMPE", "PHOQUE", "REQUIN", "MOUTON", "MUSARAIGNE", "MOUFETTE", "ESCARGOT", "SERPENT", "MOINEAU", "ARAIGNEE", "SPATULE", "CALMAR", "ECUREUIL", "ETOURNEAU", "RAIE", "PUNAISE", "CIGOGNE", "HIRONDELLE", "CYGNE", "TAPIR", "TARSIER", "TERMITE", "TIGRE", "STERNE", "GRIVE", "TIGRE", "CRAPAUD", "TOUCAN", "TRUITE", "DINDON", "TORTUE", "VIPERE", "VOLTURE", "WALLABY", "MORSE", "GUEPE", "BELETTE", "BALEINE", "CHAT SAUVAGE", "LOUP", "WOMBAT", "BECASSE", "PIVOINE", "VER", "ROITELET", "YACK", "ZEBRE"]; ===================================================================
--- original.js
+++ change.js
@@ -438,15 +438,15 @@
 			onClick: onClickMiniBackGround
 		});
 		var oneCell = new GridCell('', 'cell'); // Define oneCell variable
 		var nbWords = mainListsList[i].length;
-		//displayText(name + "(" + nbWords + ")", 'cellWord', nbWords * oneCell.width + oneCell.width / 2, miniBackGrounds[i].height / 2 + 2.5 * oneCell.height);
-		var nameGrid = makeNameGrid(name + "(" + nbWords + ")", 'cellWord');
-		nameGrid.y = miniBackGrounds[i].height / 2 - 2.5 * nameGrid.height;
-		nameGrid.width = miniBackGrounds[i].width - 2 * oneCell.width;
-		nameGrid.height = 2 * miniBackGrounds[i].height;
-		nameGrid.x = -nameGrid.width / 2 + oneCell.width / 2;
-		miniBackGrounds[i].addChild(nameGrid);
+		displayText(name + "(" + nbWords + ")", 'cellWord', nbWords * oneCell.width + oneCell.width / 2, miniBackGrounds[i].height / 2 + 2.5 * oneCell.height);
+		//var nameGrid = makeNameGrid(name + "(" + nbWords + ")", 'cellWord');
+		//nameGrid.y = miniBackGrounds[i].height / 2 - 2.5 * nameGrid.height;
+		//nameGrid.width = miniBackGrounds[i].width - 2 * oneCell.width;
+		//nameGrid.height = 2 * miniBackGrounds[i].height;
+		//nameGrid.x = -nameGrid.width / 2 + oneCell.width / 2;
+		//miniBackGrounds[i].addChild(nameGrid);
 		game.addChild(miniBackGrounds[i]);
 		setHelpButton('ButtonHelp');
 	}
 } //Fin de la fonction displayminiBackGrounds
@@ -584,13 +584,18 @@
 			nameGrid.x = x;
 			nameGrid.y = y + i / 4 * cellHeight * 2 + j / 2 * cellHeight;
 			nameGrid.width /= 2;
 			nameGrid.height /= 2;
+			//if (object instanceof Container) {
+			//scoreTest = "Container valide! ";
 			if (object instanceof Container) {
 				object.addChild(nameGrid);
 			} else {
-				console.error("The provided object is not a valid Container instance.");
+				game.addChild(nameGrid);
 			}
+			//} else {
+			//scoreTest = "Container non valide! ";
+			//game.addChild(nameGrid);
 			textsGrid.push(nameGrid);
 		}
 	}
 	return textsGrid;
@@ -1067,9 +1072,8 @@
 * Main loop
 ****/ 
 game.update = function () {
 	//scoreTest = wordsMainList.length;
-	scoreTest = "Game is started: " + isGameStarted;
 	updateScoreTest(scoreTest);
 	//Choix du thème
 	if (!isThemaSelected) {
 		return;
 An empty cell.
 Drapeau national des USA en fond d'un patchwork des États américains.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Une jeton de scrabble sans lettre.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Un bouton arrondi suggérant une validation mais sans texte écrit dessus.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A round button with a cyan interrogation mark.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A round cyan button with a yellow lamp bulb.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Planetes.
 Remove the white square and the red lines.
 A patchwork of european countries with the european unio flag in back ground.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A yellow coin wher we can see '+10' written on it.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 A red coin wher we can see '-10' written on it... Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Patchwork of heads of plenty animals.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 The periodic table of the elements.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Patchwork de mots sur un fond cyan.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 Patchwork of scene extracted from video games.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.
 It is written "COOL QUIZZ".
 A cyan circle button with a home silhouette in the center. The button means "go back to start window". Avoid white color.. Single Game Texture. In-Game asset. 2d. Blank background. High contrast. No shadows.