I made a game in javascript, but I wanted to know how to add Pause and start by pressing only one key

Asked

Viewed 58 times

-1

I made a game in javascript, but I wanted to know how to add Pause and start by pressing only one key. Example if you press the P key pause the game, and if you press the S key the game starts from where it left off. can anyone help ? the code is this


const audio = {
    die: new Audio('audio/die.mp3'),
}


function novoElemento(tagName, className) {
    const elem = document.createElement(tagName)
    elem.className = className
    return elem
}

function Barreira(reversa = false) {
    this.elemento = novoElemento('div', 'barreira')

    const borda = novoElemento('div', 'borda')
    const corpo = novoElemento('div', 'corpo')
    this.elemento.appendChild(reversa ? corpo : borda)
    this.elemento.appendChild(reversa ? borda : corpo)

    this.setAltura = altura => corpo.style.height = `${altura}px`
}

function ParDeBarreiras(altura, abertura, x) {
    this.elemento = novoElemento('div', 'par-de-barreiras')

    this.superior = new Barreira(true)
    this.inferior = new Barreira(false)

    this.elemento.appendChild(this.superior.elemento)
    this.elemento.appendChild(this.inferior.elemento)

    this.sortearAbertura = () => {
        const alturaSuperior = Math.random() * (altura - abertura)
        const alturaInferior = altura - abertura - alturaSuperior
        this.superior.setAltura(alturaSuperior)
        this.inferior.setAltura(alturaInferior)
    }
   
    this.getX = () => parseInt(this.elemento.style.left.split('px')[0])
    this.setX = x => this.elemento.style.left = `${x}px`
    this.getLargura = () => this.elemento.clientWidth

    this.sortearAbertura()
    this.setX(x)
}

function Barreiras(altura, largura, abertura, espaco, notificarPonto) {
    this.pares = [
        new ParDeBarreiras(altura, abertura, largura),
        new ParDeBarreiras(altura, abertura, largura + espaco),
        new ParDeBarreiras(altura, abertura, largura + espaco * 2),
        new ParDeBarreiras(altura, abertura, largura + espaco * 3)

    ]

    const deslocamento = 3
    this.animar = () => {
        this.pares.forEach(par => {
            par.setX(par.getX() - deslocamento)

            if (par.getX() < -par.getLargura()) {
                par.setX(par.getX() + espaco * this.pares.length)
                par.sortearAbertura()
            }

            const meio = largura / 2
            const cruzouOMeio = par.getX() + deslocamento >= meio 
                && par.getX() < meio
            if(cruzouOMeio) notificarPonto()    
        })
    }
}


function Passaro(alturaJogo) {
    let voando = false

    this.elemento = novoElemento('img', 'passaro')
    this.elemento.src = 'imgs/passaro.png'

    this.getY = () => parseInt(this.elemento.style.bottom.split('px')[0])
    this.setY = y => this.elemento.style.bottom = `${y}px`
        
    document.addEventListener("keydown", Passaro => {
    if (Passaro.keyCode === 38)
        voando = true
    })
    
    document.addEventListener("keyup", Passaro => {
        if (Passaro.keyCode === 38)
             voando = false
        })

    this.animar = () => {
        const novoY = this.getY() + (voando ? 7 : -5)
        const alturaMaxima = alturaJogo - this.elemento.clientHeight
        
        if (novoY <= 0) {
            this.setY(0)
        } else if (novoY >= alturaMaxima) {
            this.setY(alturaMaxima)
        } else {
            this.setY(novoY)
        }
    }

    this.setY(alturaJogo / 2)
}

function Progresso() {
    this.elemento = novoElemento('span', 'progresso')
    this.atualizarPontos = pontos => {
        this.elemento.innerHTML = pontos
    }

    this.atualizarPontos(0)
}

