Update a value within a function

0

I'm 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 on the last line and at each iteration of the user (typing left or right) the cannon must be moved.

What I've 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 is to update the variable k: I need k to start from 28 and every time the function is called k update to "k + direction". However, every 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 more specific imports, libraries or functions. It has to be really rustic. How can I resolve this?

    
asked by anonymous 29.04.2018 / 17:46

1 answer

0

As you have already seen, doing k = 28 at the beginning of the function will cause the value 28 to be assigned to k whenever the function is executed. So how do you not make it happen? Just do not k = 28 inside the function.

Since this is going to 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 change it inside the function, you only have to global k to say to the program that is referring to the variable k of the global scope of the program, and do 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
    
29.04.2018 / 20:57