es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿Cómo puedo agregar audio aleatorio en el lienzo cada vez que golpeo un objeto?

Soy nuevo en programación. Intenté hacer un juego de serpiente usando canvas. Quiero agregar un audio aleatorio cada vez que golpeo un obstáculo. Cuando agrego un audio, funciona perfectamente bien, pero no puedo hacer lo mismo con dos audios. Intenté hacerlo usando una matriz, etc., pero no funcionó. ¿Cómo puedo solucionarlo?

JAVASCRIPT
“`
const canvas = document.getElementById('oyun');
const ctx = canvas.getContext('2d');

let speed = 7;

let tileCount = 24;
let tileSize = canvas.width / tileCount – 2;
let headX = 12;
let headY = 12;

let appleX = 5;
let appleY = 5;

let audio = document.getElementById("sesefekt");

let xVelocity = 0;
let yVelocity = 0;

function drawGame(){
changeSnakePosition();
checkAppleCollision();
clearScreen();
drawApple();
drawSnake();
setTimeout(drawGame, 1000 / speed);
}

function clearScreen(){
ctx.fillStyle = '#a40af7';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}

function drawSnake() {
ctx.fillStyle = 'purple';
ctx.fillRect(headX * tileCount, headY * tileCount, tileSize,tileSize);
}

function changeSnakePosition() {
headX = headX + xVelocity;
headY = headY + yVelocity;
}

function drawApple() {
ctx.fillStyle = "plum";
ctx.fillRect(appleX * tileCount, appleY * tileCount, tileSize, tileSize);
}

function checkAppleCollision() {
if(appleX == headX && appleY == headY){
appleX = Math.floor(Math.random() * tileCount);
appleY = Math.floor(Math.random() * tileCount);
audio.play();<br>
}
}

//hareket etme fonksiyonları
document.body.addEventListener('keydown', keyDown);

function keyDown(event) {
//yukarı
if (event.keyCode == 38){
if(yVelocity == 1)
return;
yVelocity = -1;
xVelocity = 0;
}
//aşağı
if (event.keyCode == 40){
if(yVelocity == -1)
return;
yVelocity = 1;
xVelocity = 0;
}
//sağ
if (event.keyCode == 39){
if(xVelocity == -1)
return;
yVelocity = 0;
xVelocity = 1;
}
//sol
if (event.keyCode == 37){
if(xVelocity == +1)
return;
yVelocity = 0;
xVelocity = -1;
}
}

drawGame();
<code>
HTML
</code>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SNAKE YILANNNNNN</title>
<style>
body{
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: black;<br>
}
canvas{
box-shadow: darkmagenta 20px 10px 50px;
}
</style>
</head>
<body>
<audio id="sesefekt">
<source src="bruh.mp3" type="audio/mp3">
<source src="a.mp3" type="audio/mp3">
</audio>

<pre><code><h1 style="color: blueviolet; text-shadow: lightblue 20px 10px 50px;">YILAN OYUNU AMA BİR DEĞİŞİK</h1>

<canvas id="oyun" width="576" height="576"></canvas>

<script src="index.js"></script>
</code></pre>

</body>
</html>
“`

Tags:  , , ,

Answer

  1. Avatar for davy.ai

    Para agregar múltiples audios aleatorios al golpear un obstáculo en un juego de serpiente con canvas, puedes seguir los siguientes pasos:

    1. Crea un array para almacenar todas las fuentes de audio:
    let audioSources = [
      "bruh.mp3",
      "a.mp3",
      // agregar más fuentes de audio aquí
    ];
    
    1. Crea una función para reproducir un audio aleatorio del array:
    function playRandomAudio() {
      let randomAudioIndex = Math.floor(Math.random() * audioSources.length);
      let audio = new Audio(audioSources[randomAudioIndex]);
      audio.play();
    }
    
    1. Actualiza la función checkAppleCollision() para llamar a la función playRandomAudio() en lugar de reproducir el audio predefinido:
    function checkAppleCollision() {
      if (appleX == headX && appleY == headY) {
        appleX = Math.floor(Math.random() * tileCount);
        appleY = Math.floor(Math.random() * tileCount);
        playRandomAudio();
      }
    }
    

    Esto reproducirá un audio aleatorio del array audioSources cada vez que la serpiente golpee un obstáculo.

    Nota: Asegúrate de que el array audioSources contenga URL de fuentes de audio válidas y actualiza el HTML en consecuencia si es necesario.

Comments are closed.