简体   繁体   English

4 位数字猜谜游戏 Python

[英]4 Digit Guessing Game Python

Im trying to make a 4 digit numbers guessing game in Python 3. It should work by generating a random number between 1000 and 10000 (random.range(1000,10000)) and then by the user guessing and it should return after each guess how many numbers you have got right.我正在尝试在 Python 3 中制作一个 4 位数字猜谜游戏。它应该通过生成一个 1000 到 10000 (random.range(1000,10000)) 之间的随机数然后由用户猜测它应该在每次猜测后返回如何很多数字你都猜对了。 My code doesn't exactly work and, I can't think why it doesn't so help is appreciated.我的代码并不完全有效,我想不通为什么它没有那么帮助表示赞赏。

import random as r

guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)

correct = 0

class Player():
    def __init__(self):
        self.player_guess = input("Enter a guess")
        self.evaluate(correct)
    def evaluate(self, correct):
        for n in range(3):
            if self.player_guess[n] == real_ans_str[n]:
                correct += 1
        if not correct == 4:
            print(str(correct)," was correct")
            correct = 0
        else:
            print("You guessed it! ")
            guessing = False

while guessing:
    Player()

There are several issues in your code:您的代码中有几个问题:

  1. You're creating a new instance of Player class inside the main loop.您正在主循环内创建 Player 类的新实例。 It works, but it's not the best approach IMHO.它有效,但恕我直言,这不是最好的方法。

  2. You're using guessing to stop the main loop.您正在使用guessing来停止主循环。 In Python, all variables are local by default.在 Python 中,默认情况下所有变量都是本地变量。 In order to reference a global variable, you must identify it as global:为了引用全局变量,您必须将其标识为全局变量:

def evaluate(self, correct):
    **global guessing**
    for n in range(3):
        if self.player_guess[n] == real_ans_str[n]:
            correct += 1
    if not correct == 4:
        print(str(correct)," was correct")
        correct = 0
    else:
        print("You guessed it! ")
        guessing = False

However using global variables could lead to a messy code.但是,使用全局变量可能会导致代码混乱。

  1. range provides values from the minimum (0 by default) inclusive and the maximum exclusive. range 提供包含最小值(默认为 0)和不包含最大值的值。 That range(3) will provide the numbers 0, 1 and 2 (3 numbers total), which is not what you want.该 range(3) 将提供数字 0、1 和 2(总共 3 个数字),这不是您想要的。

Since you're using a class, I'd try the following:由于您正在使用课程,我会尝试以下操作:

  1. Create a single instance of Player创建 Player 的单个实例

  2. Create a new method called guess创建一个名为 guess 的新方法

  3. Change the evaluate method to return how many digits the player guessed right更改评估方法以返回玩家猜对的数字

  4. Create a new method called run, that will call guess and evaluate创建一个名为 run 的新方法,该方法将调用 guess 和评估

import random as r

class Player():
    def __init__(self):
        self.real_ans = str(r.randrange(1000,100000,2))

    def guess(self):
        self.player_guess = raw_input("Enter a guess")

    def evaluate(self):
        correct = 0
        for n in range(4):
            if self.player_guess[n] == self.real_ans[n]:
                correct += 1
        return correct 

    def run(self):
        while True:
            self.guess()
            correct = self.evaluate()
            if not correct == 4:
                print(str(correct)," was correct")
            else:
                print("You guessed it! ")
                break

Player().run()
#Digit Guessing Game by Deniz
#python 3.5.1 - Please note that from Python version 2.7 "Tkinter" has been renamed tkinter, with a lowercase "t".
import tkinter
import random

computer_guess = random.randint(1,10)

def check():

    user_guess = int(txt_guess.get())


if user_guess < computer_guess:
    msg = "Higher!"
elif user_guess > computer_guess:
    msg = "Lower!"
elif user_guess == computer_guess:
    msg = "Correct!"
else:
    msg = "Houston we have a problem!..."


lbl_result["text"] = msg


txt_guess.delete(0, 5)

def reset():

    global computer_guess
    computer_guess = random.randint(1,10)
    lbl_result["text"] = "Game reset. Guess again!"

root = tkinter.Tk()

root.configure(bg="white")

root.title("Guess the correct number!")

root.geometry("280x75")

