4位数猜猜游戏Python

时间:2016-04-22 19:14:46

标签: python

我试图在Python 3中制作一个4位数的猜数游戏。它应该通过生成1000到10000之间的随机数(random.range(1000,10000)),然后由用户猜测,然后它应该返回每个猜测你有多少数字正确。我的代码不完全正常工作,我想不出为什么它没有这样的帮助表示赞赏。

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()

7 个答案:

答案 0 :(得分:2)

您的代码中存在以下几个问题:

  1. 您正在主循环中创建一个新的Player类实例。它有效,但它不是最好的方法恕我直言。

  2. 您正在使用guessing来停止主循环。在Python中,默认情况下所有变量都是本地的。要引用全局变量,必须将其标识为全局变量:

  3. 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
    

    然而,使用全局变量可能会导致代码混乱。

    1. range提供最小值(默认为0)和最大值的最大值。该范围(3)将提供数字0,1和2(总共3个数字),这不是您想要的。
    2. 由于您正在使用课程,我会尝试以下方法:

      1. 创建一个Player

      2. 的单个实例
      3. 创建一个名为guess

      4. 的新方法
      5. 更改评估方法以返回玩家猜对的位数

      6. 创建一个名为run的新方法,该方法将调用guess和evaluate

      7. 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()
        

答案 1 :(得分:1)

#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()

答案 2 :(得分:0)

使用range(4)range(3)的值为[0, 1, 2],因此缺少3

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

全局guessing在类方法中不可用,因此循环在猜对之后永远不会结束。

工作但丑陋的解决方案是:

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

答案 3 :(得分: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
            else:
               print(str(correct)," was correct")
               correct = 0
               break
        if correct == 4:
            print("You guessed it! ")
            guessing = False

你可以将它与@ Robson的答案结合起来以结束循环。

答案 4 :(得分:0)

这是一个没有类的非无限循环版本。我以为你想一次输入一个号码?如果没有,那可以改变。

另外,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')

样品运行(正确)

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

示例运行(不正确)

4667
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Enter a guess: 5
Sorry! 4667 was correct

答案 5 :(得分:0)

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

答案 6 :(得分:0)

我所做的只是在第 14 行将 nn in range(3) 更改为 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()