T
Selecting the type of gameFirst, we will solve the problem of knowing which type of game that will run: partida or campeonato.
Your logic works very well on this part, so let's keep it.tipo_jogo = 0
Enquanto não for uma opção válida:
while tipo_jogo == 0:
# Menu de opções:
print("Bem-vindo ao jogo do NIM! Escolha:")
print(" ")
print("1 - Para jogar uma partida isolada")
print("2 - Para jogar um campeonato")
# Solicita a opção ao usuário:
tipo_jogo = int(input("Sua opção: "))
print(" ")
# Decide o tipo de jogo:
if tipo_jogo == 1:
print("Voce escolheu partida isolada!")
partida()
break
elif tipo_jogo == 2:
print("Voce escolheu um campeonato!")
campeonato()
break
else:
print("Opção inválida!")
tipo_jogo = 0
The structure with the while is basically to repeat while the user does not enter a valid option. When it is 1, the function partida It's called. When it is 2, the function campeonato It's called.Function partidaNow let's set the function partida. As requested, the function has no parameters and must request the user the values of n and m, starting the game after that.def partida():
print(" ")
# Solicita ao usuário os valores de n e m:
n = int(input("Quantas peças? "))
m = int(input("Limite de peças por jogada? "))
# Define uma variável para controlar a vez do computador:
is_computer_turn = True
# Decide quem iniciará o jogo:
if n % (m+1) == 0: is_computer_turn = False
# Execute enquanto houver peças no jogo:
while n > 0:
if is_computer_turn:
jogada = computador_escolhe_jogada(n, m)
is_computer_turn = False
print("Computador retirou {} peças.".format(jogada))
else:
jogada = usuario_escolhe_jogada(n, m)
is_computer_turn = True
print("Você retirou {} peças.".format(jogada))
# Retira as peças do jogo:
n = n - jogada
# Mostra o estado atual do jogo:
print("Restam apenas {} peças em jogo.\n".format(n))
# Fim de jogo, verifica quem ganhou:
if is_computer_turn:
print("Você ganhou!")
return 1
else:
print("O computador ganhou!")
return 0
Her logic is very simple and self-explanatory by code comments. User's values are requested n and m. Check who will start: if n for multiple m+, then the user starts, so the variable is_computer_turn becomes false. Runs a while while there are pieces in the game, that is, n > 0. Verifies, through the variable is_computer_turn, whose turn is and calls the respective function, returning the amount of pieces that were taken. It is disconnected from the total value of parts, n = n - jogada and back to the beginning of loop. When n = 0, the loop, giving the game as finished. If it ended instead of the computer, it means the user took the last piece and won, otherwise it was the computer that took the last piece, winning the game.Function usuario_escolhe_jogadaThe simplest function of the game. Requests the user the number of parts he wants to remove. If it is a valid number, that is, greater than 0, smaller or equal m, maximum number of parts per round, and smaller or equal to n, current number of pieces in the game. While the number is not valid, continue requesting.def usuario_escolhe_jogada(n, m):
# Vez do usuário:
print("Sua vez!\n")
# Define o número de peças do usuário:
jogada = 0
# Enquanto o número não for válido
while jogada == 0:
# Solicita ao usuário quantas peças irá tirar:
jogada = int(input("Quantas peças irá tirar? "))
# Condições: jogada < n, jogada < m, jogada > 0
if jogada > n or jogada < 1 or jogada > m:
# Valor inválido, continue solicitando ao usuário:
jogada = 0
# Número de peças válido, então retorne-o:
return jogada
Function computador_escolhe_jogadaThe idea is always to make the computer win. So the first condition we have is: the computer can remove all parts (n < m)? If so, return the value n, that is, all the remaining pieces of the game. Otherwise, the computer will always seek to maintain the number of parts being multiple m+, so that the user cannot win. This condition is made by calculating the rest of the division n by m+. It will always be a value between 0 and mincluding. If it is greater than 0, then it will be the number of pieces that the computer needs to take so that n become multiple m+. If it is 0, there is no way to leave a multiple, then remove as much as you give, m.def computador_escolhe_jogada(n, m):
# Vez do computador:
print("Vez do computador!")
# Pode retirar todas as peças?
if n <= m:
# Retira todas as peças e ganha o jogo:
return n
else:
# Verifica se é possível deixar uma quantia múltipla de m+1:
quantia = n % (m+1)
if quantia > 0:
return quantia
# Não é, então tire m peças:
return m
Function campeonatoThe championship function will only run three times the function partida and account for the score:def campeonato():
# Pontuações:
usuario = 0
computador = 0
# Executa 3 vezes:
for _ in range(3):
# Executa a partida:
vencedor = partida()
# Verifica o resultado, somando a pontuação:
if vencedor == 1:
# Usuário venceu:
usuario = usuario + 1
else:
# Computador venceu:
computador = computador + 1
# Exibe o placar final:
print("Placar final: Você {} x {} Computador".format(usuario, computador))
See the full code in https://ideone.com/GfaZyF , also in https://repl.it/FjxW/0 or even https://gist.github.com/acwoss/6b2993f727db4afd9f0c6bedccc84709 .