简体   繁体   English

Python猜谜游戏[骰子]

[英]Python guessing game [Dice]

import random

number = random.randrange(1, 10)
print(number)
guess_count = 0
guess_limit = 3
out_of_gusses = False
guess = int(input("enter ur guess: "))

while guess > number or guess != number and not out_of_gusses:
    if guess > number:
        print("ur guess is higer than the number")
    else:
        print("ur guess is lower than the number:")

    if guess_count < guess_limit:
        guess = int(input("enter ur guess: "))
        guess_count += 1
    else:
        out_of_gusses = True

    if out_of_gusses:
        print("Out of guesses u lose: ")
    else:
        print("u Win")

my problem is that when i run the program and i did enter my number it says u win even though the number is wrong and i also get 4 tries when the limit is set to 3 guess:limit = 3我的问题是,当我运行程序并且我确实输入了我的号码时,它说即使号码错误u win了,当限制设置为 3 时,我也尝试了 4 次guess:limit = 3

iam new at coding so iam not to sure what the problem is but i think its somthing with the condintion of my while loop but cant quite get my head around how i should phase then我是编码新手,所以我不确定问题是什么,但我认为它与我的 while 循环的条件有关,但我不能完全理解我应该如何分阶段

Here's how you can restructure your entire logic into something simple that works:以下是如何将整个逻辑重组为简单有效的方法:

import random

number = random.randrange(1, 10)
print(number)
guess_count = 0
guess_limit = 3

while True:
    if guess_count < guess_limit:
        guess = int(input("enter ur guess: "))
        guess_count += 1
        if guess == number:
            print("u Win")
            break
    else:
        print("Out of guesses u lose: ")
        break
    
    if guess > number:
        print("ur guess is higer than the number")
    elif guess < number:
        print("ur guess is lower than the number:")

Basically, you create an infinite loop that you break out of, if the guess is correct or if they have run out of guesses.基本上,您会创建一个无限循环,如果猜测正确或他们的猜测用完了,您就可以打破这个无限循环。 This way, you can have your entire dice game logic into that while loop.这样,您就可以将整个骰子游戏逻辑放入该while循环中。

There are a few flaws in your code你的代码有一些缺陷

while guess > number or guess != number and not out_of_gusses:

This resolves to这解决了

while guess != number and not out_of_gusses:

because whenever guess > number is true , guess != number is anyway true .因为只要guess > numbertrueguess != number无论如何true That also means that if your guess is correct in the first place, the while loop is not executed at all.这也意味着,如果您的猜测首先是正确的,则根本不会执行 while 循环。

The problem with your off by one guess_count comes from the fact that you're initializing guess_count with 0 ignoring the initial guess.你关闭一个guess_count来自这样一个事实,即你用 0 初始化guess_count忽略了初始猜测。

if out_of_gusses:
  print("Out of guesses u lose: ")
else:
  print("u Win")

This conclusion is not correct, just because you're not out of guesses doesn't mean you won!这个结论是不正确的,仅仅因为你没有猜错并不意味着你赢了!

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

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