簡體   English   中英

玩家 1 切換到玩家 2。如何從玩家 2 切換回玩家 1? 這是一個2人數字猜謎游戲

[英]Player 1 switches to Player 2. How do I switch back from Player 2 to Player 1? It's a 2 player number guessing game

我正在為 2 人數字猜謎游戲編寫 Python 代碼。 玩家 1 嘗試猜測,如果他們猜錯了,程序應該轉到玩家 2。如果玩家 2 猜錯了,程序應該返回給玩家 1。我使用的是我發現的“主動、被動”代碼在堆棧溢出時,它在從玩家 1 到玩家 2 時有效,但如果玩家 2 猜錯了,我不能 go 回到玩家 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" 

您可以使用 function,這將大大簡化您的代碼。

作為備注,在 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM