Skip to content

Commit

Permalink
updates with backend
Browse files Browse the repository at this point in the history
  • Loading branch information
emrebilge committed Sep 18, 2023
1 parent f55affd commit 3692215
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 8 deletions.
55 changes: 47 additions & 8 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,23 @@ const app = express();
const PORT = 5551;

app.use(cors());
app.use(express.json());

const baseURL = 'https://random-word-api.herokuapp.com/word';

let score = 0;
let guesses = 0;
let correct = 0;
let words = [];
let currentWord = '';
let correctWords = [];

// Function to fetch a random word from the API
async function fetchRandomWord() {
try {
const response = await axios.get(`${baseURL}`);
console.log(response.data);
currentWord = response.data;
words.push(response.data);
return response.data; // Extract the first word from the API response array
} catch (error) {
throw error; // Handle errors as needed
Expand All @@ -32,11 +36,11 @@ function scrambleWord(word) {
word = word[0];
const shuffledWord = word.split('').sort(() => Math.random() - 0.5).join('');
return shuffledWord;
}
}


app.get('/', (req, res) => {
res.send('Hello, World!');
// send the score endpoint
app.get('/score', (req, res) => {
res.json({ score });
});

app.get('/get_word', async (req, res) => {
Expand All @@ -55,17 +59,52 @@ app.get('/score', (req, res) => {
res.send(`${score}`);
});

// Increment or decrement the score based on the query parameter
// Endpoint to update the score
app.patch('/score', (req, res) => {
const val = parseInt(req.query.val);
if (!isNaN(val)) {

if (!isNaN(val)) { // check if val is a valid number
score += val;
res.status(200).json({ score, guessedWords });
res.status(200).json({ score });
} else {
res.status(400).json({ message: 'Invalid score value' });
}
});

// Endpoint to validate the data.
app.post('/validate', (req, res) => {
const userGuess = req.body.guess;
guesses += 1;
if(userGuess.toLowerCase() === currentWord.toLowerCase()) {
score += 10;
correct += 1;
correctWords.push(currentWord);
res.status(200).json({ score });
}else{
res.status(400).json({ message: 'Incorrect guess. Try again.', correctWord });
}
});

app.get('/correct_words', (req, res) => {
res.send({ correctWords });
});

// end point to reset the game after the game is over
app.post('/reset_game', (req, res) => {
score = 0;
correct = 0;
guesses = 0;
correctWords = [];
res.json({ message: 'Game reset successfully' });
});

// retrieve the accuracy
app.get('/accuracy', (req, res) => {
const accuracy = (correct / guesses) * 100;
res.send({ accuracy });
});


app.listen(PORT, () => {
console.log(`Backend is running on http://localhost:${PORT}`);
});
Empty file.
Empty file.

0 comments on commit 3692215

Please sign in to comment.