Topic de Aureliusback149 :

je sors d'un cours particuliers malaisant (en ligne)

Supprimé
En gros j'ai une élève elle a un devoir de programmation à faire. (c'est pas en France).
Et au bout de 30 min elle me dit qu'elle a pondu le code en utilisant tchatGPT, hors dans l'énoncé du prof c'est marqué qu'il faut pas utiliser tchatGPT....
on a passé une heure à chercher une erreur dans un code pondu par TCHATGPT et on l'a pas trouvé :rire:
C'est tellement irronique car s'il avait fait le code elle-même on aurait pu avancer pas à pas pour comprendre comment utiliser tel fonction etc etc
Donc là fin du cours je suis déjà payé et elle aura certainement 0 pour avoir utiliser tchat GPT :rire:

Le code en question :

let boutons = ["bouton1", "bouton2"];
let vertIndex;
let debutTemps;
let meilleursScore = [];
let reussite = 0;
let tempsTotal = 0;
let partieEnCours = true;

function changerCouleur() {
  vertIndex = Math.floor(Math.random() * 2);
  let autreIndex = 1 - vertIndex;
  document.getElementById(boutons[vertIndex]).className = "vert";
  let autreCouleur = Math.random() < 0.5 ? "rouge" : "gris";
  document.getElementById(boutons[autreIndex]).className = autreCouleur;
  debutTemps = Date.now();
  document.getElementById("message").textContent =
    "Cliquez sur le bouton vert ";
}

function clique(index) {
  if (!partieEnCours) return;

  let id = boutons[index];
  let classe = document.getElementById(id).className;

  if (classe === "vert") {
    let temps = Date.now() - debutTemps;
    reussite++;
    tempsTotal += temps;
    document.getElementById(
      "message"
    ).textContent = `Bravo ! Temps de réaction : ${temps} ms`;

    setTimeout(() => {
      nouvelleCouleurs();
      changerdeCouleur();
    }, 1000);
  } else if (classe === "rouge") {
    document.getElementById("message").textContent =
      "Raté, Vous avez cliqué sur le ROUGE.";
    finDePartie();
  }
}

function nouvelleCouleurs() {
  boutons.forEach((id) => {
    document.getElementById(id).className = "gris";
  });
}

function changerdeCouleur() {
  setTimeout(changerdeCouleur, 1000 + Math.random() * 3000);
}

function finDePartie() {
  let moyenne = reussite > 0 ? Math.round(tempsTotal / reussite) : 0;

  meilleursScores.push({ reussite, moyenne });
  meilleursScores.sort(
    (a, b) => b.reussite - a.reussite || a.moyenne - b.moyenne
  );
  meilleursScores = meilleursScores.slice(0, 3);
  localStorage.setItem("meilleursScores", JSON.stringify(meilleursScores));
  afficherTopScores();
  reussite = 0;
  tempsTotal = 0;
  setTimeout(() => {
    partieEnCours = true;
    nouvelleCouleurs();
    changerCouleur();
  }, 1000);
}

function afficherTopScores() {
  let liste = document.getElementById("topScores");
  liste.innerHTML = "";
  meilleursScores.forEach((item) => {
    let li = document.createElement("li");
    li.textContent = `${item.reussite} réussites - ${item.moyenne} ms`;
    liste.appendChild(li);
  });
}
let scores = localStorage.getItem("meilleursScores");
if (scores) {
  meilleursScores = JSON.parse(scores);
  afficherTopScores();
}
changerCouleur();
Y'a une boucle infinie dans la fonction affichertopscores mais j'ai pas trouvé le bug, des idées ? :)
https://image.noelshack.com/fichiers/2017/39/3/1506524542-ruth-perplexev2.png la sélection du pronte et primordial dans ce genre cas

Bah elle a peut-être juste pas assez de connaissances de base pour pondre un code seule

C'est pas forcément idiot d'utiliser chat gpt, au moins partiellement quand tu débutes

Claude a trouvé ça comme erreur: https://image.noelshack.com/fichiers/2024/44/5/1730449164-mibibigif.gif

Looking at your JavaScript code, I've identified several bugs:

Major Bugs:

Function name typo: changerdeCouleur() should be changerCouleur() (line 43)
Variable name typo: meilleursScore should be meilleursScores (line 53)
Infinite recursion: In changerdeCouleur(), you're calling setTimeout(changerdeCouleur, ...) which will cause infinite loops and potential stack overflow
Logic error: finDePartie() sets partieEnCours = true and restarts the game automatically, but the initial state should probably be false until manually started

Logic Issues:

Game flow: The game restarts automatically after every red click, which might not be the intended behavior
Missing HTML structure: The code references DOM elements (bouton1, bouton2, message, topScores) that aren't defined in the provided code
Timing issue: In clique(), you call both nouvelleCouleurs() and changerdeCouleur(), but changerdeCouleur() doesn't actually change colors - it just sets up a timeout

