Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 电脑猜谜游戏_Python - Fatal编程技术网

Python 电脑猜谜游戏

Python 电脑猜谜游戏,python,Python,如果你想让电脑猜你的号码,你可以使用如下功能: import random def start(): print "\t\t***-- Please enter Y for Yes and N for No --***" answer = raw_input("\t\t Would you like to play a Guessing Game?: ") if answer == "Y" or answer == "y": game() elif answer == "

如果你想让电脑猜你的号码,你可以使用如下功能:

import random

def start():
    print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t    Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
    game()
elif answer == "N"
or answer == "n":
    end()

def end():
    print("\t\t\t     **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")

def game():

    print "\t\t\t  Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t  Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)

while attempt < 5:
    guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
    print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
    print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
    print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?:  ")
if answer == "Y"
or answer == "y":
    game()
elif answer == "N"
or answer == "n":
    end()

start()

这只是一个又快又脏的例子,但我希望它能给你一个想法。这样,计算机可以得到无限的猜测,但您可以轻松更改while循环以限制其猜测次数。

@Akar这就是我的代码的外观。结果真的很奇怪。我需要让电脑猜一猜,虽然它现在和我一起工作,用户输入数字,我必须猜。但是我想让电脑猜我输入的数字,这是毫无疑问的。单击“编辑”,将您遇到的问题添加到问题中。并修复缩进,因为在Python中正确缩进是至关重要的。如果您希望计算机进行猜测,则需要编写一个全新的程序。没有简单的方法来改变这个程序。
import random

my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []

def make_guess():
    guess = random.randint(1, 20)
    while guess in guesses:
        guess = random.randint(1, 20)
    guesses.append(guess)
    return guess

while True:
    guess = make_guess()
    print(guess)
    if guess == my_number:
        print("The computer wins!")
        break
    else:
        print(guesses)