Uh oh!
There was an error while loading. Please reload this page.
forked from hellenicdev/codriver
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
Latest commit
202 lines (175 loc) · 6.88 KB
/
Copy pathscript.js
File metadata and controls
202 lines (175 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// Theme Preferences
constuserPreferences=JSON.parse(localStorage.getItem("preferences"))||{theme: "light"};
document.body.className=userPreferences.theme;
functionchangeTheme(){
userPreferences.theme=userPreferences.theme==="light" ? "dark" : "light";
document.body.className=userPreferences.theme;
localStorage.setItem("preferences",JSON.stringify(userPreferences));
}
// DOM Elements
constuserInput=document.getElementById("userInput");
constmessageArea=document.getElementById("messageArea");
constmicStatus=document.getElementById("micStatus");
// Constants
constWEATHER_API_KEY="5b72dabcdd9d4b67a75170510250304";
constNYT_API_KEY="N8j8mb3TSiexCbefuDeT1Ap5MgKPGwmw";
letgameActive=false;
letsecretNumber=null;
// Speech Recognition
constrecognition=new(window.SpeechRecognition||window.webkitSpeechRecognition)();
recognition.lang="en-US";
recognition.interimResults=false;
recognition.addEventListener("start",()=>micStatus.style.display="block");
recognition.addEventListener("end",()=>micStatus.style.display="none");
recognition.addEventListener("result",(event)=>{
userInput.value=event.results[0][0].transcript;
sendMessage();
});
functionstartListening(){
recognition.start();
}
// User presses Enter
userInput.addEventListener("keypress",(event)=>{
if(event.key==="Enter")sendMessage();
});
// Utility Functions
functionspeak(text){
constutterance=newSpeechSynthesisUtterance(text);
window.speechSynthesis.speak(utterance);
}
functionaddAssistantMessage(response){
constassistantContainer=document.createElement("div");
assistantContainer.classList.add("assistant-message-container");
constassistantMessage=document.createElement("p");
assistantMessage.textContent="Codriver: "+response;
assistantMessage.classList.add("assistant-message");
constassistantSpeaker=document.createElement("button");
assistantSpeaker.textContent="🔊";
assistantSpeaker.onclick=()=>speak(response);
assistantContainer.appendChild(assistantMessage);
assistantContainer.appendChild(assistantSpeaker);
messageArea.appendChild(assistantContainer);
}
// External Fetches
asyncfunctionfetchWeather(city){
try{
constresponse=awaitfetch(`http://api.weatherapi.com/v1/current.json?key=${WEATHER_API_KEY}&q=${city}`);
constdata=awaitresponse.json();
return`🌤 Weather in ${data.location.name}: ${data.current.temp_c}°C, ${data.current.condition.text}`;
}catch{
return"Sorry, I couldn't fetch the weather.";
}
}
asyncfunctionfetchNews(){
try{
constresponse=awaitfetch(`https://api.nytimes.com/svc/topstories/v2/home.json?api-key=${NYT_API_KEY}`);
constdata=awaitresponse.json();
returndata.results.slice(0,5).map(article=>`• ${article.title}`).join("\n");
}catch{
return"Sorry, I couldn't fetch the top news.";
}
}
// Random Data Generators
functiongetRandomQuote(){
return[
"The only limit to our realization of tomorrow is our doubts of today.",
"Be the change you wish to see in the world.",
"Life is 10% what happens to us and 90% how we react to it.",
"Keep your face always toward the sunshine—and shadows will fall behind you."
][Math.floor(Math.random()*4)];
}
functiongetRandomFunFact(){
return[
"Honey never spoils!",
"Bananas are berries, but strawberries aren't!",
"Sharks existed before trees.",
"Octopuses have three hearts."
][Math.floor(Math.random()*4)];
}
functiongetRandomJoke(){
return[
"Why don't scientists trust atoms? Because they make up everything!",
"Why did the scarecrow win an award? Because he was outstanding in his field!",
"I told my computer I needed a break, and it said 'No problem, I'll go to sleep.'"
][Math.floor(Math.random()*3)];
}
functiongetRandomRiddle(){
return[
"What has keys but can’t open locks? A piano.",
"What can travel around the world while staying in one spot? A stamp.",
"What gets wetter the more it dries? A towel."
][Math.floor(Math.random()*3)];
}
functiongetCurrentTime(){
constnow=newDate();
consthours=now.getHours();
constminutes=String(now.getMinutes()).padStart(2,"0");
constperiod=hours>=12 ? "PM" : "AM";
constformattedHours=hours%12||12;
return`The current time is ${formattedHours}:${minutes}${period}`;
}
// Main Handler
asyncfunctionsendMessage(){
constinput=userInput.value.trim();
if(!input)return;
constuserMessage=document.createElement("p");
userMessage.textContent="You: "+input;
userMessage.classList.add("user-message");
messageArea.appendChild(userMessage);
if(gameActive){
if(/exitgame/i.test(input)){
gameActive=false;
addAssistantMessage("Game exited. How else can I assist you?");
}elseif(/^\d+$/.test(input)){
constguess=parseInt(input,10);
if(guess===secretNumber){
gameActive=false;
addAssistantMessage("Congratulations! You guessed it right.");
}elseif(guess<secretNumber){
addAssistantMessage("Too low. Try again!");
}else{
addAssistantMessage("Too high. Try again!");
}
}else{
addAssistantMessage("We're in a game! Please enter a number or type 'exit game'.");
}
userInput.value="";
return;
}
letresponse="";
if(/hello|hi|hey|greetings/i.test(input)){
response="Hello! How can I assist you today?";
}elseif(/quote/i.test(input)){
response=getRandomQuote();
}elseif(/weather/i.test(input)){
constcity=input.split(" ").pop();
response=awaitfetchWeather(city);
}elseif(/news/i.test(input)){
response=awaitfetchNews();
}elseif(/funfact/i.test(input)){
response=getRandomFunFact();
}elseif(/joke/i.test(input)){
response=getRandomJoke();
}elseif(/riddle/i.test(input)){
response=getRandomRiddle();
}elseif(/time/i.test(input)){
response=getCurrentTime();
}elseif(/game/i.test(input)){
gameActive=true;
secretNumber=Math.floor(Math.random()*10)+1;
response="Let's play a game! I'm thinking of a number between 1 and 10. What's your guess?";
}elseif(/calculate|what'?s|whatis|^[0-9+\-*/().\s]+$/i.test(input)){
try{
constexpression=input.replace(/[^0-9+\-*/().]/g,"");
constresult=Function("'use strict'; return ("+expression+")")();
response=`The result is ${result}`;
}catch{
response="I couldn't calculate that. Please check your expression.";
}
}else{
response="Sorry, I didn't understand that.";
}
addAssistantMessage(response);
userInput.value="";
messageArea.scrollTop=messageArea.scrollHeight;
}