在python中玩猜数游戏,直到用户选择退出

时间:2015-01-13 14:56:07

标签: python python-3.x

import random

play_game=input("Do you want to play ? Y/N :")
play_game=play_game.upper()
print(play_game)

while play_game == 'Y':
    #Type of game does the user wish to play
    game_type=input("please select a type:'H' for hard,'M' for medium ,'E' for easy  :")
    game_type=game_type.upper()

    #print(game_type)
    if game_type=='E':
        #generating a random number between 1 and 10
        random_number=random.randint(1,10)
        print(random_number)

        guess_times=0
        #guessing a number
        while guess_times<3:
            user_number=(input("Enter the number \n:"))
            user_number=int(user_number)
            guess_times+=1
            if user_number!=abs(user_number):
                print("the number should be a +ve number")
            else:
                if user_number==random_number:
                    print("Congratulaions,%d is the correct guess and you guessed in %d attempts"%(user_number,guess_times))
                    break
                if user_number<random_number:
                    print("the number,%d is lower than the guessed number"%user_number)
                if user_number>random_number:
                    print("the number,%d is higher than the guessed number"%user_number)
else:
        print("not the valid option")
print("bye")

我在上面创建了一个简单的猜测游戏。它工作正常。但是我想让用户玩游戏,直到用户决定不玩。

我在游戏开始时使用while循环,一旦用户进入游戏,就不会选择退出选项。

我还不想使用函数,因为我是编程新手。

2 个答案:

答案 0 :(得分:1)

您永远不会在循环中更新play_game;你需要在循环结束时再次询问用户:

while play_game == 'Y':
    # your game 

    play_game = input("Do you want to play again? Y/N :").upper()

然后,当循环返回到顶部时,如果用户未在该提示下输入yY,则游戏结束。

答案 1 :(得分:0)

您可以为game_type添加一个选项,.e.g为退出:

game_type=input("please select a type:'H' for hard,'M' for medium ,'E' for easy , Q to quit :")

并改变代码的结尾:

elif game_type == 'Q':
    print("bye")
    break
else:
    print("not the valid option")