我正在写一个2人猜数游戏的Python代码。玩家1尝试猜测,如果他们猜错了,程序应该转到玩家2。如果玩家2猜错了,程序应该返回到玩家1。我使用的是我在堆栈溢出中找到的“主动、被动”代码,它在从玩家1转到玩家2时起作用,但如果玩家2猜错了,我就不能回到玩家1。
如果他们真的做对了,代码也不会说出编程的句子。它只是移动到Player 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" 发布于 2021-04-09 18:10:19
你可以使用一个函数,这将大大简化你的代码。
值得一提的是,在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)https://stackoverflow.com/questions/67019006
复制相似问题