Update a value within a function

Asked

Viewed 739 times

0

I am starting in Python and need help to create the following function:

ESQUERDA = -1
DIREITA = 1
CANHAO = 'A'
EXPLOSAO = '*'

def moveCanhao(direcao, matriz):
''' int, (matriz) -> bool

      Recebe um inteiro com a direção (valores definidos em ESQUERDA e
      DIREITA) para mover o canhão do jogador (caracter definido em CANHAO)
      e a matriz de caracteres do jogo, para mover o canhão nessa direção.
      Ao mover tem que observar se atingiu algum laser de alguma nave (caso
      no qual tem que imprimir um EXPLOSAO no lugar). Nesse caso precisará
      informar que o canhão foi atingido pois a função retorna esse valor.

      Retorna:

      True se canhão do jogador foi atingido (False se não)

      Obs.: o movimento do canhão é ciclíco quando ele se move além dos
      limites laterais da matriz do jogo.'''

The game matrix has 20 rows and 57 columns. The cannon must always be in the last line and at each user iteration (typing left or right) the cannon must be move.

What I’ve already done:

v = False
k = 28
n = k + direcao
matriz[19][n % 57] = CANHAO
if direcao == DIREITA:
    matriz[19][n - 1] = " "
else:
    matriz[19][n + 1] = " "
k += direcao

return v

The function should only return True or False (determined by variable v). The big problem and my question enter the update of variable k: I need k to start from 28 and each time the function is called k update to "k+direction". However, each time the function is called k is updated to 28 and the accumulator at the end of the function becomes useless. An important detail is that it is not allowed to use Imports, libraries or more specific functions. It has to be very rustic. How can I fix this?

1 answer

0


As you’ve noticed, do k = 28 at the start of the function will cause the 28 value to be assigned to k whenever the function is executed. So how to make it not happen? Just don’t do k = 28 within the function.

As this will be your initial value, you have to assign it at the beginning of the program. For example, along with the declaration of your other variables:

ESQUERDA = -1
DIREITA = 1
CANHAO = 'A'
EXPLOSAO = '*'
k = 28

So to modify it within the function, you just have to do global k to tell the program that you are referring to the variable k the overall scope of the program, and does not want to create a new variable k within the local scope of the function:

def moveCanhao(direcao, matriz):
    global k
    v = False
    n = k + direcao
    matriz[19][n % 57] = CANHAO
    if direcao == DIREITA:
        matriz[19][n - 1] = " "
    else:
        matriz[19][n + 1] = " "
    k += direcao

    return v
  • It worked, bro!!!! Thank you! You saved my semester hahah

  • @PYTHON_13 Nothing, I’m happy to help! If the answer solved the problem, be sure to accept it to mark the issue as resolved :)

Browser other questions tagged

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