Python 循环骰子程序
我正在做一个程序,任务是编写一个程序,模拟一对六面骰子的掷法(它将产生2到12个) 这段代码模拟了掷骰子游戏的第一次掷骰子 如果用户掷2、3或12,则会输(输出骰子总数和“您输了”) 如果用户掷7,他们赢(输出骰子总数和“你赢了”) 如果他们抛出其他任何东西,该值就是他们的“点数”(输出骰子总数) 无输入文件,无输出文件,提示用户输入掷骰子的次数。辊是分开的,相互独立 名为roll_dices的函数将返回两个随机数,表示两个骰子的滚动。random.randint(1,6)是Python库函数,它返回一个介于1和6之间(包括1和6)的随机数。使用随机函数,因为掷骰子的数字应该是随机的 名为win_lost的函数将确定用户是赢还是输。此函数应返回赢或输的指示以及掷骰子的值 这是我到目前为止的代码,没有输出Python 循环骰子程序,python,Python,我正在做一个程序,任务是编写一个程序,模拟一对六面骰子的掷法(它将产生2到12个) 这段代码模拟了掷骰子游戏的第一次掷骰子 如果用户掷2、3或12,则会输(输出骰子总数和“您输了”) 如果用户掷7,他们赢(输出骰子总数和“你赢了”) 如果他们抛出其他任何东西,该值就是他们的“点数”(输出骰子总数) 无输入文件,无输出文件,提示用户输入掷骰子的次数。辊是分开的,相互独立 名为roll_dices的函数将返回两个随机数,表示两个骰子的滚动。random.randint(1,6)是Python库函数,
import random
# Variables
AGAIN = int(input("How many times do you want to roll the dice "))
MIN = 1
MAX = 6
def main():
roll_dice(AGAIN)
win_lost(dices)
def roll_dice(AGAIN):
for dice in range(AGAIN):
X = random.randint(MIN, MAX)
Y = random.randint(MIN,MAX)
dices = X + Y
return dices
def win_lost(dices):
if dices == 2 or dices == 3 or dices == 12:
print('You rolled ', dices, '. You lost.', sep ='')
elif dice == 7:
print('You rolled 7. You win')
else:
print('You earned', dices, 'points.')
# Calling the main function
main()
需要换成
elif dices == 7:
循环
def win_lost(dices):
if dices == 2 or dices == 3 or dices == 12:
print('You rolled ', dices, '. You lost.', sep ='')
elif dices == 7:
print('You rolled 7. You win')
else:
print('You earned', dices, 'points.')
REPEAT = input("Do you want go again? (Y/N)")
if REPEAt == Y:
main()
else:
pass
对代码进行适度的更改
import random
def main(rolls):
'''
Input is the number of rolls
'''
# Variables for min, max dice values
MIN = 1
MAX = 6
result = []
for rolls in range(rolls):
# loop rolls times
roll = roll_dice(MIN, MAX)
win_lost(roll)
def roll_dice(MIN, MAX):
' Generate dice total '
X = random.randint(MIN, MAX)
Y = random.randint(MIN, MAX)
return X + Y
def win_lost(dices):
' Message of win/lost/points based upon dices total '
if dices == 2 or dices == 3 or dices == 12:
print('You rolled ', dices, '. You lost.', sep ='')
elif dices == 7:
print('You rolled 7. You win')
else:
print('You earned', dices, 'points.')
# Get number of rolls
rolls = int(input("How many times do you want to roll the dice "))
# Calling the main function
main(rolls)
测试
How many times do you want to roll the dice 5
You rolled 7. You win
You earned 5 points.
You earned 5 points.
You earned 11 points.
You earned 10 points.
您不是从
win\u lost(骰子)
中得到了一个错误吗?您从未分配过dice
变量。为什么roll\u dice()
需要循环?您只返回最后一对骰子。您需要dies=roll\u dice(再次)
@Barma我应该把它放在哪里?放在main()
而不是roll\u dice(再次)
非常感谢您提供这部分内容,但我仍然有错误message@DOC--如果这有助于回答你的问题,别忘了投票表决。
How many times do you want to roll the dice 5
You rolled 7. You win
You earned 5 points.
You earned 5 points.
You earned 11 points.
You earned 10 points.