双人号码猜测游戏 - Python

时间:2015-04-11 15:35:21

标签: python

我正在尝试编写一个游戏,玩家One选择一个数字,而玩家二有5个猜测猜测它。如果他设法这样做,他就赢了,如果没有,他就输了,而球员一赢了。

所以我有代码,但是如果例如玩家1选择号码' 3'和玩家二输入数字' 3'在任何一场比赛中,它仍然表示球员一胜。

>>> 
Player One enter you chosen number: 3
Player Two have a guess: 3
Player One wins.
>>> 

这也发生了:

>>> 
Player One enter you chosen number: 5
Player Two wins.

此外,玩家2可以拥有他喜欢的转弯次数,但它应该只有5次。如果他超过了这个数量,玩家一自动获胜。这是我的代码:(我不知道我错了。)

def Game():
    Guess = 0
    NumberOfGuesses = 0
    NumberToGuess = int(input("Player One enter you chosen number: "))
    while NumberToGuess < 1 or NumberToGuess > 10:
        NumberToGuess = int(input("Not a valid choice, please enter another number: "))
    while Guess != NumberToGuess and NumberOfGuesses < 5:
        Guess = int(input("Player Two have a guess: "))
        NumberOfGuesses = NumberOfGuesses + 1
    if Guess == NumberToGuess:
        print("Player One wins.")
    else:
        print("Player Two wins.")


Game()

3 个答案:

答案 0 :(得分:1)

你的if语句是错误的。 而不是

if Guess == NumberToGuess:
    print("Player One wins.")
else:
    print("Player Two wins.")

应该是

if Guess == NumberToGuess:
    print("Player Two wins.")
else:
    print("Player One wins.")

因为如果他猜测玩家1选择的号码(NumberToGuess),则玩家2获胜。 我无法重建你的第二个问题,其中玩家2立即获胜,玩家1进入5.它对我来说很好。

答案 1 :(得分:0)

逻辑错误。如果输入不等于NumberToGuess,则无法打印Player Two wins.

然后你必须循环。然后在循环外检查玩家1是否成功。

while Guess != NumberToGuess and NumberOfGuesses < 5:
    Guess = int(input("Player Two have a guess: "))
    NumberOfGuesses = NumberOfGuesses + 1
    if Guess == NumberToGuess:
        print("Player Two wins.")

if Guess != NumberToGuess:
      print("Player One wins.")

答案 2 :(得分:0)

"""This game generates random number, then players try to guess the number generated"""

import random
#generate number directly
num = random.randrange(1,5)

#initialize global variables
player1 = "Human"
player2 = "Alien"
player = ""
player1PlayCount = 0
player2PlayCount = 0
maxPlayTimes = 3

#game logic
def Game():
    global player1, player2, player, player1PlayCount, player2PlayCount, maxPlayTimes, num
    """enter and assign names to players"""
    player1Name = input('Player1 Enter Your Name: ')
    player2Name = input('Player2 Enter Your Name: ')
    
    player1 = player1Name
    
    player2 = player2Name
    
    player = player1
    
    print(player1, 'turn')
    
    while ((player1PlayCount and player2PlayCount) != maxPlayTimes):
        guessNum = int(input("Guess Number: "))

        if guessNum == num:
            print(player, "won")
            exit()
            
        elif player == player1:
            player1PlayCount +=1
            player = player2
            print(player2, 'turn')
            
        elif player == player2:
            player2PlayCount +=1
            player = player1
            print(player1, 'turn')

        else:
            print("Both ", player1, " and ", player2, " lose")
            exit()
Game()