Code viewer for World: Practical
// Adriana Rincon & Tara Sarli
// "Hello World" to call the CHATGPT API 

//Credits to  "GA (Finnegans Wake)" by "Coding Train" project for the setup function idea
/*
function setup(){
    AB.newDiv("header");
  
  $("#header").css({
      "padding-top": "30", 
      "padding-left": "30",
      "padding-bottom": "10"
      });

  $("#header").html( "<h1> Let us Play Hangman! Tell CHATGPT to 'Pick a random word and lets play hangman' </h1>" +
        "<p><input style='width:25vw;' maxlength='2000' NAME='p' id='p' VALUE=''><button onclick='start();'  class=ab-normbutton >Start</button><p>"
    );
}

   // Credits to "Capture the Hat" by Tuomas Bazzan for the start function idea 

function start()         
{
    console.log("starting")
	var  prompt =  jQuery("input#p").val();
	prompt = prompt.trim();
	if ( prompt != "Pick a random word and let's play hangman" )
	{
	    $("#errordiv").html( "<font color=red> <B> Error: Please try again. </b></font> " );
	    return;
	}
    generateChatResponse(prompt);
    AB.removeSplash();  
}

const apiUrl = 'https://api.openai.com/v1/chat/completions';  // Check the API documentation for the correct endpoint
const apiKey = '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';


//    Code adapted and modified from OpenAI's CHATGPT API documentation
async function generateChatResponse(userInput) {
  try {
      console.log(apiKey);
      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();
    console.log(responseData.choices[0].message.content);
    console.log(responseData);
  } catch (error) {
    console.error('Error making API request:', error.message);
  }
}
generateChatResponse(userInput);
*/
AB.newSplash();                   
AB.splashHtml (
` <h1> Let's Play Hangman! Tell CHATGPT to "Pick a random word and let's play hangman" </h1>  
    <p> 
    <input    style='width:25vw;'    maxlength='2000'   NAME="p"    id="p"       VALUE='' >  
    <button onclick='start();'  class=ab-normbutton >Start</button>
    <p>  
    <div id=errordiv name=errordiv> </div> `
);


const apiUrl = 'https://api.openai.com/v1/chat/completions';  
const apiKey = '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';
let guessedLetters = "";

//    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 },
        { role: 'user', content: "without any additional words or punctuation, tell me the word you picked for hangman" }],
        max_tokens: 150, 
      }),
    });
      console.log(response);

    if (!response.ok) {
      throw new Error(`API request failed with status ${response.status}`);
    }
    const responseData = await response.json();
    console.log(responseData.choices[0].message.content);
    console.log(responseData);
  } catch (error) {
    console.error('Error making API request:', error.message);
  }
}

generateChatResponse(userInput);

// Credits to "Capture the Hat" by Tuomas Bazzan for the start function idea 
function start()         
{
    console.log("starting")
	var  prompt =  jQuery("input#p").val();
	prompt = prompt.trim();
	if ( prompt != "Pick a random word and let's play hangman" )
	{
	    $("#errordiv").html( "<font color=red> <B> Error: Please try again. </b></font> " );
	    return;
	}
	
    let generatedWord = generateChatResponse(prompt); //help - store chzatgpt output variable
    AB.removeSplash();  
}

// handle the user's guess
function handleGuess(letter) {
    guessedLetters += letter;
    if (generatedWord.includes(letter)) {   // check if letter is in word
        console.log(`Congratulations! '${letter}' is in the word.`);
    } else {
        console.log(`Sorry, '${letter}' is not in the word. Try again.`);
    }
    updateGuessedLetters();
}

function updateGuessedLetters() {
  $("#guessedLetter").text(`Guessed Letters: ${guessedLetters}`);
}

//Credits to  "GA (Finnegans Wake)" by "Coding Train" project for the setup function idea
function setup() {
    AB.newDiv("header");
    $("#header").css({
        "padding-top": "30", 
        "padding-left": "30",
        "padding-bottom": "10",
        "border": "1px solid #000", // Add a box border around the entire content
        "width": "fit-content", // Adjust width as needed
        "margin-top": "20px"
    });
    $("#header").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>"  // This is where the guessed letter will be displayed
    );
}

// get a user's guess and call handleGuess
function getUserGuess() {
    var letterguess = jQuery("input#d").val(); //letter user guesses is given to html header d 
    //if the input is a valid and a letter
    if (/^[a-z]$/i.test(letterguess)) {
       handleGuess(letterguess);
    } else {
        $("#errordiv").html("<font color=red> <B> Error: Please enter a valid single letter. </b></font> ");
    }
}


// Assume this function is called after generating the word from ChatGPT API
function startGameWithGeneratedWord(word) {
    // Store the generated word in the global variable
    generatedWord = word.toLowerCase();

    // Call a function to get the user's guess
    getUserGuess();
}

const generatedWordFromAPI = responseData.choices[0].message.content;
startGameWithGeneratedWord(generatedWordFromAPI);