如何在Python中模拟掷骰子?

3 投票
5 回答
17576 浏览
提问于 2025-04-17 14:16

这是我第一次在这里发帖。我正在用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

我想发一张图片,但它不让我发。


我只想对所有回答我问题的人说声谢谢!你们的每一个回答都很有帮助!**多亏了你们,我的项目才能按时完成!谢谢你们!

5 个回答

1

我不太确定哪种骰子有8个数字,我用的是6面的。

一种方法是使用洗牌。

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

每次都会随机打乱这个列表,然后取第一个。

1
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循环会一直执行下面的代码(也就是缩进的部分),直到条件变成假为止。所以,如果玩家输入了q,循环就会停止,然后程序会继续执行下一部分。你可以查看这个链接了解更多:Python 循环 --- Tutorials Point

关于Python 3(假设你在用这个版本),有一点需要注意的是没有raw_input这个函数。使用input时,用户输入的内容会被当作Python代码来处理。因此,用户必须输入'q'或者'r'。不过,为了避免用户出错(比如玩家只输入qr,没有加引号),可以在开始时给这些变量赋值。

1

简单使用:

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)

撰写回答