如何对用户输入进行surpress打印



我想隐藏take_stick = int(input()),这样它就不会打印用户输入,因为它应该在不同的地方打印,但我不知道如何做到。我需要输出如下所示:

Game of sticks
Player 1 enter how many sticks to remove: 2
There are 19 sticks left
Player 2 enter how many sticks to remove: 4
Must remove between 1-3 sticks! 

等等,但现在输出给出了每行之间的输入数字(原因很明显(。这是迄今为止的代码:

def main():
print("Game of sticks")
player_turn = 1
starting_sticks = 21
sticks_left = starting_sticks
while True:
if starting_sticks == 21:
if sticks_left < 1:
print("There are", sticks_left, "sticks left")
take_stick = int(input())
if take_stick < 1 or take_stick > 3:
print("Must remove between 1-3 sticks!")
elif take_stick >= 1 and take_stick <= 3:
sticks_left -= take_stick
if sticks_left == 21:
print("Player", player_turn, "enter how many sticks to remove:", take_stick)
player_turn += 1
if player_turn == 3:
player_turn -= 2
elif sticks_left != 1:
print("Player", player_turn, "enter how many sticks to remove:", take_stick)
player_turn += 1
if player_turn == 3:
player_turn -= 2
print("There are", sticks_left, "sticks left")
if sticks_left <= 0:
print()
print("Player", (player_turn), "lost the game!")
break
main()

如前所述,您可以使用getpass,并将默认提示设置为空字符串。此外,您可以将光标向上移动一行,这样就不会有空行(如果可能的话,在您的终端中(。

示例:

from getpass import getpass
take_stick = int(getpass(prompt=''))

我认为您不需要隐藏任何输入;你只需要重组你的循环来匹配游戏的流程。类似的东西

def main():
print("Game of sticks")
player_turn = 1
sticks_left = 21
while sticks_left > 0:
print("There are", sticks_left, "sticks left")
while True:
take_stick = int(input(f"Player {player_turn} enter how many sticks: ")    
if 1 <= take_stick <= 3:
break
print(f"Must remove between 1-3 sticks!")
sticks_left -= take_stick
player_turn = 2 if player_turn == 1 else 1
print(f"Player {player_turn} lost the game!")
main()

整个游戏只是:

  1. 说明还剩多少棍子
  2. 让当前玩家拿一些棍子
  3. 更新轮到谁了
  4. 重复,直到所有的棍子都掉光为止
  5. 将当前玩家报告为失败者(因为他们没有棍子可拿(

如果我理解正确,我想这就是你想要做的:

def main():
print("Game of sticks")
player_turn = 1
starting_sticks = 21
sticks_left = starting_sticks
while True:
if starting_sticks == 21:
if sticks_left < 1:
print("There are", sticks_left, "sticks left")
take_stick = int(input(f"Player {player_turn} enter how many sticks to remove: "))
if take_stick < 1 or take_stick > 3:
print("Must remove between 1-3 sticks!")
continue
elif take_stick >= 1 and take_stick <= 3:
sticks_left -= take_stick
if sticks_left == 21:
player_turn += 1
if player_turn == 3:
player_turn -= 2
elif sticks_left != 1:
player_turn += 1
if player_turn == 3:
player_turn -= 2
print("There are", sticks_left, "sticks left")
if sticks_left <= 0:
print()
print("Player", (player_turn), "lost the game!")
break
main()

input函数接受一个参数prompt,这是一个表示输入前消息的字符串。这允许用户在行的末尾而不是在行之间输入其编号。因此,你不需要我删除的带有上述字符串的指纹。我还添加了一个continue语句,这样,如果一个玩家拿了太多棍子,就轮到他了。

相关内容

  • 没有找到相关文章

最新更新