试图添加我的第一个得分计数器(Python)(初学者)

时间:2017-12-03 16:58:07

标签: python python-3.x

这是我在这里的第一篇文章。我是编码的初学者,我创造了一个小游戏来进行某种练习。我在添加分数计数器时遇到了麻烦。我见过一些类似的帖子,但我没有设法弄清楚。

你们也可以给我一些关于我的代码的提示,欢迎任何反馈(告诉我我可以改进的等等)。

以下是代码:

import random
import time


def game():

    user_wins = 0
    user_loses = 0

    while True:
        try:
            number = int(input('Choose a number between 1 and 10: '))
            if 0 <= number <= 10:
                print('Rolling the dices {} time(s)!'.format(number))
                break
            else:
                print("That's not quite what we were looking for.")
                continue
        except ValueError:
            print("That's not quite what we were looking for.")

    user_number = random.randint(1, 50)
    computer_number = random.randint(1, 50)

    time.sleep(1)
    print("You've rolled {}".format(user_number))

    time.sleep(1)
    print('Bob rolled {}'.format(computer_number))

    if computer_number > user_number:
        time.sleep(0.5)
        print('Bob Won')
        user_loses += 1
    elif computer_number < user_number:
        time.sleep(0.5)
        print("You've Won!")
        user_wins += 1
    elif computer_number == user_number:
        time.sleep(0.5)
        print('Seems like we have a little situation')

    print("\nWins: {} \nLosses: {}".format(user_wins, user_loses))

    time.sleep(0.5)
    play_again = input(str("Would you like to play again (y/n)? "))
    if play_again == 'y':
        print("Ready?\n")
        game()
    else:
        print("\nThank you for playing.")


game()

我想添加像你的得分:1-0或类似的东西。我已经取得了一些进展,但是当循环重置值时..

3 个答案:

答案 0 :(得分:0)

欢迎编程!所以我要告诉你如何来实现它,所以你也可以自己做:D。所以这就是我们要做的事情:

我们会在while循环的scope(click here)之外设置一个变量来跟踪分数,比如score = 0。 每当有人成功,得到正确答案,我们就会通过说score = score + 1来增加答案。但这需要太多时间来输入正确的D:所以python有一个捷径!你在代码中的某个地方说score += 1你要增加分数(在while True循环中,在这种情况下)。然后我们将通过引用它来打印出分数(或任何内容):

print( "Your final score was %s" % str(score) ) - 我知道,愚蠢的str()是什么!?这是因为我们的score是一个整数。因为我们可以添加和操作它(是的,我知道很酷)。

Aaaand就是这样:)。如果您需要任何进一步的帮助,请不要犹豫。祝你好运:D。

答案 1 :(得分:0)

在while循环开始之前移动此行。     number = int(输入(&#39;选择1到10之间的数字:&#39;)) 此外,它提示输入1-10之间,但if语句允许0-10。 通过为两个玩家分配初始分数为0来添加计数器。

user_number_score = 0

在If语句中确定谁赢了该轮,例如,如果用户赢了添加...

user_number_score = user_number_score + 1

答案 2 :(得分:0)

我找到了办法。我不得不重新开始,从头开始重新编写代码,它也更好看。谢谢大家的反馈。

Added it as image.