简体   繁体   English

如何在 Python 中为猜谜游戏添加范围系统?

[英]How do I add a range system for a guessing game in Python?

this is my first time asking on stack overflow and I'm quite new to programming.这是我第一次询问堆栈溢出,我对编程很陌生。 I just have a question on how to make 'guessing ranges.我只是有一个关于如何制作“猜测范围”的问题。 For example: Num is the number you have to guess例如:Num 是你要猜的数字

if guess > Num + 1 between Num + 5  
 print("That's really close") 

But I don't really know what to code to make it work, or if it's even possible.但我真的不知道要编写什么代码才能使其工作,或者是否有可能。 Basically what I want to do is to make the game print a text when you guess and it's near the Answer at a certain range eg 5基本上我想做的是让游戏在你猜测时打印一个文本,并且它在某个范围内接近答案,例如 5

This is my code so far, and it works as expected:到目前为止,这是我的代码,它按预期工作:

#Author: Sunya Hatch-Barnwell
#Date: 6/02/2021
#Program: NumberGuess
import random
Guess = 0
Num = 1
choice = 0
min = 1
max = 0

print("Welcome to Number Guess")
max = int(input("What's the highest number you want?: "))

Num = random.randint(min, max)

while Guess != Num:

    Guess = int(input("Guess the number: "))
    if Guess == Num:
        print("That's correct the number was " ,Num )
    elif Guess > Num:
        print("Too high! ")
    elif Guess < Num:
        print("Too low! ")
    else:
        print("Please type a number! ")

If you mean "in a certain range" as in I was 4 numbers away from the guess, you could do it like this:如果你的意思是“在一定范围内”,因为我离猜测有 4 个数字,你可以这样做:

if abs(num - guess) < 5:
   print("You're within 4 numbers! Keep trying!") 

The abs() function is necessary, seeing as we can't use negative values for a distance from something in this context. abs() function 是必要的,因为在这种情况下我们不能使用负值来表示与某物的距离。

You can also remove the else statement in your code.您还可以删除代码中的else语句。 Not only is the variable initialized (so the variable will always be greater or less than the guess), but the input forces a value in anyway before the conditionals.不仅变量被初始化(因此变量总是大于或小于猜测值),而且input在条件句之前强制一个值。

So basically your looking for something like this?所以基本上你在寻找这样的东西?

min = 1
max = int(input('the maximum number?'))
cn = random.randint(min, max)

guess = int(input('guess the number!'))
if guess > cn:
    print('too high!')
elif cn > guess:
    print('too low!')
elif guess == cn:
    print('correct!')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM