python-如何找到完成蛇和梯子游戏所需的平均掷骰数?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-如何找到完成蛇和梯子游戏所需的平均掷骰数?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2386字,纯文字阅读大概需要4分钟。
内容图文
![python-如何找到完成蛇和梯子游戏所需的平均掷骰数?](/upload/InfoBanner/zyjiaocheng/692/b7ff371b153e4ef8bba8111ae8870709.jpg)
编写代码以模拟一名玩家的游戏,并计算完成游戏所需的掷骰子次数.应该允许用户指定模拟游戏的数量,并且代码应该计算每个游戏掷骰子的平均数量.
#Snakes and Ladders simulation
import random #importing the random function to be able to use it later on
counterposition = 0 #setting counterposition and diceroll to 0
currentDiceroll = 0
def diceroll (): #when user rolls the 1-6 dice this does it randomly
return random.randint (1,6)
userInput = int(input("How many games would you like to play snakes and ladders?"))
for i in range (userInput):
currentDiceroll = diceroll()
print("The currentDiceroll is", currentDiceroll)
if counterposition == 1: #all the if statements show what happens if the one player lands on a snake or a ladder
counterposition = counterposition + 37
if counterposition == 4:
counterposition = counterposition + 10
if counterposition == 9:
counterposition = counterposition + 22
if counterposition == 21:
counterposition = counterposition + 21
if counterposition == 28:
counterposition = counterposition + 56
if counterposition == 51:
counterposition = counterposition + 16
if counterposition == 72:
counterposition = counterposition + 19
if counterposition == 80:
counterposition = counterposition + 19
if counterposition == 17:
counterposition = counterposition - 10
if counterposition == 54:
counterposition = counterposition - 20
if counterposition == 63:
counterposition = counterposition - 4
if counterposition == 64:
counterposition = counterposition - 4
if counterposition == 87:
counterposition = counterposition - 51
if counterposition == 92:
counterposition = counterposition - 19
if counterposition == 95:
counterposition = counterposition - 20
if counterposition == 98:
counterposition = counterposition - 19
if counterposition >= 100:
print ("Congratulations end of game")
counterposition = counterposition + currentDiceroll
print("the counter position is", counterposition)
解决方法:
您编写的代码只会掷骰子一次.您需要不断滚动,直到赢得比赛为止.最好创建一个可以玩一次游戏并返回所需掷骰数的函数.
def playGame():
counterPosition = 0
numberOfRolls = 0
while (counterPosition < 100):
numberOfRolls += 1
currentDiceroll = diceroll()
print("The currentDiceroll is", currentDiceroll)
counterPosition += currentDiceroll
# your if statements go here
return numberOfRolls
然后,您可以多次调用此函数.
totalDiceRolls = 0
for i in range(userInput):
totalDiceRolls += playGame()
avgRolls = totalDiceRolls / userInput
内容总结
以上是互联网集市为您收集整理的python-如何找到完成蛇和梯子游戏所需的平均掷骰数?全部内容,希望文章能够帮你解决python-如何找到完成蛇和梯子游戏所需的平均掷骰数?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。
来源:【匿名】