石头-布-剪刀-得分问题

2024-05-14 02:50:35 发布

您现在位置:Python中文网/ 问答频道 /正文

请有人告诉我如何做一个基本的评分系统进入这个代码。在

import random
print 'Welcome to Rock, paper, scissors!'
firstto=raw_input('How many points do you want to play before it ends? ')

playerscore=+0
compscore=+0

while True:
    choice = raw_input ('Press R for rock, press P for paper or press S for scissors, CAPITALS!!! ')

    opponent = random.choice(['rock', 'paper' ,'scissors' ])

    print 'Computer has chosen', opponent

    if choice == 'R' and opponent == "rock":
        print 'Tie'
        playerscore = playerscore+0
        compscore = compscore+0

    elif choice == 'P' and opponent == "paper":
        print 'Tie'
        playerscore = playerscore+0
        compscore = compscore+0

    elif choice == 'S' and opponent == "scissors":
        print 'Tie'
        playerscore = playerscore+0
        compscore = compscore+0

    elif choice == 'R' and opponent == "paper":
        print 'CPU Wins'
        playerscore = playerscore+0
        compscore = compscore+1

    elif choice == 'P' and opponent == "scissors":
        print 'CPU Wins'
        playerscore = playerscore+0
        compscore = compscore+1

    elif choice == 'S' and opponent == "rock":
        print 'CPU Wins'
        playerscore = playerscore+0
        compscore = compscore+1


    elif choice == 'P' and opponent == "rock":
            print 'You Win'
            playerscore = playerscore+1 
            compscore = compscore+0

    elif choice == 'S' and opponent == "paper":
            print 'You Win'
            playerscore = playerscore+1
            compscore = compscore+0

    elif choice == 'R' and opponent == "scissors":
            print 'You Win'
            playerscore = playerscore+1
            compscore = compscore+0


    print 'Player score is',playerscore
    print 'Computer score is',compscore

    if playerscore == firstto:
        'You won the game :)'
        exit()
    elif compscore == firstto:
        'You lost the game :('
        exit()

Tags: andyouforcpupaperprintscissorsrock
3条回答

问题出在第3行的raw_inputraw_input总是返回一个字符串,而您需要的是一个int。如果您将第3行改为:

firstto = int(raw_input('How many points do you want to play before it ends? '))

你的代码会起作用的。在

要清理用户输入(这样当用户输入"hello"而不是5时,代码不会崩溃),可以将raw_input调用包装到tryexcept语句中。在

例如:

^{pr2}$

另外,您的代码被困在一个无限循环中,因为您在与整数比较时使用了raw_input提供的字符串。这将始终返回False:

^{3}$

修改第一个原始输入值。你得到了一根绳子。在

为了获得更好的结果,还需要验证输入:-)

while 1:
    firstto=raw_input('How many points do you want to play before it ends? ')
    if firstto.isdigit():
        firstto = int(firstto)
        break
    else:
        print "Invalid Input. Please try again"

这将只接受带数字的字符串。即使有人给出的输入是“5.0”,也会被忽略。在

要更好地阅读原始输入,请单击here。要了解有关内置字符串方法的更多信息,请阅读here。在

附言:这与问题无关。但有一点建议。你的代码可以简化得多。如果您正在学习,请将此代码保留为v0.1并在您的进度时更新它。在

有很多方法可以优化这段代码,但是您当前的问题是raw_input和点的入口。这将返回一个字符串,而您需要一个int。用int()包起来,你就没事了。也就是说,直到有人输入了一个无法解析的东西。在

firstto = int(raw_input('How many points do you want to play before it ends? '))

如果你不想去优化你的代码:

^{pr2}$

相关问题 更多 >