setTimeout(() => {
nouvelleCouleurs();
changerCouleur(); // correct ici
}, 1000);

https://image.noelshack.com/fichiers/2021/25/5/1624631919-leo-pense-mrc.png mon chat a trouvé une erreur

Le 26 mai 2025 à 19:40:22 :
Claude a trouvé ça comme erreur: https://image.noelshack.com/fichiers/2024/44/5/1730449164-mibibigif.gif

Looking at your JavaScript code, I've identified several bugs:

Major Bugs:

Function name typo: changerdeCouleur() should be changerCouleur() (line 43)
Variable name typo: meilleursScore should be meilleursScores (line 53)
Infinite recursion: In changerdeCouleur(), you're calling setTimeout(changerdeCouleur, ...) which will cause infinite loops and potential stack overflow
Logic error: finDePartie() sets partieEnCours = true and restarts the game automatically, but the initial state should probably be false until manually started

Logic Issues:

Game flow: The game restarts automatically after every red click, which might not be the intended behavior
Missing HTML structure: The code references DOM elements (bouton1, bouton2, message, topScores) that aren't defined in the provided code
Timing issue: In clique(), you call both nouvelleCouleurs() and changerdeCouleur(), but changerdeCouleur() doesn't actually change colors - it just sets up a timeout

Merci du coup je vois ou ça bug mais elle a pas Claude je crois elle a juste tchatgpt 1.0, celui qui donne juste l'heure. https://image.noelshack.com/fichiers/2016/26/1467335935-jesus1.png

Gemini m'a donné ça : Okay, let's debug this!

The primary issue causing the "loop" behavior (or rather, the game stalling after a successful click) is a typo and a misunderstanding of function calls.

You have two functions related to changing colors:

changerCouleur(): This is the main function that actually picks a green button, sets the other, and records debutTemps.

changerdeCouleur(): This function only schedules itself to be called again after a delay. It doesn't actually change any colors.

Inside your clique() function, after a successful click:

setTimeout(() => {
nouvelleCouleurs(); // This makes buttons gray
changerdeCouleur(); // THIS IS THE PROBLEM CALL
}, 1000);

You are calling changerdeCouleur() (with the "de"). This function then just sets a timeout to call itself again, and again, and again. It never calls the changerCouleur() (without "de") function which is responsible for making a new button green. So the buttons turn gray, and then nothing green appears again.

Additionally, there's a typo in your global variable: meilleursScore should be meilleursScores to match its usage.

Here's the corrected code:

let boutons = ["bouton1", "bouton2"];
let vertIndex;
let debutTemps;
let meilleursScores = []; // Corrected: meilleursScore -> meilleursScores
let reussite = 0;
let tempsTotal = 0;
let partieEnCours = true;

// Assume you have HTML elements like this:
// <button id="bouton1" onclick="clique(0)">Bouton 1</button>
// <button id="bouton2" onclick="clique(1)">Bouton 2</button>
// <div id="message"></div>
// <ul id="topScores"></ul>
// <style>
// .vert { background-color: green; }
// .rouge { background-color: red; }
// .gris { background-color: grey; }
// </style>

function changerCouleur() {
if (!partieEnCours) return; // Don't change colors if game ended unexpectedly

vertIndex = Math.floor(Math.random() * 2);
let autreIndex = 1 - vertIndex;
document.getElementById(boutons[vertIndex]).className = "vert";
let autreCouleur = Math.random() < 0.5 ? "rouge" : "gris"; // Keep other button as non-green
document.getElementById(boutons[autreIndex]).className = autreCouleur;
debutTemps = Date.now();
document.getElementById("message").textContent = "Cliquez sur le bouton vert";
}

function clique(index) {
if (!partieEnCours) return;

let id = boutons[index];
let classe = document.getElementById(id).className;

if (classe === "vert") {
let temps = Date.now() - debutTemps;
reussite++;
tempsTotal += temps;
document.getElementById(
"message"
).textContent = `Bravo ! Temps de réaction : ${temps} ms`;

nouvelleCouleurs(); // Set to gray immediately
setTimeout(() => {
// Then, after a delay, show new colors
if (partieEnCours) { // Check again in case finDePartie was called by something else
changerCouleur();
}
}, 1000); // Delay before next green button
} else if (classe === "rouge") {
document.getElementById("message").textContent =
"Raté, Vous avez cliqué sur le ROUGE.";
finDePartie();
} else if (classe === "gris") {
// Optional: Handle clicking on a gray button if it's possible
// For instance, if the other button was gray and not red.
document.getElementById("message").textContent =
"Raté, Vous avez cliqué sur un bouton GRIS.";
finDePartie();
}
}

