Python猜测游戏提示和分数系统

时间:2016-09-07 13:58:48

标签: python

我正在编写我的第一个python游戏并尝试合并两个额外的元素,但我不确定如何编写它。

1:想法是游戏将使用内置随机模块(即123)生成随机三位数字,并且用户将有23次尝试猜测正确的数字。它将通过要求用户在0-9之间输入三位数来启动。我想创建一个提示系统,以便用户知道他们是否在正确的轨道上。请参阅下面链接中的示例(我无法显示嵌入图像)。

Click to see example Input/Output for hints

  • A" W"表示猜测中的所有字符都是错误的。
  • 一个或多个" X" s表示他们的角色正确,但位置不正确
  • 一个或多个" R" s表示他们在正确的位置有正确的角色

要获得此类提示,我需要创建3个单独的数字并将它们组合在一起以形成目标数字,或者我仍然可以使用以下代码执行此操作:

target = random.randint(111, 999)

我开始编写一个函数,它接受变量猜测(这是用户输入的内容)和目标(生成的数字):

def get_hint(guess, target):

据我所知。可笑,我知道。我真的不知道是否有可能创建这个提示系统。

2:我还希望它有一个积分系统,其中积分从10000开始(如果用户首先正确猜测)并且每次错误猜测减少10%(第二次猜测= 9000,第三次猜测= 8100等) 。)到小数点后两位。我已经增加了用户尝试的猜测量的计数,所以当他们猜出正确的数字时会发生以下情况:

if guess == target:
    print("Congratulations!")
    print("{} was the correct answer!".format(target))
    print("You guessed the correct answer in {} tries and scored {} points.".format(tries, points))

2 个答案:

答案 0 :(得分:0)

首先,积分系统相当简单:只需得一个得分变量并在每轮score=score*0.9修改它,并在用"{:.2f}".format(score)

打印时将其四舍五入到小数点后

关于提示系统:

拥有三个数字的列表将更容易处理,因此我假设targetguess具有以下格式之一"123"[1,2,3](因为字符串可以索引为列表)

棘手的部分是进行正确的比较,因为你已经处理了与目标匹配的数字,以便在guess = 113和target = 333的示例情况下仅提供"r"。这是一个完成工作的功能:

def hint(guess,target):

    if guess == target:
        print("win")
    else:
        #we store a list to keep track of the numbers 
        #already matched so we don't count them twice as x and r
        r=[0]*len(target) 

        #first we check if there's a direct match
        for i,n in enumerate(guess):
            if guess[i] == target[i]:
                r[i]=1

        #we make new lists without the digits that matched
        stripped_guess=[n for i,n in enumerate(guess) if r[i] == 0]  
        stripped_target=[n for i,n in enumerate(target) if r[i] == 0]  

        #we will now try to count the amount of x
        x=0
        for n in set(stripped_guess):
            #we count how many time that given digit appears 
            # in the two lists, the smallest is our x amount
            x+=min(stripped_guess.count(n),stripped_target.count(n))

        if sum(r) == 0 and x == 0:
            print("w")
        else:
            print("r"*sum(r)+"x"*x)

一些测试:

>>> hint(guess="404",target="404")
win
>>> hint("135","331")
rx
>>>hint("11123","12133")
rrrx

答案 1 :(得分:-1)

如果变量num中有一个三位数的数字,则可以删除数字: 在[1]中:num = 347

在[2]中:num%10

Out [2]:7

在[3]中:( num%100)// 10

Out [3]:4

在[4]中:( num%1000)// 100

Out [4]:3

然后你可以比较数字并放置你的X和R。