Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
acharneski committed May 16, 2024
1 parent b2741ec commit 90bee78
Show file tree
Hide file tree
Showing 6 changed files with 74 additions and 113 deletions.
3 changes: 2 additions & 1 deletion math_practice_1/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ <h1>K-1 Math Game</h1>
<p>&copy; 2023 K-1 Math Game</p>
</footer>

<script src="main.js"></script>
<script type="module" src="utils.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>
2 changes: 1 addition & 1 deletion math_practice_1/instructions.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ <h1>How to Play the Game</h1>
</ul>
<button id="back-button" class="button">Back to Game</button>
</div>
<script src="main.js"></script>
<script type="module" src="main.js"></script>
</body>
</html>
77 changes: 40 additions & 37 deletions math_practice_1/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,31 @@ document.addEventListener('DOMContentLoaded', (event) => {

let currentQuestion = {};
let score = 0;
let difficulty = loadSettings().difficulty; // Load difficulty from settings
let difficulty;

try {
difficulty = loadSettings().difficulty || 'easy'; // Load difficulty from settings
} catch (error) {
console.error('Error loading settings:', error);
difficulty = 'easy';
}

// Initialize the game
function initGame() {
document.getElementById('start-button').addEventListener('click', startGame);
document.getElementById('instructions-button').addEventListener('click', showInstructions);
document.getElementById('settings-button').addEventListener('click', showSettings);
const startButton = document.getElementById('start-button');
const instructionsButton = document.getElementById('instructions-button');
const settingsButton = document.getElementById('settings-button');

if (startButton) startButton.addEventListener('click', startGame);
if (instructionsButton) instructionsButton.addEventListener('click', showInstructions);
if (settingsButton) settingsButton.addEventListener('click', showSettings);
}

// Start the game
function startGame() {
score = 0;
document.getElementById('score').innerText = `Score: ${score}`;
const scoreElement = document.getElementById('score');
if (scoreElement) scoreElement.innerText = `Score: ${score}`;
generateQuestion();
}

Expand Down Expand Up @@ -53,26 +65,13 @@ function generateQuestion() {

// Create a math question based on difficulty
function createQuestion(difficulty) {
let num1, num2, correctAnswer, question;
const { min, max } = getRangeByDifficulty(difficulty);
const num1 = getRandomInt(min, max);
const num2 = getRandomInt(min, max);
const correctAnswer = num1 + num2;
const question = `${num1} + ${num2} = ?`;
const choices = [];

if (difficulty === 'easy') {
num1 = getRandomInt(1, 10);
num2 = getRandomInt(1, 10);
correctAnswer = num1 + num2;
question = `${num1} + ${num2} = ?`;
} else if (difficulty === 'medium') {
num1 = getRandomInt(1, 20);
num2 = getRandomInt(1, 20);
correctAnswer = num1 + num2;
question = `${num1} + ${num2} = ?`;
} else if (difficulty === 'hard') {
num1 = getRandomInt(1, 50);
num2 = getRandomInt(1, 50);
correctAnswer = num1 + num2;
question = `${num1} + ${num2} = ?`;
}

choices.push(correctAnswer);
while (choices.length < 4) {
const wrongAnswer = getRandomInt(correctAnswer - 10, correctAnswer + 10);
Expand All @@ -94,13 +93,14 @@ function createQuestion(difficulty) {
// Check the user's answer
function checkAnswer(selectedAnswer) {
const feedbackElement = document.getElementById('feedback-message');
if (selectedAnswer == currentQuestion.correctAnswer) { // Use == for type coercion
if (selectedAnswer === currentQuestion.correctAnswer) {
score++;
feedbackElement.innerText = 'Correct!';
} else {
feedbackElement.innerText = 'Try Again!';
}
document.getElementById('score').innerText = `Score: ${score}`;
const scoreElement = document.getElementById('score');
if (scoreElement) scoreElement.innerText = `Score: ${score}`;
setTimeout(() => {
feedbackElement.innerText = '';
generateQuestion();
Expand All @@ -112,16 +112,19 @@ function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Load settings from local storage
function loadSettings() {
const settings = localStorage.getItem('gameSettings');
if (settings) {
return JSON.parse(settings);
} else {
// Default settings
return {
difficulty: 'easy',
sound: true
};
// Get range of numbers based on difficulty
function getRangeByDifficulty(difficulty) {
switch (difficulty) {
case 'easy':
return { min: 1, max: 10 };
case 'medium':
return { min: 1, max: 20 };
case 'hard':
return { min: 1, max: 50 };
default:
return { min: 1, max: 10 };
}
}
}

// Load settings from utils.js
import { loadSettings } from './utils.js';
7 changes: 4 additions & 3 deletions math_practice_1/settings.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings</title>
<link rel="stylesheet" href="styles.css">
<script src="settings.js" defer></script>
<script type="module" src="settings.js" defer></script>
</head>
<body>
<h1>Settings</h1>
<form id="settings-form" class="settings">
<form id="settings-form">
<label for="difficulty">Difficulty:</label>
<select id="difficulty" name="difficulty">
<div class="settings-container">
Expand All @@ -28,6 +28,7 @@ <h1>Game Settings</h1>
<br>
<button type="submit">Save Settings</button>
</form>
<div id="feedback-message" class="feedback"></div>
<button onclick="window.location.href='index.html'">Back to Game</button>
</div>

Expand All @@ -40,6 +41,6 @@ <h1>Game Settings</h1>
<button id="back-to-game-button" class="button">Back to Game</button>
</div>

<script src="settings.js"></script>
<script type="module" src="settings.js"></script>
</body>
</html>
78 changes: 7 additions & 71 deletions math_practice_1/settings.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,9 @@
// settings.js

// Function to load settings from local storage
function loadSettings() {
const settings = localStorage.getItem('gameSettings');
if (settings) {
return JSON.parse(settings);
} else {
// Default settings
return {
difficulty: 'easy',
sound: true
};
}
}
// Load settings from utils.js
import { loadSettings, saveSettings } from './utils.js';

// Function to save settings to local storage
function saveSettings(settings) {
localStorage.setItem('gameSettings', JSON.stringify(settings));
}

// Function to update the game based on the selected settings
function applySettings(settings) {
Expand All @@ -44,7 +30,11 @@ function handleSettingsFormSubmit(event) {

saveSettings(newSettings);
applySettings(newSettings);
alert('Settings saved successfully!');
const feedbackElement = document.getElementById('feedback-message');
feedbackElement.innerText = 'Settings saved successfully!';
setTimeout(() => {
feedbackElement.innerText = '';
}, 3000);
}

// Function to initialize the settings page
Expand All @@ -58,57 +48,3 @@ function initSettingsPage() {

// Initialize the settings page when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', initSettingsPage);
```
### Explanation
1. **loadSettings()**:
- This function retrieves the game settings from the browser's local storage. If no settings are found, it returns default settings.
2. **saveSettings(settings)**:
- This function saves the provided settings object to local storage.
3. **applySettings(settings)**:
- This function updates the settings UI elements based on the provided settings object. It sets the difficulty level and sound preference.
4. **handleSettingsFormSubmit(event)**:
- This function handles the form submission event for the settings page. It prevents the default form submission behavior, retrieves the selected settings from the form, saves them to local storage, applies the new settings, and displays a success message.
5. **initSettingsPage()**:
- This function initializes the settings page by loading the current settings and applying them to the UI. It also sets up an event listener for the settings form submission.
6. **DOMContentLoaded Event Listener**:
- This ensures that the settings page is initialized only after the DOM is fully loaded.
### HTML Form Example
Here is an example of what the settings form in `settings.html` might look like:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings</title>
<link rel="stylesheet" href="styles.css">
<script src="settings.js" defer></script>
</head>
<body>
<h1>Settings</h1>
<form id="settings-form">
<label for="difficulty">Difficulty:</label>
<select id="difficulty" name="difficulty">
<option value="easy">Easy</option>
<option value="medium">Medium</option>
<option value="hard">Hard</option>
</select>
<br>
<label for="sound">Sound:</label>
<input type="checkbox" id="sound" name="sound">
<br>
<button type="submit">Save Settings</button>
</form>
<button onclick="window.location.href='index.html'">Back to Game</button>
</body>
</html>
20 changes: 20 additions & 0 deletions math_practice_1/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// utils.js

// Function to load settings from local storage
export function loadSettings() {
const settings = localStorage.getItem('gameSettings');
if (settings) {
return JSON.parse(settings);
} else {
// Default settings
return {
difficulty: 'easy',
sound: true
};
}
}

// Function to save settings to local storage
export function saveSettings(settings) {
localStorage.setItem('gameSettings', JSON.stringify(settings));
}

0 comments on commit 90bee78

Please sign in to comment.