Flackern der Früchte gelöscht

This commit is contained in:
2025-05-06 16:35:57 +02:00
parent adbcb178a8
commit 9b56ad321a
3 changed files with 34 additions and 17 deletions

View File

@@ -6,7 +6,6 @@ class Fruit{
constructor(fruitManager, playground, startX, startY, type, index = 0) {
this.fruitManager = fruitManager;
this.playground = playground;
this.index = index;
this.x = startX;
this.y = startY;
@@ -20,7 +19,7 @@ class Fruit{
if(tile === undefined) return;
if(tile?.class === "Snake"){
this.fruitManager.scored(this.index, tile.color);
this.fruitManager.scored(this, tile.color);
return;
}

View File

@@ -26,6 +26,9 @@ class FruitManager{
createFruit(){
const pos = this.randomUnusedTile();
if(pos === null) return;
const type = Math.random() < 0.5 ? "Apfel" : "Blaubeere";
const newFruit = new Fruit(
this,
@@ -36,7 +39,7 @@ class FruitManager{
);
this.fruits.push(newFruit);
this.fruits.forEach((fruit, i) => { fruit.index = i });
newFruit.update();
}
@@ -44,6 +47,8 @@ class FruitManager{
let isUnused = false;
let x = 0;
let y = 0;
let attempts = 0;
const maxAttempts = this.playground.width * this.playground.height;
do{
x = Math.floor(Math.random() * this.playground.height);
@@ -52,22 +57,35 @@ class FruitManager{
const tile = this.playground.getTile(x, y);
if(tile === null) isUnused = true;
} while(!isUnused);
attempts++;
} while(!isUnused && attempts < maxAttempts);
if(!isUnused){
return null;
}
return {x, y};
}
updateFruits(){
this.fruits.forEach(fruit => fruit.update());
const fruitsCopy = [...this.fruits];
fruitsCopy.forEach(fruit => {
if (this.fruits.includes(fruit)) {
fruit.update();
}
});
}
scored(fruitIndex, snakeColor){
scored(fruitToDelete, snakeColor){
const fruitIndexInArray = this.fruits.indexOf(fruitToDelete);
if (fruitIndexInArray === -1) return;
this.fruits.splice(fruitIndexInArray, 1);
this.game.score += 1;
this.game.gameLoop.snakes.forEach(snake => {
if(snake.color == snakeColor) snake.getBigger();
})
this.fruits.splice(fruitIndex, 1);
this.createFruit();
}

View File

@@ -186,16 +186,16 @@ class Snake{
const exsitingtile = this.playground.getTile(tile.x, tile.y);
// TODO: Klammert man das ein Kann man alleine Spielen, da es keine Kolisionserkennung gibt
if(exsitingtile === undefined){
// End Game weil außerhalb des Spielfeldes
await this.game.endGame(`${this.player.username} hat die Wand berührt!`);
return;
}
if(exsitingtile?.class === "Snake"){
// Eng Game weil schon belegt mit anderer oder eigender Schlange
await this.game.endGame(`Es gab eine Kollision!`);
return;
}
// if(exsitingtile === undefined){
// // End Game weil außerhalb des Spielfeldes
// await this.game.endGame(`${this.player.username} hat die Wand berührt!`);
// return;
// }
// if(exsitingtile?.class === "Snake"){
// // Eng Game weil schon belegt mit anderer oder eigender Schlange
// await this.game.endGame(`Es gab eine Kollision!`);
// return;
// }
this.playground.setTile(tile.x, tile.y, tile);
}