почему мой код не проходит мимо «сколько жетонов вы хотите взять»? ним игра питон 3

вот код, и у меня закончились идеи. Я пробовал изменить отступ, но это тоже не сработало. цель игры ним: «игрок ставит 2 стопки блоков, второй игрок выбирает, ходить первым или вторым, каждый по очереди убирает блоки (в данном случае вместо блоков я кладу - ) игроки должны удалите по крайней мере один или не более 3 блоков из любой стопки, в зависимости от того, какой игрок возьмет последний блок, выиграет.

      from math import *
from random import randint
pile1 = randint(1,20)
pile2 = randint(1,20)

player= 1
print("it's,"+str(player ) +' playing')
while pile1+pile2>0 : 
  if pile1>0: 
    print ('pile 1 :'+'-'*pile1) 
  if pile2>0: 
    print('pile 2:'+'-'*pile2)   
  break
which_pile=int(input('On which pile would you like to play ? : '))
while which_pile !=1 and which_pile != 2: 
  which_pile=int(input('On which pile would you like to play ? : '))
tokens=int(input('How many tokens would you like to take ? : '))
if which_pile==1:
  while tokens<1 or tokens>min(3,pile1):
      tokens=int(input('How many tokens would you like to take ? : '))
      pile1-=tokens
else:
   while tokens<1 or tokens>min(3,pile2):
      tokens=int(input('How many tokens would you like to take ? : '))
      pile2-=tokens

1 ответ

В отформатированном виде ваш код не имеет возможности запрашивать плеер 2.

Так и будет

  1. проверить сумму всех плиток> 0 и, если да, вывести стопки
  2. затем он спросит, какую стопку играть
  3. затем он попросит токены удалить и удалить их
  4. затем программа заканчивается.

Вам не хватает внешнего цикла, который меняет игрока и продолжается до тех пор, пока не будет выполнено условие окончания игры (в стопках больше не осталось плиток).

Вам также нужны дополнительные меры безопасности, чтобы избежать ValueErrorесли не введены целые числа и общая очистка, на которую следует обратить внимание . Руководство по стилю для python .

Готовая программа может выглядеть так:

      from math import *
from random import randint
pile1 = randint(1,20)
pile2 = randint(1,20)

player = "1"
while True:
    print(f"\n\nPlayer {player}'s turn:")

    print (f"  pile 1: {'-' * pile1}")
    print (f"  pile 2: {'-' * pile2}\n")

    if pile1 == 0 or pile2 == 0:
        print("  Only one pile left.")
        which_pile = "2" if pile1 == 0  else "1"
    else:
        # use strings to compare, no need to care about ValueErrors by int()
        which_pile = input('  On which pile would you like to play? ')
        while which_pile not in ("1", "2"): 
            which_pile = input('  On which pile would you like to play? ')

    available_tokens = pile1 if which_pile == "1" else pile2

    tokens = input('  How many tokens would you like to take ? ')

    # make sure you do not take more then 3 (or the amount in the pile)
    while tokens not in map(str, range(1, min(4, available_tokens+1))):
        tokens = input('  How many tokens would you like to take ? ')

    # only playe you really need an int - and its ensured above it
    # can be converted to an integer
    tokens = int(tokens)

    if which_pile == "1":
        pile1 -= tokens
    else:
        pile2 -= tokens

    if pile1 + pile2 == 0:
        break # exit while True loop

    # change player
    player = "2" if player == "1" else "1"

print(f"Player {player} wins" )

И возможная игра будет выглядеть так:

      Player 1's turn:
  pile 1: -----
  pile 2: --

  On which pile would you like to play? 1
  How many tokens would you like to take ? 3    

Player 2's turn:
  pile 1: --
  pile 2: --

  On which pile would you like to play? 1
  How many tokens would you like to take ? 2


Player 1's turn:
  pile 1:
  pile 2: --

  Only one pile left.
  How many tokens would you like to take ? 1


Player 2's turn:
  pile 1:
  pile 2: -

  Only one pile left.
  How many tokens would you like to take ? 1
Player 2 wins

Я использую map(int, range(..)) для создания разрешенных строк для повторной проверки ввода.

Я использую тернарные условия для проверок, см. Есть ли в Python тернарный условный оператор?

Другие вопросы по тегам