【问题标题】:Most efficient way to reuse code multiple times? And also my while loops infinitly with boolean switch多次重用代码的最有效方法?还有我的 while 无限循环与布尔开关
【发布时间】:2026-01-22 18:40:01
【问题描述】:

当我刚开始时,我正在制作一个石头剪刀布游戏作为一个小项目,而且我必须经常使用相同的代码。最好的方法是什么,因为目前我已经将它复制并粘贴到了整个地方。它看起来很不整洁,而且我在验证输入时遇到了循环问题,不得不全部更改它很痛苦。

user_continue = raw_input("Would you like to play again? Y/N: ")
user_continue = user_continue.upper()
#Yes or no continue for the continue while loop to continue working until correct user input.
y_n_continue = False
while y_n_continue == False:
    if user_continue == "Y" or user_continue == "YES" or user_continue == "N" or user_continue == "NO":
        if user_continue == "Y" or user_continue == "YES":
            continue_game = True
            y_n_continue = True
        elif user_continue == "N" or user_continue == "NO":
            continue_game = False
            y_n_continue = True
        else:
            print "Press Y or N"
            y_n_continue = False
    else:
        print ""

如果我添加整个代码可能会更容易(通过修复,感谢 Anton. 目前我收到错误 - TypeError: 'bool' object is not callable.

我基本上是想让它在用户想要的时间内循环游戏,同时还要验证输入以使一切尽可能防弹。

编辑 2 - 这是新代码,下面有一些测试数据。

当我启动它时,系统会提示您在开始时输入 y/n。

您还必须在每场比赛后输入 y 或 n 两次。

如果您在石头/纸/剪刀选择中输入“错误”数据,则会进入 y/n 选择

import random


def continue_game():
    while True:
        user_continue = raw_input("Would you like to play again? Y/N: ").upper()
        if user_continue in ["Y", "YES", "N", "NO"]:
            return user_continue in ["Y", "YES"]
        else:
            print "Press Y or N"



while continue_game():

    #computers choice of rock, paper or scissors
    computer_input = ["ROCK", "PAPER", "SCISSORS"]
    computer_choice = random.choice(computer_input)
    #users choice or rock, paper or scissors
    user_input = raw_input("Choose rock, paper or scissors: ")
    #Turns user input to upper case.
    user_choice = user_input.upper()
    if user_choice == "ROCK" or user_choice == "PAPER" or user_choice == "SCISSORS":
        #Computer = ROCK
        if computer_choice == "ROCK":
            #user = ROCK
            if user_choice == "ROCK":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You draw!"

                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False



            #user = PAPER
            elif user_choice == "PAPER":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You win!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False


            #user = SCISSORS   
            elif user_choice == "SCISSORS":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You lose!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False


        #Computer = PAPER
        elif computer_choice == "PAPER":
            #user = ROCK
            if user_choice == "ROCK":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You lose!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False

            #user = PAPER
            elif user_choice == "PAPER":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You draw!"
                if continue_game():
                    print "continue"
                else:
                    continue_game = False


            #user = SCISSORS   
            elif user_choice == "SCISSORS":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You win!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False

        #Computer = SCISSORS
        elif computer_choice == "SCISSORS":
            #user = ROCK
            if user_choice == "ROCK":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You win!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False

            #user = PAPER
            elif user_choice == "PAPER":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You lose!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False

            #user = SCISSORS   
            elif user_choice == "SCISSORS":
                print "You have chosen: " + user_choice
                print "The computer has chosen: " + computer_choice
                print "You draw!"
                #replay?
                if continue_game():
                    print "continue"
                else:
                    continue_game = False

        else:
            print "Something has gone wrong."
    else:
        print "Are you sure you entered that correctly?"

输出:

Would you like to play again? Y/N: y

Choose rock, paper or scissors: rock

You have chosen: ROCK

The computer has chosen: PAPER

You lose!

Would you like to play again? Y/N: y

continue

Would you like to play again? Y/N: y

Choose rock, paper or scissors: paper

You have chosen: PAPER

The computer has chosen: ROCK

You win!

Would you like to play again? Y/N: wer

Press Y or N

Would you like to play again? Y/N: dfg

Press Y or N

Would you like to play again? Y/N: y

continue

Would you like to play again? Y/N: y

Choose rock, paper or scissors: test

Are you sure you entered that correctly?

Would you like to play again? Y/N: y

Choose rock, paper or scissors: rock

You have chosen: ROCK

The computer has chosen: SCISSORS

You win!

Would you like to play again? Y/N: n

exit

Would you like to play again? Y/N: n

>>> 

我知道我很痛苦,但这一切都值得赞赏。

【问题讨论】:

  • 我认为您正在寻找一个函数 - 这是一个非常基本的概念,您可能需要阅读一些教程。

标签: python while-loop boolean infinite-loop


【解决方案1】:

您可以从代码中创建一个函数并返回continue_game 变量的值。以下是封装在函数中的代码的缩小版本,以及其用法示例:

def continue_game():
    while True:
        user_continue = raw_input("Would you like to play again? Y/N: ").upper()
        if user_continue in ["Y", "YES", "N", "NO"]:
            return user_continue in ["Y", "YES"]
        else:
            print "Press Y or N"

if continue_game():
    print "continue"
else:
    print "exit"

更新:关于您的完整代码,要修复错误,您需要删除以下行:

continue_game = True

并替换:

while continue_game == True:

与:

while continue_game():

【讨论】:

    【解决方案2】:

    首先你应该避免像 while var == False use while not var:

    同样的事情:

    "如果 user_continue == "Y" or user_continue == "YES" or user_continue == "N" or user_continue == "NO":"

    做一些类似的事情:

    "如果 user_continue.upper() in "YESNO"

    有更好的方法吗? 而是:)

    我认为询问玩家是否想再次玩的正确方法是制作一个“游戏”函数并在最后调用它

    这里的例子: http://pastebin.com/0jQtwGdi

    【讨论】:

      【解决方案3】:

      一旦你弄清楚这个代表游戏规则的表格:

            | ROCK2 | PAPR2 | SCIS2 |
      ------+-------+-------+-------|
      ROCK1 |    0  |     2 |     1 |
      PAPR1 |    1  |     0 |     2 |
      SCIS1 |    2  |     1 |     0 |
      
      1 = column wins, 2 = row wins, 0 = draw
      

      您的整个程序可以通过使用字典和元组的索引以及一些异常处理来缩小很多:

      import random
      
      m = dict(
              rock     = dict(rock=0, paper=2, scissors=1),
              paper    = dict(rock=1, paper=0, scissors=2),
              scissors = dict(rock=2, paper=1, scissors=0)
          )
      
      while True:
      
          try:
              continue_game = {'n': False, 'y': True}[
                  raw_input("Would you like to play again? Y/N: ")[0].lower()
              ]
          except:
              print "Press Y or N"
              continue # next loop
      
          if not continue_game: break
      
          human = raw_input("Choose rock, paper or scissors: ").lower()
          computer = random.choice(m.keys())
      
          print "You have chosen:", human
          print "The computer has chosen:", computer
          print ("You draw!", "You lose!", "You win!")[ m[computer][human] ]
      

      一开始您可能会发现它有点棘手,但这样设计的代码向您保证 not to repeat yourself 并且它比在您的情况下采用 if-then-else 结构的重度代码更具可读性(和可维护性)。

      【讨论】:

        最近更新 更多