简体   繁体   English

python代码不起作用

[英]python code not working

i have the following code for a rock paper scissors game:我有以下石头剪刀布游戏代码:

import random
def rps():  
   computerchoice = random.randint(1,3) 
   if computerchoice == 1: 
     computerchoice = "rock" 
   elif computerchoice == 2: 
     computerchoice = "paper" 
   elif computerchoice == 3: 
     computerchoice = "scissors"
   choice = raw_input("Rock, paper, or scissors?:") 
   choice = choice.lower() 
   if choice != "rock":
     if choice != "paper":
       if choice != "scissors":
         print "Check your spelling and try again." 
         rps()
       else:
         pass
     else:
       pass 
   else: 
     print "The computer chose " + computerchoice + "." 
     if choice == computerchoice: 
       print "It's a draw!" 
     elif choice + computerchoice == "rockpaper": 
       print "Computer wins, paper covers rock!" 
     elif choice + computerchoice == "rockscissors": 
       print "Player wins, rock crushes scissors!" 
     elif choice + computerchoice == "paperrock": 
       print "Player wins, paper covers rock!" 
     elif choice + computerchoice == "paperscissors": 
       print "Computer wins, scissors cut paper!" 
     elif choice + computerchoice == "scissorsrock":
       print "Computer wins, rock crushes scissors!"
     elif choice + computerchoice == "scissorspaper":
       print "Player wins, scissors cuts paper!" 
rps()

Whenever i run it, it works fine if i pick rock, but if i pick paper or scissors, the code stops.每当我运行它时,如果我选择石头,它就可以正常工作,但是如果我选择纸或剪刀,代码就会停止。 It wont throw any kind of error, it just stops.它不会抛出任何类型的错误,它只是停止。 Please help me!请帮我!

This should be closer to what you need:这应该更接近您的需要:

import random
def rps():
    computerchoice = random.randint(1,3)
    if computerchoice == 1:
        computerchoice = "rock"
    elif computerchoice == 2:
        computerchoice = "paper"
    elif computerchoice == 3:
        computerchoice = "scissors"
    choice = raw_input("Rock, paper, or scissors?:")
    choice = choice.lower()
    if choice not in ["scissors","paper","rock"]: # check if choice is valid
        rps()
    print "The computer chose " + computerchoice + "."
    if choice == computerchoice:   # move on to your comparison checks 
        choice + computerchoice
        print "It's a draw!"
    elif choice + computerchoice == "rockpaper":
        print "Computer wins, paper covers rock!"
    elif choice + computerchoice == "rockscissors":
        print "Player wins, rock crushes scissors!"
    elif choice + computerchoice == "paperrock":
        print "Player wins, paper covers rock!"
    elif choice + computerchoice == "paperscissors":
        print "Computer wins, scissors cut paper!"
    elif choice + computerchoice == "scissorsrock":
        print "Computer wins, rock crushes scissors!"
    elif choice + computerchoice == "scissorspaper":
        print "Player wins, scissors cuts paper!"
rps()

The problem is from the first choice if statement:问题来自第一选择 if 语句:

    if choice != "rock":
        if choice != "paper":
            if choice != "scissors":

when rock is selected it jumps to the else statement without evaluating the other two if statements.当rock被选中时,它会跳转到else语句而不评估其他两个if语句。 A more intuitive but admittedly non-Pythonic way is to have a series of nested if statements:一种更直观但不可否认的非 Pythonic 方法是使用一系列嵌套的 if 语句:

import random
def rps():  
    computerchoice = random.randint(1,3) 
    if computerchoice == 1: 
        computerchoice = "rock" 
    elif computerchoice == 2: 
        computerchoice = "paper" 
    elif computerchoice == 3: 
        computerchoice = "scissors"
    choice = raw_input("Rock, paper, or scissors?:") 
    choice = choice.lower() 
    print "The computer chose " + computerchoice + "." 
    if choice == 'rock':
        if computerchoice == 'rock':
            print 'Draw: you both picked rock'
        elif computerchoice == 'scissors':
            print 'You win! Rock beats scissors'
        elif computerchoice == 'paper':
            print 'You lose.  Try again'
    elif choice == 'paper':
        if computerchoice == 'rock':
            print 'You win!'
        elif computerchoice == 'scissors':
            print 'You lose.'
        elif computerchoice == 'paper':
            print 'You draw.'
    elif choice == 'scissors':
        if computerchoice == 'rock':
            print 'You lose.'
        elif computerchoice == 'scissors':
            print 'You draw.'
        elif computerchoice == 'paper':
            print 'You win.'
    else:
        print 'I am sorry, I could not make out what you typed.  Try again'
        rps()

rps()

