Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Background sound #172

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions paras/src/App.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,53 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import './App.css';

// Import audio files
import backgroundMusic from './background2.mp3';
import clickXSoundFile from './clickX.wav';
import clickOSoundFile from './clickO.wav';

const initialBoard = Array(9).fill(null);

const App = () => {
const [board, setBoard] = useState(initialBoard);
const [currentPlayer, setCurrentPlayer] = useState('X');
const [winner, setWinner] = useState(null);
const [musicStarted, setMusicStarted] = useState(false); // State to track music

// Create Audio instances
const backgroundAudio = new Audio(backgroundMusic);
const clickXSound = new Audio(clickXSoundFile);
const clickOSound = new Audio(clickOSoundFile);

useEffect(() => {
backgroundAudio.loop = true; // Loop the background music
return () => {
backgroundAudio.pause(); // Stop the music on component unmount
};
}, []);

const startMusic = () => {
if (!musicStarted) {
backgroundAudio.play();
setMusicStarted(true);
}
};

const handleCellClick = (index) => {
startMusic(); // Start music on first interaction
if (board[index] || winner) return;
const newBoard = [...board];
newBoard[index] = currentPlayer;
setBoard(newBoard);
checkWinner(newBoard, currentPlayer);

// Play the respective sound
if (currentPlayer === 'X') {
clickXSound.play();
} else {
clickOSound.play();
}

setCurrentPlayer(currentPlayer === 'X' ? 'O' : 'X');
};

Expand All @@ -37,6 +71,10 @@ const App = () => {
setBoard(initialBoard);
setCurrentPlayer('X');
setWinner(null);
backgroundAudio.currentTime = 0; // Reset music to start
if (musicStarted) {
backgroundAudio.play(); // Restart background music
}
};

const renderCell = (index) => {
Expand Down Expand Up @@ -69,7 +107,7 @@ const App = () => {
</ul>
</div>
<footer className="footer">
<p>&copy; 2023 TIC TAC TOE . All rights reserved.</p>
<p>&copy; 2023 TIC TAC TOE. All rights reserved.</p>
</footer>
</div>
);
Expand Down
Binary file added paras/src/background2.mp3
Binary file not shown.
Binary file added paras/src/clickO.wav
Binary file not shown.
Binary file added paras/src/clickX.wav
Binary file not shown.