function nouvelleCouleurs() {
boutons.forEach((id) => {
document.getElementById(id).className = "gris";
});
}

// This function was problematic and redundant.
// The logic to proceed to the next round is handled within clique() or finDePartie()
/*
function changerdeCouleur() {
// This was causing the loop of timeouts without changing colors
setTimeout(changerdeCouleur, 1000 + Math.random() * 3000);
}

  • /

function finDePartie() {
partieEnCours = false; // End the current game immediately
let moyenne = reussite > 0 ? Math.round(tempsTotal / reussite) : 0;

meilleursScores.push({ reussite, moyenne });
meilleursScores.sort(
(a, b) => b.reussite - a.reussite || a.moyenne - b.moyenne
);
meilleursScores = meilleursScores.slice(0, 3);
localStorage.setItem("meilleursScores", JSON.stringify(meilleursScores));
afficherTopScores();

// Prepare for a new game
reussite = 0;
tempsTotal = 0;

// Display end message, then reset for a new game after a delay
// The message about clicking red/gray is already set in clique()
// You might want a specific "Game Over" message here before restart.
// document.getElementById("message").textContent = "Partie terminée! Prêt pour la suivante...";

setTimeout(() => {
partieEnCours = true;
nouvelleCouleurs(); // Set buttons to gray
changerCouleur(); // Start new round by making one green
}, 2000); // Longer delay after game over before starting a new one
}

function afficherTopScores() {
let liste = document.getElementById("topScores");
if (!liste) return; // Guard if element doesn't exist
liste.innerHTML = "";
meilleursScores.forEach((item) => {
let li = document.createElement("li");
li.textContent = `${item.reussite} réussites - ${item.moyenne} ms`;
liste.appendChild(li);
});
}

// Initialisation
window.onload = () => { // Ensure DOM is loaded
let scores = localStorage.getItem("meilleursScores");
if (scores) {
meilleursScores = JSON.parse(scores);
afficherTopScores();
}
nouvelleCouleurs(); // Start with gray buttons
changerCouleur(); // Then make one green to start the game
};
IGNORE_WHEN_COPYING_START
content_copy
download
Use code with caution.
JavaScript
IGNORE_WHEN_COPYING_END

Key Changes and Explanations:

meilleursScore to meilleursScores:

Corrected let meilleursScore = []; to let meilleursScores = []; for consistency.

Removed changerdeCouleur() function:

The function function changerdeCouleur() { setTimeout(changerdeCouleur, ...); } was the source of the problem. It was called after a successful click but only scheduled itself, never calling the actual changerCouleur() to make a new button green.

The logic for advancing to the next set of colors is now correctly handled within the setTimeout of the clique function (for successful clicks) or finDePartie (after a loss).

Corrected Call in clique():

Inside clique(), after a successful click, the setTimeout now directly calls changerCouleur():

setTimeout(() => {
if (partieEnCours) {
changerCouleur();
}
}, 1000);
IGNORE_WHEN_COPYING_START
content_copy
download
Use code with caution.
JavaScript
IGNORE_WHEN_COPYING_END

I also moved nouvelleCouleurs(); to happen before the setTimeout so the buttons turn gray immediately after a correct click, and then the new green button appears after the 1-second delay.

partieEnCours in changerCouleur():

Added a check if (!partieEnCours) return; at the beginning of changerCouleur() as a safeguard.

partieEnCours = false in finDePartie():

Set partieEnCours = false; at the beginning of finDePartie() to immediately stop interactions with the current game round.

Handling Clicks on "Gris":

Added an else if (classe === "gris") in clique() because the non-green button can be gray. Clicking it should also be a "miss".

Initialisation with window.onload:

Wrapped the initial setup code (loading scores, calling changerCouleur()) in window.onload (or document.addEventListener('DOMContentLoaded', ...)). This ensures that the HTML elements (bouton1, bouton2, message, topScores) exist before your script tries to manipulate them. I also added nouvelleCouleurs() before the first changerCouleur() call on startup, so buttons start gray briefly.

With these changes, the game should flow correctly:

A button turns green.

If you click green: message updates, buttons turn gray, then after 1 second a new green button appears.

If you click red (or gray): game over, scores update, then after a 2-second delay, a new game starts.

Données du topic

Auteur
Aureliusback149
Date de création
26 mai 2025 à 19:35:39
Date de suppression
26 mai 2025 à 19:53:00
Supprimé par
Auteur
Nb. messages archivés
9
Nb. messages JVC
15
Voir le topic sur JVC

Afficher uniquement les messages de l'auteur du topic

En ligne sur JvArchive

JvArchive compagnon

Découvrez JvArchive compagnon , l'userscript combattant la censure abusive sur le 18-25 !