需要增加的代码:

在播放音效的地方增加一个变量,用来记录音效是否已经播放过,初始值为false。

在判断是否吃到食物的地方,如果吃到食物且音效没有播放过,则播放音效,并将变量设置为true。

修改后的代码如下:

// 音效是否已经播放过 private boolean isSoundPlayed = false;

// 判断是否吃到食物 if (head.equals(food)) { // 如果音效没有播放过,则播放音效 if (!isSoundPlayed) { Random random = new Random(); int index = random.nextInt(8); String filePath = ""; switch (index) { case 0: filePath = "C:\Users\彭 杨\IdeaProjects\untitled\src\snake\emmmm__(van)_1.WAV"; break; // ...省略其他case } playMusic(filePath); isSoundPlayed = true; // 将变量设置为true } // 更新贪吃蛇和食物 snake.add(0, head); initFood(); // 如果吃到食物,则将 score 的值加上 10 score += 10; } else { snake.add(0, head); snake.remove(snake.size() - 1); isSoundPlayed = false; // 每次移动时将变量设置为false


原文地址: https://www.cveoy.top/t/topic/fL0X 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录