【问题标题】:Simulate rolling dice in Python?在 Python 中模拟掷骰子?
【发布时间】:2013-01-15 02:08:28
【问题描述】:

第一次在这里写..我正在用python编写一个“掷骰子”程序,但我被卡住了,因为不能让它每次都生成一个随机数

这是我目前所拥有的

import random

computer= 0 #Computer Score
player= 0 #Player Score

print("COP 1000 ")
print("Let's play a game of Chicken!")

print("Your score so far is", player)

r= random.randint(1,8)

print("Roll or Quit(r or q)")

现在每次我输入 r 时,它都会一遍又一遍地生成相同的数字。我只是想每次都改变它。

我希望它每次都更改号码,请帮忙 我问过我的教授,但这是他告诉我的。“我想你必须弄清楚”我的意思是我希望我能,我一遍又一遍地检查我的笔记,但我不知道该怎么做它:-/


顺便说一句,这就是它向我展示程序的方式

COP 1000
Let's play a game of Chicken!
Your score so far is 0
Roll or Quit(r or q)r

1

r

1

r

1

r

1

我想发布图片,但它不允许我发布


我只想对所有回答我问题的人说声谢谢!您的每一个答案都有帮助! **感谢你们,我会按时完成我的项目!谢谢你

【问题讨论】:

  • 您似乎在这里遗漏了一些代码——您需要某种循环来获得您正在显示的输出......
  • Python dice simulation 的可能重复项
  • 您是在循环的每次迭代中调用random.randint(1,8),还是在循环之前调用一次?
  • 是的,我以为它每次都会选择一个随机数,但它没有这样做。这让我觉得这是错误的代码,教授从来没有教过我们怎么做,也许是因为班里有人以前编程过,但这是我第一次,没有最好的体验,尤其是当他没有甚至不想花时间帮我一把,帮助我遇到困难的地方
  • @ckarmann 我认为他根本没有使用循环

标签: python random dice


【解决方案1】:

不知道什么类型的骰子有 8 个数字,我用的是 6。

一种方法是使用随机播放。

import random
dice = [1,2,3,4,5,6]
random.shuffle(dice)
print(dice[0])

每次它都会随机打乱列表并取第一个。

【讨论】:

  • Nix 它向我显示无效的语法,并且单词 dice 突出显示为红色(请原谅我的语法)仍在学习英语
  • 假设您只需要括号,您必须使用 Python 3。
【解决方案2】:

简单使用:

import random
dice = [1,2,3,4,5,6]       #any sequence so it can be [1,2,3,4,5,6,7,8] etc
print random.choice(dice)

【讨论】:

    【解决方案3】:
    import random
    
    computer= 0 #Computer Score
    player= 0 #Player Score
    
    print("COP 1000 ")
    print("Let's play a game of Chicken!")
    
    print("Your score so far is", player)
    
    r= random.randint(1,8) # this only gets called once, so r is always one value
    
    print("Roll or Quit(r or q)")
    

    您的代码中有很多错误。这只会工作一次,因为它不在循环中。 改进后的代码:

    from random import randint
    computer, player, q, r = 0, 0, 'q', 'r' # multiple assignment
    print('COP 1000')  # q and r are initialized to avoid user error, see the bottom description
    print("Let's play a game of Chicken!")
    player_input = '' # this has to be initialized for the loop
    while player_input != 'q':
        player_input = raw_input("Roll or quit ('r' or 'q')")
        if player_input == 'r':
            roll = randint(1, 8)
        print('Your roll is ' + str(roll))
        # Whatever other code you want
        # I'm not sure how you are calculating computer/player score, so you can add that in here
    

    while 循环执行其下的所有操作(即缩进),直到语句变为 false。因此,如果玩家输入q,它将停止循环,并进入程序的下一部分。见:Python Loops --- Tutorials Point

    关于 Python 3 的挑剔部分(假设您正在使用它)是缺少 raw_input。使用input,无论用户输入什么,都会被评估为 Python 代码。因此,用户必须输入“q”或“r”。但是,避免用户错误的一种方法(如果玩家只输入qr,没有引号)是用这些值初始化这些变量。

    【讨论】:

    • 天哪!!!!!!!谢谢!!但我认为他不会接受这一点,因为我们还没有学习大部分代码,可能会给我一个 F
    • 没问题:)。但是,您可以告诉您的教授您查过它(谷歌搜索对任何语言都有很大帮助)。如果他们帮助了你,这是接受答案的标准协议,只是说:P
    【解决方案4】:

    这是一个蟒蛇骰子滚轮 它要求一个 d(int) 并返回一个介于 1 和 (d(int)) 之间的随机数。 它返回没有 d 的骰子,然后打印随机数。它可以做 2d6 等。如果你输入 q 或退出,它就会中断。

    import random 
    import string
    import re
    from random import randint
    
    def code_gate_3(str1):
      if str1.startswith("d") and three == int:
        return True
      else:
        return False
    
    def code_gate_1(str1):
        if str1.startswith(one):
          return True
        else:
          return False
    
    def code_gate_2(str2):
        pattern = ("[0-9]*[d][0-9]+")
        vvhile_loop = re.compile(pattern)
        result = vvhile_loop.match(str1)
        if result:
          print ("correct_formatting")
        else:
          print ("incorrect_formattiing")
    
    while True:
      str1 = input("What dice would you like  to roll? (Enter a d)")
      one, partition_two, three = str1.partition("d")
      pattern = ("[0-9]*[d][0-9]+")
      if str1 == "quit" or str1 == "q":
        break
      elif str1.startswith("d") and three.isdigit():
        print (random.randint(1, int(three)))
        print (code_gate_2(str1))
      elif code_gate_1(str1) and str1.partition("d") and one.isdigit():
        for _ in range(int(one)):
          print (random.randint(1, int(three)
      print (code_gate_2(str1))
      elif (str1.isdigit()) != False:
        break
      else:
        print (code_gate_2(str1))
      print ("Would you like to roll another dice?")
      print ("If not, type 'q' or 'quit'.")
    
    print ("EXITING>>>___")
    

    【讨论】:

      【解决方案5】:

      这是最简单的答案之一。

      import random
      
      def rolling_dice():
      
          min_value = 1
      
          max_value = 6
      
          roll_again = "yes"
      
          while roll_again == "yes" or roll_again == "Yes" or roll_again == "Y" or roll_again == "y" or roll_again == "YES":
              print("Rolling dices...")
              print("The values are...")
              print(random.randint(min_value, max_value))
              print(random.randint(min_value, max_value))
              roll_again = input("Roll the dices again? ")
      
      rolling_dice()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-12
        • 1970-01-01
        • 2021-11-03
        • 1970-01-01
        • 2018-01-03
        • 2019-03-09
        • 1970-01-01
        相关资源
        最近更新 更多