setup()
setup() runs once when the page loads. It initializes the DOM structure (title, chat box, input field, buttons) and restores Larry's memory from localStorage so previous conversations are never forgotten.
function setup() {
noCanvas();
loadMemory();
const app = select("#app");
app.html("");
createElement("h1", "Larry").parent(app);
chatHistoryDiv = createDiv().parent(app);
chatHistoryDiv.id("chatHistoryDiv");
const row = createDiv().parent(app);
row.addClass("row");
inputField = createInput().parent(row);
inputField.id("inputField");
sendButton = createButton("Send");
sendButton.parent(row);
sendButton.id("sendButton");
sendButton.mousePressed(sendCurrentMessage);
voiceButton = createButton("🎤");
voiceButton.parent(row);
voiceButton.id("voiceButton");
voiceButton.mousePressed(startVoice);
inputField.elt.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
sendCurrentMessage();
}
});
addMessage("bot", "Hello. I am Larry 🤖");
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
createElement("h1", "Larry").parent(app);
Creates the title and attaches input field, chat history, and button elements to the page
loadMemory();
Restores Larry's knowledge base, topic counter, Markov brain, and user name from localStorage
inputField.elt.addEventListener("keydown", (e) => {
Allows sending messages by pressing Enter or clicking the Send button
noCanvas();- Tells p5.js not to create a default canvas—this sketch uses only HTML/DOM elements
loadMemory();- Retrieves Larry's saved knowledge base, topics, Markov chains, and user name from browser storage
const app = select("#app");- Selects the #app div from index.html so we can add chat UI elements to it
chatHistoryDiv = createDiv().parent(app);- Creates the scrollable chat history area where messages will appear
sendButton.mousePressed(sendCurrentMessage);- Connects the Send button to the sendCurrentMessage function so clicking it sends your message
voiceButton.mousePressed(startVoice);- Connects the microphone button to startVoice so you can activate speech recognition
if (e.key === "Enter") {- Detects when the user presses the Enter key in the input field
addMessage("bot", "Hello. I am Larry 🤖");- Displays Larry's greeting when the sketch first loads