Loop just your input.仅循环您的输入。 Don't recursively call the whole game again.不要再次递归调用整个游戏。 Also setup a variable to test against for valid choices.还设置一个变量来测试有效的选择。 Also if you break out the win conditions you can add to it easily.此外,如果您打破获胜条件,则可以轻松添加。 Maybe something like this也许像这样

import random
CHOICES = {'rock': 'crushes', 'paper': 'covers', 'scissors': 'cuts'}


def win(p1, p2):
    if p1 == p2:
        return 0
    if p1 == 'rock':
        return 2 if p2 == 'paper' else 1
    if p1 == 'paper':
        return 2 if p2 == 'scissors' else 1
    if p1 == 'scissors':
        return 2 if p2 == 'rock' else 1


def rps():
   computerchoice = random.choice(CHOICES.keys())
   choice = raw_input("Rock, paper, or scissors?:").lower()
   while choice not in CHOICES:
       print "Check your spelling and try again."
       choice = raw_input("Rock, paper, or scissors?:").lower()
   print "The computer chose %s." % computerchoice
   winner = win(choice, computerchoice)
   if winner==0:
       print "It's a draw!"
   if winner==1:
       print "Player wins, %s %s %s!" % (choice, CHOICES[choice], computerchoice)
   if winner==2:
       print "Computer wins, %s %s %s!" % (computerchoice, CHOICES[computerchoice], choice)


rps()

Now say you want to add lizard and spock .现在假设您要添加lizardspock Just update CHOICES and the win() function.只需更新CHOICESwin()函数。 :) :)

Check theese lines out:检查这些行:

 if choice != "paper": if choice != "scissors": print "Check your spelling and try again." rps() else: pass #here you tell it to do nothing when you choose "scissors" else: pass #here you tell it to do nothing when you choose "paper"

I think you just need to re-sort your if/else statements :-)我认为你只需要重新排序你的 if/else 语句:-)

The else section (containing the brains of your code) of the first if :else部分(包含代码的大脑)第一if

if choice != "rock":
    if choice != "paper":
        if choice != "scissors":

never runs if player doesn't select 'rock' ie 'paper' , 'scissors' and any invalid input will ensure the else containing the important section of your code doesn't get executed.如果玩家没有选择'rock' ,'paper''scissors'和任何无效的输入将确保包含代码重要部分的else不会被执行,则永远不会运行。

you definitely don't need recursion for such a simple algorithm (calling rps() from rps() )对于这样一个简单的算法,您绝对不需要递归rps()rps()调用rps()

you should try to implement it like this:你应该尝试像这样实现它:

input == ""
while input != "quit":
  input = raw_input(...)
  if input not in ["r", "p", "s"]: continue
  computer_choice = ...
  if foo beats bar: print ...
  if bar beats foo: print ...

Let's look at this.让我们看看这个。

if choice != "rock":
  if choice != "paper":
    if choice != "scissors":
      print "Check your spelling and try again." 
      rps()
    else:
      pass
  else:
    pass 
else: 
  # Do stuff...

You input scissors.你输入剪刀。

  • Does "scissors" != "rock"? “剪刀”!=“摇滚”吗? Yes, so lets go further.是的,所以让我们走得更远。

  • Does "scissors" != "paper"? “剪刀”!=“纸”吗? Yes, so lets go further.是的,所以让我们走得更远。

  • Does "scissors" != "scissors"? “剪刀”!=“剪刀”吗? No, so let's look at the alternative else clause:不,让我们看看替代的 else 子句:

     else: pass

This code does nothing... Every other if/else clause is then broken out of after this... See the issue?这段代码什么都不做……在此之后,所有其他的if/else子句都被打破了……看到问题了吗?

There are also a lot of simplifications you can do, for example you can make use of tables and lists more often instead of using so many if statements .您还可以进行很多简化,例如您可以更频繁地使用表格和列表,而不是使用如此多的if statements For example (although the code remains largely untested):例如(尽管代码在很大程度上未经测试):

import random

def convert_choice(choice):
    choice_map = {"rock":0, "paper":1, "scissors":2}
    return choice_map[choice]

def rock_paper_scissors():
    choices = ["rock", "paper", "scissors"]
    computer_choice = random.randint(0,2)
    player_choice = raw_input("Rock, paper, or scissors? ") 
    raw_player_choice = convert_choice(player_choice) * 3
    print "Copmuter played: " + choices[computer_choice]
    print "You played: " + player_choice
    win_states = {0:"tied", 3:"won", 6:"loss", 
                  -1:"loss", 2:"tied", 5:"won",
                  -2:"won", 1:"loss", 4:"tied"}
    print "You " + win_states[raw_player_choice - computer_choice]

def main():
    rock_paper_scissors()

if __name__ == "__main__":
    main()

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

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