我正在制作一个简单的石头剪刀布游戏。对于每个结果,都应该播放等效的声音(已完成),不仅如此,而且如果前一个声音仍在播放,那么它应该在当前声音开始之前停止,这就是我的问题:我只能做到如果我将保存“新音频”(在本例中为 playSound)的任何变量或对象移动到全局范围,则工作(停止先前的声音)。我已经尝试了我能想到的一切,在摆弄变量、函数等几个小时之后,我最终确定了一个对象(playSound)。我不知道还能做什么,也不知道为什么会这样,我真的很想在不诉诸全局范围的情况下解决这个问题。const determineWinner = (userChoice, computerChoice) => { const playSound = { winSound: new Audio("sound/kids-shouting-yay-sound-effect.mp3"), loseSound: new Audio("sound/aww-sound-effect.mp3"), tieSound: new Audio("sound/roblox-death-sound.mp3"), stopSound() { this.winSound.pause(); this.winSound.currentTime = 0; this.loseSound.pause(); this.loseSound.currentTime = 0; this.tieSound.pause(); this.tieSound.currentTime = 0; }, playerWin() { this.stopSound(); this.winSound.play(); return `Player wins! :D`; }, playerLose() { this.stopSound(); this.loseSound.play(); return `Computer wins! :(`; }, playerTie() { this.stopSound(); this.tieSound.play(); return `It's a tie! :/`; } }; if ((userChoice === computerChoice)) { return playSound.playerTie() } else if ((userChoice === 'rock')) { if ((computerChoice === 'paper')) { return playSound.playerLose(); } else { return playSound.playerWin(); } } else if ((userChoice === 'paper')) { if ((computerChoice === 'scissors')) { return playSound.playerLose(); } else { return playSound.playerWin(); } } else if ((userChoice === 'scissors')) { if ((computerChoice === 'rock')) { return playSound.playerLose(); } else { return playSound.playerWin(); } }};有关代码的更多信息,这里是 github 的 repo:https : //github.com/RenanMDP/rock-paper-scissors
添加回答
举报
0/150
提交
取消