Skip to content

Commit 0aaea9f

Browse files
authored
Create calc.js
1 parent 1a8040a commit 0aaea9f

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

calc.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Generate a random math problem
2+
function generateProblem() {
3+
const operators = ['+', '-', '*', '/'];
4+
const operand1 = Math.floor(Math.random() * 100) + 1;
5+
const operand2 = Math.floor(Math.random() * 100) + 1;
6+
const operator = operators[Math.floor(Math.random() * operators.length)];
7+
8+
return `${operand1} ${operator} ${operand2}`;
9+
}
10+
11+
// Check the user's answer
12+
function checkAnswer(problem, answer) {
13+
const result = eval(problem);
14+
return result === answer;
15+
}
16+
17+
// Start the game
18+
function startGame() {
19+
// Generate a new problem
20+
const problem = generateProblem();
21+
22+
// Display the problem to the user
23+
const problemElement = document.querySelector('#problem');
24+
problemElement.textContent = problem;
25+
26+
// Get the user's answer
27+
const answerElement = document.querySelector('#answer');
28+
answerElement.value = '';
29+
30+
// Add an event listener to the answer element to check the user's answer when they press enter
31+
answerElement.addEventListener('keydown', function(event) {
32+
if (event.keyCode === 13) {
33+
// Get the user's answer
34+
const answer = answerElement.value;
35+
36+
// Check the user's answer
37+
const isCorrect = checkAnswer(problem, answer);
38+
39+
// Display the feedback to the user
40+
const feedbackElement = document.querySelector('#feedback');
41+
feedbackElement.textContent = isCorrect ? 'Correct!' : 'Incorrect.';
42+
43+
// If the user's answer is correct, start a new game
44+
if (isCorrect) {
45+
startGame();
46+
}
47+
}
48+
});
49+
}
50+
51+
// Start the game when the page loads
52+
window.addEventListener('load', startGame);

0 commit comments

Comments
 (0)