//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 >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="";
let apiResponseData;
let allLowerCase; //word that is generated lowercase
let underScoreShower = ""; //storing the underscores for length of word generated
let counter = 0;
let correctGuesses = []; // Array to store correct guesses
// 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; // storing API response in variable
return apiResponseData.toLowerCase();
} 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
async function start()
{
var prompt = "give me a random word";
allLowerCase = await generateChatResponse(prompt);
underScoreShower = makeUnderscore(allLowerCase);
setupUnderscores();
console.log(underScoreShower);
console.log(allLowerCase);
AB.removeSplash();
}
// handle the user's guess
function handleGuess(letter) {
guessedLetters += letter + ","; //adding guessed letters to list
if (allLowerCase.includes(letter)) {
counter++;
correctGuesses.push(letter); //storing correct letter guesses in array
updateUnderscores(letter);//updating underscores
$("#correctLetter").text(`Your letter guess ${letter} is correct`).css({
"position": "absolute",
"top": "0",
"right": "0",
"padding": "10px",
"background-color": "#00FF00",
"border": "1px solid #000",
"border-radius": "5px",
});
} else {
$("#incorrectLetter").text(`Your letter guess ${letter} is incorrect`).css({
"position": "absolute",
"top": "0",
"right": "0",
"padding": "10px",
"background-color": "#00FF00",
"border": "1px solid #000",
"border-radius": "5px",
});
}
updateGuessedLetters();
}
// updates the list that displays all the guessed letters
function updateGuessedLetters() {
$("#guessedLetter").text(`Guessed Letters: ${guessedLetters}`);
}
// Update the underscores display with all correct guesses
function updateUnderscores(letter) {
let updatedUnderscores = "";
for (let i = 0; i < allLowerCase.length; i++) { //updates underscores with correct letter guess when inputted
if (correctGuesses.includes(allLowerCase[i])) {
updatedUnderscores += `${allLowerCase[i]} `;
} else {
updatedUnderscores += "_ ";
}
}
if (!updatedUnderscores.includes('_')) { //checks if all underscores are replaaced; if they are, then user won
console.log(`Congratulations! You guessed the word: '${letter}'`);
AB.newSplash();
AB.splashHtml(
` <h1> Congratulations! You guessed the correct word: '${allLowerCase}'. Game Over. </h1>
<p> Please Refresh The Page to Play Again. </p>
<div id=errordiv name=errordiv> </div> `
);
}
$("#underscores").html(`<p>${updatedUnderscores}</p>`);
}
//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": "30",
"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: </h1>" +
"<p><input style='width:25vw;' maxlength='2000' NAME='p' id='d' VALUE=''><button onclick='getUserGuess();' class=ab-normbutton >Guess</button><p>" +
"<p id='correctLetter'></p>" +
"<p id='incorrectLetter'></p>" +
"<p id='guessedLetter'></p>"
);
}
function setupUnderscores() { //creates underscores
AB.newDiv("underscores");
$("#underscores").css({
"padding-top": "10",
"padding-left": "30",
"padding-bottom": "10",
"width": "fit-content",
"color": "#00008B"
});
$("#underscores").html(`<p>${makeUnderscore(allLowerCase)}</p>`);
}
//get a users guess and calls handleGuess
function getUserGuess() {
var letterguess = jQuery("input#d").val();
//valid input
if (/^[a-z]$/i.test(letterguess)) {
handleGuess(letterguess);
} else { //invalid input
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 makeUnderscore(word) { //function that returns underscore based on wordlength
let result = "";
for (let i =0; i< word.length; i++) {
result += "_ ";
}
return result;
}