编写代码来模拟一个玩家的游戏,并计算完成游戏所需的掷骰子次数。用户应该被允许指定模拟游戏的数量,代码应该计算出每个游戏掷骰子的平均数量。在
#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)
这不是您明确要求的,但是您的代码与所有这些
if
语句有点重复。你可以做的一件事是把移动的概念化为按模滚给定的量移动,然后是一个“bump”,大多数方块是0,梯子开始的方块是正数,蛇顶部的方块是负数。字典是bumps的自然数据结构,只显式地存储负的和正的bump。dictionary方法get()
可用于返回bump(如果最后一个方块是字典中的一个键)或返回默认的0
(如果不是的话)。那么单个游戏模拟可以是:预计转鼓数量可通过以下公式估算:
^{pr2}$上面的一些内容可能涉及到您还没有看到的东西,但是当您发现自己在编写几乎完全相同的代码时,您应该尽可能简化它。重复代码不是Python式的。在
如果您还没有研究过字典,但是已经研究过列表,那么您可以使
bump
一个包含101个项目的数组,初始化为:bump = [0]*101
(101个零),然后进行一系列赋值,如bump[1] = 37
,bump[4] = 10
,等等,然后替换该行:更简单的说法是:
实际上是说“在当前位置加上滚动加上产生的凹凸”
代码
^{pr2}$在sum函数内部使用生成器表达式。如果你还不熟悉这些,你可以在一个显式的循环中添加它们,就像A.Sokol的优秀答案一样
你写的代码只掷骰子一次。你必须继续努力直到你赢了比赛。最好创建一个函数,该函数只玩一次游戏,并返回所需的掷骰子数。在
然后您可以任意调用这个函数。在
^{pr2}$相关问题 更多 >
编程相关推荐