lbl_title = tkinter.Label(root, text="Welcome to Deniz's guessing Game!", bg="White")
lbl_title.pack()

lbl_result = tkinter.Label(root, text="Good Luck!", bg="White")
lbl_result.pack()

btn_check = tkinter.Button(root, text="Check", fg="blue", bg="White", command=check)
btn_check.pack(side="left")

btn_reset = tkinter.Button(root, text="Reset", fg="red", bg="White", command=reset)
btn_reset.pack(side="right")

txt_guess = tkinter.Entry(root, width=7)
txt_guess.pack()

root.mainloop()
root.destroy()

Use range(4) , range(3) has the values [0, 1, 2] so 3 is missing:使用range(4)range(3)的值是[0, 1, 2]所以缺少3

for n in range(4):
    if self.player_guess[n] == real_ans_str[n]:
        correct += 1

The global guessing is not available inside the class method, so the loop never ends after guessing it right.全局guessing在类方法中不可用,因此在猜测正确后循环永远不会结束。

And working but ugly solution would be:工作但丑陋的解决方案是:

print("You guessed it! ")
global guessing
guessing = False

After reading your comments, I think what you need is this:阅读您的评论后,我认为您需要的是:

class Player():
    def __init__(self):
        self.player_guess = input("Enter a guess")
        self.evaluate(correct)
    def evaluate(self, correct):
        for n in range(4):
            if self.player_guess[n] == real_ans_str[n]:
                correct += 1
            else:
               print(str(correct)," was correct")
               correct = 0
               break
        if correct == 4:
            print("You guessed it! ")
            guessing = False

You can integrate it along with @Robson's answer to end the loop.您可以将它与@Robson 的答案结合起来以结束循环。

Here is a non infinite loop version without a class.这是一个没有类的非无限循环版本。 I assumed you wanted to input one number at a time?我假设你想一次输入一个数字? If not, that could be changed.如果没有,那可以改变。

Also, the 2 on the end of the randrange only included even numbers, so that wasn't necessary此外, randrange数末尾的 2 只包含偶数,因此没有必要

import random as r
debug = True

real_ans = str(r.randrange(1000, 10000))

if debug:
    print(real_ans) 

correct = 0
for i in range(len(real_ans)):
    player_guess = input("Enter a guess: ")
    if str(player_guess) == real_ans[i]:
        correct += 1

if correct == 4:
    print('You guessed it!')
    correct = 0
else:
    print('Sorry!', real_ans, 'was correct')

Sample run (Correct)样品运行(正确)

9692
Enter a guess: 9
Enter a guess: 6
Enter a guess: 9
Enter a guess: 2
You guessed it!

Sample run (Incorrect)样品运行(不正确)

4667
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Sorry! 4667 was correct
import random
from Tools.scripts.treesync import raw_input
x= random.randint(1000,9999)
num=0
while num < 1000 or num > 9999:
    num = int(raw_input("Please enter a 4 digit number: "))
    if num < 1000 or num > 9999:
        print("///wrong input////")

print("system generated number is ",x)
print("The number you entered is ",num)
if num == x:
    print("Congrats you win")
else:
    rabbit=0
    tortose=0
    unum = str(num)
    snum = str(x)
    c1=0enter code here
    for i in unum:
        c1=c1+1
        c2 = 0
        for j in snum:
            c2=c2+1
            if(i==j):
                if(c1==c2):
                    rabbit=1

                else:
                    tortose=1


    if rabbit==1:
        print("you got rabbit")
    elif rabbit==0 and tortose==1:
        print("you got tortose")
    else:
        print("Bad Luck you dont have any match")

    enter code here

what i did was just change n from n in range(3) to n in range(4) in line 14我所做的只是将第 14 行中的nn in range(3)中的n in range(4)更改为n in range(4)中的n in range(4)

import random as r

guessing = True
real_ans = r.randrange(1000, 10000, 2)
real_ans_str = str(real_ans)

correct = 0

class Player():
    def __init__(self):
        self.player_guess = input("Enter a guess")
        self.evaluate(correct)
    def evaluate(self, correct):
        for n in range(4):
            if self.player_guess[n] == real_ans_str[n]:
                correct += 1
        if not correct == 4:
            print(str(correct)," was correct")
            correct = 0
        else:
            print("You guessed it! ")
            guessing = False

while guessing:
    Player()

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

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