Code viewer for World: project (clone by Adriana ...

// Cloned by Adriana Rincon on 2 Dec 2023 from World "project" by Tara 
// Please leave this clone trail here.
 
//by Adriana Rincon and Tara Sarli

AB.newSplash();                   
AB.splashHtml (
`   <h1> ChatGPT, give me a random word. </h1>  
    <p> 
    <button onclick='start();'  class='ab-normbutton custom-button'>Start</button>
    <p>  
    <div id=errordiv name=errordiv> </div> `
);


const apiUrl = 'https://api.openai.com/v1/chat/completions';  // Check the API documentation for the correct endpoint
const apiKey = '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';
let guessedLetters="";
let apiResponseData; 
let allLowerCase;
let underScoreShower = "";
const counter = 0; 


//    Code adapted and modified from OpenAI's CHATGPT API documentation
async function generateChatResponse(userInput) {
  try {
      const response = await fetch(apiUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`,
      },
      body: JSON.stringify({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: userInput }],
           
        max_tokens: 150, 
      }),
    });
      console.log(response);

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }

    const responseData = await response.json();
    apiResponseData = responseData.choices[0].message.content; // Assign the response data to the variable
    allLowerCase = apiResponseData.toLowerCase();
    underScoreShower = makeUnderscore(allLowerCase);
    console.log(underScoreShower);
    console.log(allLowerCase);
  } catch (error) {
    console.error('Error making API request:', error.message);
  }
}



// Credits to "Capture the Hat" by Tuomas Bazzan for the start function idea: https://ancientbrain.com/world.php?world=6053399167
function start()         
{
    console.log("starting")
	var  prompt = "give me a random word";
    generateChatResponse(prompt);
    setupUnderscores();
    AB.removeSplash();  
}

// handle the user's guess
function handleGuess(letter) {
    guessedLetters += letter +",";    
    if (allLowerCase.includes(letter)) {
        console.log(`Congratulations! '${letter}' is in the word.`);
        counter++; 
    } else {
        console.log(`Sorry, '${letter}' is not in the word. Try again.`);
    } 
    updateGuessedLetters();
    if (counter === allLowerCase.length) { //make if stmwnt so that whener number if letters ffrom word =numbner oif guesse3d lettrsz , it kmnows it compltetd the word andprint s the co vgrats 
        console.log(`Congratulations! You guessed the word: '${letter}'`);
        AB.newSplash();                   
        AB.splashHtml (
        ` <h1> Congratulations! You guessed the correct word: '${letter}' !!! </h1>  
            <p> 
            <button onclick='resetGame();'  class=ab-normbutton >Play Again</button>  
            <p>  
            <div id=errordiv name=errordiv> </div> `
        );
        //resetGame();
        
    }
        
}

// updataes the list that displays all the guessed letters
function updateGuessedLetters() {
  $("#guessedLetter").text(`Guessed Letters: ${guessedLetters}`);
}


//Credits to  "GA (Finnegans Wake)" by "Coding Train" project for the setup function idea: https://ancientbrain.com/world.php?world=2904634584
function setup() {
    AB.newDiv("header");
  
    $("#header").css({
        "padding-top": "10", 
        "padding-left": "30",
        "padding-bottom": "10",
        "border": "1px solid #000",
        "width": "fit-content", 
        "margin-top": "0px",
        "color": "#00008B"
        
    });


    $("#header").html(
        "<h1> Let's play Hangman! Pick a letter: &nbsp;  </h1>" +
        "<p><input style='width:25vw;' maxlength='2000' NAME='p' id='d' VALUE=''><button onclick='getUserGuess();' class='ab-normbutton'>Guess</button><p>" +
        "<p id='guessedLetter'></p>"  
    );
}

function setupUnderscores() {
  AB.newDiv("underscores");

  $("#underscores").css({
    "position": "fixed",
    "top": "10",
    "right": "10",
  });
  // take this out if it works 
    $("#underscores").html(
            "<h1> 'Pick a letter' </h1>" +
            "<p><input style='width:25vw;' maxlength='2000'NAME='p' id='d' VALUE=''><button onclick='getUserGuess();' class=ab-normbutton>Guess</button><p>" +
            "<p id='guessedLetter'></p>"  
        );
 $("#underscores").text(underScoreShower);
}

//get a users guess and call handleGuess
function getUserGuess() {
    var letterguess = jQuery("input#d").val(); 
    
    //if the input is valid
     if (/^[a-z]$/i.test(letterguess)) {
        handleGuess(letterguess);

    } else {
         console.log("Invalid input: Please enter a valid single letter.");
        $("#errordiv").html("<font color=red> <B> Error: Please enter a valid single letter. </b></font> ");
    }
}

// function to reset the entire game after it has finished
function resetGame() {
    guessedLetters = "";
    AB.newSplash();                   
    AB.splashHtml (
    ` <h1> ChatGPT, give me a random word. </h1>  
        <p> 
        <button onclick='start();'  class=ab-normbutton >Start</button>
        <p>  
        <div id=errordiv name=errordiv> </div> `
    );
}

function makeUnderscore(word) {
   
    let result = "";
    for (let i =0; i< word.length; i++) {
        result += "_ ";
        
    }
    return result; 
}