玩家 1 切换到玩家 2。如何从玩家 2 切换回玩家 1?这是一个2人猜数字游戏

时间:2021-04-09 09:59:20

标签: python

我正在为 2 人猜数字游戏编写 Python 代码。玩家 1 尝试猜测,如果他们猜错了,程序应该转到玩家 2。如果玩家 2 猜错了,程序应该返回给玩家 1。我正在使用我发现的“主动、被动”代码这里是堆栈溢出,它在从玩家 1 到玩家 2 时有效,但如果玩家 2 猜错了,我就无法回到玩家 1。

如果他们真的做对了,代码也不会说出程序化的句子。它只是移动到玩家 2,或者什么都不打印。

import random
answer= random.randint(1,100)
print('The bingo answer is', answer, '.', 'This will not be shown to the user.')

upperLimit=100
lowerLimit=1
guessingPlayer= ""

active, passive = "1", "2"
while guessingPlayer== "1":
    print('~ ', lowerLimit, 'to ',upperLimit, '~')
    guess = input('Player 1:')
    if int(guess) == answer:
      print("Bingo! Player 1 wins!")
      break
  
else:
    guess= input('Player 1:')
    if int(guess) < answer:
      print('Wrong!')
      lowerLimit=guess
      print('~', lowerLimit, 'to', upperLimit, '~')
    if int(guess)>answer:
      print('Wrong!')
      upperLimit=guess
      print('~', lowerLimit, 'to', upperLimit, '~')
      passive, active= "1", "2"

while guessingPlayer== "2":
  guess = input('Player 2:')
  if int(guess) ==answer:
    print("Bingo! Player 2 wins!")
    break

else:
  guess= input('Player 2:')
  if int(guess)<answer:
    print('Wrong!')
    lowerLimit=guess
    print('~', lowerLimit, 'to', upperLimit, '~')
  if int(guess)>answer:
    print('Wrong!')
    upperLimit=guess
    print('~', lowerLimit, 'to', upperLimit, '~')
    active, passive= "1", "2" 

1 个答案:

答案 0 :(得分:0)

您可以使用一个函数,这将大大简化您的代码。

需要注意的是,Python 中的变量命名约定不是驼峰式大小写 (myVariable),而是使用下划线 (my_variable)。

import random

answer = random.randint(1, 100)
print('The bingo answer is', answer, '.', 'This will not be shown to the user.')


def ask_player(player_number, lower_bound_, upper_bound_):
    """ asks the player, returns True if the guess is correct, False o.w. """
    print('~ ', lower_bound_, 'to ', upper_bound_, '~')
    current_guess = input('Player %s:' % player_number)
    if int(current_guess) == answer:
        print("Bingo! Player %s wins!" % player_number)
        return True
    return False


if __name__ == "__main__":
    upper_limit = 100
    lower_limit = 1
    guessing_player = ""

    active, passive = "2", "1"
    playing = True
    while playing:
        active, passive = passive, active  # switch roles
        playing = not ask_player(active, lower_limit, upper_limit)
相关问题