创建循环,能够退出吗?

时间:2017-03-27 05:51:58

标签: python

  

我正在制作一个基本游戏2个玩家1-3个骰子可供选择,而不是谁赢得最高数量的胜利。我如何使用python

来完成这项工作      

我不确定如何循环滚动然后能够选择退出,继续并且能够选择另一个要掷骰子的数量并转到开始屏幕。还有什么可以用来保持这个分数。这是我的代码。

     

我也遇到了if命令的问题如何在不显示所有选项的情况下将骰子从1选择为3

Dice = input("Please select number of dice you would like to use (1-3)")
if Dice == "1":
    print("You have selected 1 dice")
 import random
 Roll1 = random.randrange(1,6)
print ("Player 1's Roll")
print(Roll1)
print ("Player 2's Roll")
print (Roll1)
#2 Dice Counter
  if Dice == "2":
    print("You have selected 2 dice")
import random
Roll2 = (random.randrange(2,12))
print ("Player 1's Roll")
print(Roll2)
print ("Player 2's Roll")
print (Roll22)

#3 Dice Counter
if Dice == "3":
    print("You have selected 3 dice")
import random
Roll3 = random.randrange(3,18)
print ("Player 1's Roll")
print(Roll3)
print ("Player 2's Roll")
print (Roll3)
while invalid_input :
            Dice()

2 个答案:

答案 0 :(得分:0)

将您的逻辑放在一个函数中,例如getDiceInput(),如果用户输入有效选项,则会返回,如果用户输入介于(1-3)之间的有效输入,则结果将被打印,否则将打印一条无效的输入消息,现在继续在循环内调用getDiceInput(),直到用户输入-1这将导致循环while (inputValue != -1)退出,并且将打印再见消息以退出,并且使用randint生成随机数,请查看以下代码段:

   from random import randint


    def getDiceInput():
      Roll1 = 0
      Roll2 = 0
      validInput = 1
      Dice = input("Please select number of dice you would like to use (1-3) -1 to exit")
      if Dice == "1":
        print("You have selected 1 dice")
        Roll1 = int(randint(1,6))
        Roll2 = int(randint(1,6))

      #2 Dice Counter
      elif Dice == "2":
        print("You have selected 2 dice")
        Roll1 = int(randint(2,12))
        Roll2 = int(randint(2,12))

      #3 Dice Counter
      elif Dice == "3":
        print("You have selected 3 dice")
        Roll1 = randint(3,18)
        Roll2 = randint(3,18)

      elif Dice == "-1":
        validInput = -1

      else :
        print("invalid input reenter")
        validInput = 0


      if validInput == 1 :
        print ("Player 1's Roll")
        print(Roll1)
        print ("Player 2's Roll")
        print (Roll2)

      return validInput

    #Code execution will start here
    inputValue = getDiceInput()
    while (inputValue != -1):
      inputValue = getDiceInput()

    print("Goodbye")

答案 1 :(得分:-1)

使用random模块和randint功能。

from random import randint

然后使用它:

randint(0,10)

以上将生成0到10之间的随机整数。

<强>循环

使用while循环来循环滚动。

condition = "play"
while condition == "play":
    #Your code here

    if(input("Enter 'play' to play again or 'quit' to stop the program and reveal the scores: ") == "quit"):
        #Break out of the loop
        break
    else:
         condition = "play"

对于if&#39; 我会使用一些数学来生成randintrandrange中的数字范围。例如:

#Get input of dice to roll as integer
toRoll = int(input("Dice to roll: "))
#'Roll' the dice that many times
Roll = random.randrange(1*toRoll,6*toRoll)

然后使用Roll变量。 这将与使用所有if语句(当然除print之外)相同。

相关问题