用Python模拟掷骰子?

2024-04-26 14:08:46 发布

您现在位置:Python中文网/ 问答频道 /正文

第一次在这里写作。。我正在用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

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


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


Tags: orof程序gameplayyoursorandom
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,不带引号)的方法是用这些值初始化这些变量。

简单使用:

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)

不知道哪种骰子有8个数字,我用了6。

一种方法是使用shuffle。

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

每次,它都会随机地洗牌列表并取第一个。

相关问题 更多 >