function estaoSobrepostos(elementoA, elementoB) {
    const a = elementoA.getBoundingClientRect()
    const b = elementoB.getBoundingClientRect()

    const horizontal = a.left + a.width >= b.left
        && b.left + b.width >= a.left
    const vertical = a.top + a.height >= b.top
        && b.top + b.height >= a.top
    return horizontal && vertical       
}

function colidiu(passaro, barreiras) {
    let colidiu = false
    barreiras.pares.forEach(parDeBarreiras => {
        if (!colidiu) {
            const superior = parDeBarreiras.superior.elemento
            const inferior = parDeBarreiras.inferior.elemento
            colidiu = estaoSobrepostos(passaro.elemento, superior)
                || estaoSobrepostos(passaro.elemento, inferior)
                
        }
    })
    return colidiu &&  audio.die.play()



}


class FlappyBird {
    constructor() {
    let pontos = 0

    const areaDoJogo = document.querySelector('[wm-flappy]')
    const altura = areaDoJogo.clientHeight
    const largura = areaDoJogo.clientWidth

    const progresso = new Progresso()
    const barreiras = new Barreiras(altura, largura, 200, 400,
        () => progresso.atualizarPontos(++pontos))
    const passaro = new Passaro(altura)
    
    areaDoJogo.appendChild(progresso.elemento)
    areaDoJogo.appendChild(passaro.elemento)
    barreiras.pares.forEach(par => areaDoJogo.appendChild(par.elemento))

    this.start = () => {
        const temporizador = setInterval(() => {
            barreiras.animar()
            passaro.animar()
           
            if (colidiu(passaro, barreiras)) {
                clearInterval(temporizador)
                 
               

            }
        },20)

         }
    
    }
}

new FlappyBird().start()

2 answers

1

Good afternoon Anderson, all right?

For your problem first of all you need to find the key code you will press, can use this site to find this:

Key Code Info

After that it is necessary to place a listener in your game using the following syntax: Key code p = 80 Key code s = 83

window.onkeyup = function(e) {
    let keyCode = e.keyCode ? e.keyCode : e.which;

    if ( keyCode == 80 ) {
        // Função para parar o jogo
    }

    if ( keyCode == 83 ) {
        // Função para iniciar o jogo
    }
}

After that you can implement the way you want, to save the game and continue from the time it was saved.

  • Hello Lavarda, thanks for the help , but I also wanted to know what code I use to pause the game, would it be something with Setinterval() or Clearinterval() or not? you would know ?

-1

All right, let’s go...

Something I didn’t notice in your code was the establishment of the engine to "run" the game.

As this involves a procedure that needs to be repeated several times, it is important set a function that keeps updating the data to x frames/s. Basically this function needs to be running constantly to calculate and update game information.

-> Whenever you talk about "programming," it’s important to think that what you’re doing is program a computer to run a series of commands, then it is necessary to imagine everything in the head as DICE to be processed.

Seen that, your layer responsible for render or draw is just displaying processes on the screen at each x frames, with different data.

So, I recommend that you read the pages in Devdocs with the documentation of the methods setInterval() and clearInterval().

So the logic I suggest to use is:

1. Preparing an event calling a game processing function;

2. At the same time as calling the processing function, call a render;

3. Define variables with execution intervals for both functions in x frames/s (frames per second).

With this logic, when you want to pause or continue the game, just add or remove the interval to the variable.

Example:


var frame_rate = 10
var game_proces;

function start_game(){ // Função que chama o processamento, atualização, loop do jogo, como quiser nomear.

game_proces = setInterval(run, frame_rate); // Insere o intervalo na variável.
game_proces; // Chama o conteúdo da variável, no caso uma função.
}

function run(){
// Seu processamento de dados, informações a serem checadas sempre, etc.
}


This is the basic structure, in the architecture model that I recommend, but it is always better that you establish according to your own taste. ;D

OBS.: To remove the execution interval of the process, use clearInterval() in the variable.

clearInterval(game_proces);

That’s it, basically, I hope I’ve given you a good enlightenment on your way, success!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.